forked from PostFixJS/PostFixJS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDictStack.js
More file actions
101 lines (91 loc) · 2.29 KB
/
DictStack.js
File metadata and controls
101 lines (91 loc) · 2.29 KB
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
/**
* Dictionary stack used by the interpreter to store dictionaries.
* There is always one dictionary active at a time. A new dictionary is added
* when a lambda function (Lam) is being executed.
*/
class DictStack {
/**
* Create a new, empty dictionary stack.
*/
constructor () {
this._dict = {}
this._stack = [this._dict]
}
/**
* Get the number of dictionaries on this dictionary stack.
*/
get count () {
return this._stack.length
}
/**
* Put a value into the active dictionary, overwrite an existing value.
* @param {string} key Name of the dictionary entry
* @param {Obj} value Value
*/
put (key, value) {
if (this._dict[key]) {
this._dict[key].refs--
}
this._dict[key] = value
value.refs++
}
/**
* Get a value from the active dictionary.
* @param {string} key Name of the dictionary entry
* @returns {Obj} Dictionary entry or null if not found
*/
get (key) {
return this._dict[key]
}
/**
* Push a dictionary on the dictionary stack and use it as active dictionary.
* @param {object} dict Dictionary object
*/
pushDict (dict) {
this._stack.push(dict)
this._dict = dict
}
/**
* Pop the topmost dictionary from the dictionary stack and use the next one as active dictionary.
*/
popDict () {
this._stack.pop()
this._dict = this._stack[this._stack.length - 1]
}
/**
* Copy the active dictionary and return it.
* @returns {object} Copy of the dictionary object
*/
copyDict () {
for (const obj of Object.values(this._dict)) {
obj.refs++
}
return Object.assign({}, this._dict)
}
/**
* Clear the dictionary stack and create a new empty active dictionary.
*/
clear () {
this._dict = {}
this._stack = [this._dict]
}
/**
* Get the dictionary stack. The first element is the bottom-most dict.
* @return {object[]} The dictionary stack
*/
getDicts () {
return this._stack
}
/**
* Create a copy of this dictionary stack that only includes
* the topmost dictionary.
* @returns {DictStack} New dictionary stack with a copy of the topmost dictionary
*/
copyCurrent () {
const copy = new DictStack()
copy._dict = this.copyDict()
copy._stack = [copy._dict]
return copy
}
}
module.exports = DictStack