-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
setupNamespace.ts
52 lines (47 loc) · 1.27 KB
/
setupNamespace.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
import { GlobalsOption } from '../../rollup/types';
import { property } from './sanitize';
export default function setupNamespace(
name: string,
root: string,
globals: GlobalsOption,
compact: boolean
) {
const parts = name.split('.');
if (globals) {
parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
}
const _ = compact ? '' : ' ';
parts.pop();
let acc = root;
return (
parts
.map(
part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}${compact ? '' : ';'}`)
)
.join(compact ? ',' : '\n') + (compact && parts.length ? ';' : '\n')
);
}
export function assignToDeepVariable(
deepName: string,
root: string,
globals: GlobalsOption,
compact: boolean,
assignment: string
): string {
const _ = compact ? '' : ' ';
const parts = deepName.split('.');
if (globals) {
parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
}
const last = parts.pop();
let acc = root;
let deepAssignment = parts
.map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}`))
.concat(`${acc}${property(last)}`)
.join(`,${_}`)
.concat(`${_}=${_}${assignment}`);
if (parts.length > 0) {
deepAssignment = `(${deepAssignment})`;
}
return deepAssignment;
}