@surface/path-matcher
Version:
Provides path matching capabilities.
55 lines (54 loc) • 1.6 kB
JavaScript
export const last = (elements) => elements[elements.length - 1];
export default class Context {
type;
start;
tokens;
pending = [];
parent;
children = [];
rolledBack = false;
constructor(type, parent) {
this.type = type;
this.parent = parent;
this.tokens = this.parent?.tokens ?? [];
this.parent?.children.push(this);
this.start = this.tokens.length;
}
discard() {
this.children.forEach(x => x.discard());
this.tokens.splice(this.start);
}
inside(context, depth = Number.MAX_VALUE) {
return !!this.lookup(context, depth);
}
lookup(context, depth = Number.MAX_VALUE) {
if (this.type != context) {
let parent = this.parent;
let index = 0;
while (parent && index < depth) {
if (parent.type == context) {
return parent;
}
parent = parent.parent;
index++;
}
return null;
}
return this;
}
push(token, rollback) {
this.tokens.push(token);
if (rollback != undefined) {
this.pending.push({ index: this.tokens.length - 1, rollback });
}
}
rollback(recursive = false) {
for (const token of this.pending) {
this.tokens[token.index] = token.rollback;
}
this.rolledBack = true;
if (recursive) {
this.children.forEach(x => x.rollback(recursive));
}
}
}