-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontext.js
More file actions
33 lines (28 loc) · 958 Bytes
/
context.js
File metadata and controls
33 lines (28 loc) · 958 Bytes
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
// ContextStack gives safe access to stack values which are:
// - referenced using '@'
// - used in chains, iteration, and error handling
class ContextStack {
// it should never point to the array it was given, always copy
constructor(stack = []) {
this.stack = [].concat(stack)
}
get(depth) {
if (depth < 1) throw new Error('Depth must be 1 or greater')
const stackRef = this.stack.length - depth
if (stackRef < 0) {
const ats = '@'.repeat(depth)
throw new Error(`${ats} not available - context not deep enough (only ${this.stack.length} levels available)`)
}
return this.stack[stackRef]
}
getCurrent() {return this.get(1)}
setCurrent(value) {
const stackRef = this.stack.length - 1
if (stackRef < 0) throw new Error('Invalid stack reference.')
this.stack[stackRef] = value
}
extend(value) {
return new ContextStack(this.stack.concat([value]))
}
}
export default ContextStack