-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathVariableScope.ts
78 lines (73 loc) · 2.35 KB
/
VariableScope.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
/**
* A class to get and set variables according to a scope name
*/
export class VariableScope {
private scopes: Record<string, Record<string, any>> = {};
private currentScope: Record<string, any> = {};
private currentScopeName: string = '';
constructor(initialScope: Record<string, any> = {}) {
this.scopes[''] = initialScope;
this.setScope('');
}
/**
* Set the current scope
* @param scopeName The name of the scope to set as current
*/
public setScope(scopeName: string) {
if (!(scopeName in this.scopes)) {
this.scopes[scopeName] = {};
}
this.currentScope = this.scopes[scopeName];
this.currentScopeName = scopeName;
return this;
}
/**
* Get the current scope name
* @returns The name of the current scope
*/
public getScopeName(): string {
return this.currentScopeName;
}
/**
* Get the current scope
* @returns The current scope
*/
public getScope(scopeName: string): VariableScope {
const scope = new VariableScope();
scope.scopes = this.scopes;
scope.setScope(scopeName);
return scope;
}
public getVariables(): Record<string, any> {
return { ...this.scopes[''], ...this.currentScope };
}
public getVariablesForScope(scopeName: string): Record<string, any> {
return { ...this.scopes[''], ...this.scopes[scopeName] };
}
/**
* Get the value of a variable in the current scope
* @param variableName The name of the variable to get
* @returns The value of the variable
*/
public get(variableName: string): any {
return this.currentScope[variableName] === undefined
? this.scopes['']![variableName]
: this.currentScope[variableName];
}
/**
* Set the value of a variable in the current scope
* @param variableName The name of the variable to set
* @param value The value to set the variable to
*/
public setForScope(scopeName: string, variableName: string, value: any) {
if (!(scopeName in this.scopes)) {
this.scopes[scopeName] = {};
}
this.scopes[scopeName][variableName] = value;
return this;
}
public set(variableName: string, value: any) {
this.currentScope[variableName] = value;
return this;
}
}