This repository has been archived by the owner on Feb 8, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate.ts
61 lines (53 loc) · 1.97 KB
/
create.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
61
// Creating and Printing a TypeScript AST
// https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#creating-and-printing-a-typescript-ast
// outputs:
// export function factorial(n): number {
// if (n <= 1) {
// return 1;
// }
// return n * factorial(n - 1);
// }
import ts = require("typescript");
function makeFactorialFunction() {
const functionName = ts.createIdentifier("factorial");
const paramName = ts.createIdentifier("n");
const parameter = ts.createParameter(
/*decorators*/ undefined,
/*modifiers*/ undefined,
/*dotDotDotToken*/ undefined,
paramName);
const condition = ts.createBinary(
paramName,
ts.SyntaxKind.LessThanEqualsToken,
ts.createLiteral(1));
const ifBody = ts.createBlock(
[ts.createReturn(ts.createLiteral(1))],
/*multiline*/ true)
const decrementedArg = ts.createBinary(paramName, ts.SyntaxKind.MinusToken, ts.createLiteral(1))
const recurse = ts.createBinary(
paramName,
ts.SyntaxKind.AsteriskToken,
ts.createCall(functionName, /*typeArgs*/undefined, [decrementedArg]));
const statements = [
ts.createIf(condition, ifBody),
ts.createReturn(
recurse
),
];
return ts.createFunctionDeclaration(
/*decorators*/ undefined,
/*modifiers*/[ts.createToken(ts.SyntaxKind.ExportKeyword)],
/*asteriskToken*/ undefined,
functionName,
/*typeParameters*/ undefined,
[parameter],
/*returnType*/ ts.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
ts.createBlock(statements, /*multiline*/ true),
)
}
const resultFile = ts.createSourceFile("someFileName.ts", "", ts.ScriptTarget.Latest, /*setParentNodes*/ false, ts.ScriptKind.TS);
const printer = ts.createPrinter({
newLine: ts.NewLineKind.LineFeed,
});
const result = printer.printNode(ts.EmitHint.Unspecified, makeFactorialFunction(), resultFile);
console.log(result);