-
Notifications
You must be signed in to change notification settings - Fork 0
/
Environment.js
54 lines (47 loc) · 1.16 KB
/
Environment.js
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
/**
* Environment: name storage.
*/
class Environment {
/**
* Creates an environment with the given record.
*/
constructor(record = {}, parent = null) {
this.record = record;
this.parent = parent;
}
/**
* Create a variable with the given name and value.
*/
define(name, value) {
this.record[name] = value;
return value;
}
/**
* Updates an existing variable.
*/
assign(name, value) {
this.resolve(name).record[name] = value;
return value;
}
/**
* Returns the value of a defined variable, or throws
* if the variable is not defined.
*/
lookup(name) {
return this.resolve(name).record[name];
}
/**
* Returns specific environment in which a variable is defined, or
* throws if a variable is not defined.
*/
resolve(name) {
if (this.record.hasOwnProperty(name)) {
return this;
}
if (this.parent == null) {
throw new ReferenceError(`Variable "${name}" is not defined.`);
}
return this.parent.resolve(name);
}
}
module.exports = Environment;