-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathexecute.ts
60 lines (53 loc) · 1.4 KB
/
execute.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { TargetLanguages, LogCallback, ExecuteOptions } from "./types";
import { num2hanzi, bool2hanzi } from "./parser";
export function isLangSupportedForEval(lang: TargetLanguages) {
if (lang !== "js")
throw new Error(
`Executing for target language "${lang}" is not supported in current environment`
);
return true;
}
function hanzinizeOuput(value: string) {
if (typeof value == "number") {
return num2hanzi(value);
} else if (typeof value == "boolean") {
return bool2hanzi(value);
} else if (Array.isArray(value)) {
return value.map(i => hanzinizeOuput(i)).join("。");
} else {
return value;
}
}
export function outputHanziWrapper(log: LogCallback, outputHanzi: boolean) {
return function output(...args) {
log(...args.map(i => (outputHanzi ? hanzinizeOuput(i) : i)));
};
}
export function evalCompiled(
compiledCode: string,
options: Partial<ExecuteOptions> = {}
) {
const {
outputHanzi = true,
scoped = false,
lang = "js",
output = console.log
} = options;
isLangSupportedForEval(lang);
let code = compiledCode;
(() => {
const _console_log = console.log;
console.log = outputHanziWrapper(output, outputHanzi);
try {
if (!scoped && "window" in this) {
window.eval(code);
} else {
eval(code);
}
} catch (e) {
throw e;
} finally {
console.log = _console_log;
}
})();
}