-
Notifications
You must be signed in to change notification settings - Fork 223
/
Copy pathutil.ts
102 lines (95 loc) · 2.07 KB
/
util.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
export function disambiguateNames<T>({
values,
getName,
setName,
}: {
values: T[];
getName: (value: T, index: number) => string;
setName: (value: T, name: string) => void;
}) {
const collisionCounter = new Map();
return values.map((value, index) => {
const name = handleReservedWord(getName(value, index));
const counter = collisionCounter.get(name);
if (counter === undefined) {
collisionCounter.set(name, 1);
return setName(value, name);
}
collisionCounter.set(name, counter + 1);
return setName(value, `${name}${counter}`);
});
}
const RESERVED_WORDS = new Set([
'await',
'break',
'case',
'catch',
'class',
'const',
'continue',
'debugger',
'delete',
'do',
'else',
'enum',
'export',
'extends',
'false',
'finally',
'function',
'if',
'implements',
'import',
'in',
'interface',
'let',
'new',
'package',
'private',
'protected',
'public',
'return',
'super',
'switch',
'static',
'this',
'throw',
'true',
'try',
'typeof',
'var',
'while',
'with',
'yield',
]);
export function handleReservedWord(name: string): string {
return RESERVED_WORDS.has(name) ? `${name}_` : name;
}
export function isTupleType(t: string) {
return t === 'tuple';
}
export function containsTupleType(t: string) {
return isTupleType(t) || isTupleArrayType(t) || isTupleMatrixType(t);
}
export function isTupleArrayType(t: string) {
return t.match(/^tuple\[([0-9]+)?\]$/);
}
export function isTupleMatrixType(t: string) {
return t.match(/^tuple\[([0-9]+)?\]\[([0-9]+)?\]$/);
}
export const unrollTuple = ({
path,
value,
}: {
path: string[];
index: number; // TODO: index is unused, do we really need it?
value: any;
}): { path: string[]; type: string }[] =>
value.components.reduce((acc: any[], component: any, index: number) => {
const name = component.name || `value${index}`;
return acc.concat(
component.type === 'tuple'
? unrollTuple({ path: [...path, name], index, value: component })
: [{ path: [...path, name], type: component.type }],
);
}, []);