avocado-old/packages/behavior/item/traversal.js

85 lines
1.7 KiB
JavaScript
Raw Normal View History

2019-03-17 23:45:48 -05:00
import {fromJSON as behaviorItemFromJSON} from './registry';
export class Traversal {
constructor() {
2019-04-15 22:47:25 -05:00
this.hash = undefined;
2019-03-17 23:45:48 -05:00
this.steps = [];
2019-04-09 09:42:29 -05:00
this.value = undefined;
2019-03-17 23:45:48 -05:00
}
2019-04-25 00:48:53 -05:00
clone(other) {
this.steps = other.steps.map((step) => {
switch (step.type) {
case 'key':
return step;
case 'invoke':
return {
type: 'invoke',
args: step.args.map((arg, index) => {
const Item = arg.constructor;
const item = new Item();
item.clone(arg);
return item;
}),
};
}
});
if (other.value) {
this.value = other.value.clone();
}
if (other.hash) {
this.hash = other.hash;
}
}
2019-03-17 23:45:48 -05:00
fromJSON(json) {
this.steps = json.steps.map((step) => {
switch (step.type) {
case 'key':
return step;
case 'invoke':
return {
type: 'invoke',
args: step.args.map((arg) => behaviorItemFromJSON(arg)),
};
}
});
2019-04-09 09:42:29 -05:00
if (json.value) {
this.value = behaviorItemFromJSON(json.value);
}
2019-04-15 22:47:25 -05:00
if (json.hash) {
this.hash = json.hash;
}
2019-03-17 23:45:48 -05:00
return this;
}
get(context) {
return this.traverse(context);
}
traverse(context) {
if (context) {
2019-04-15 22:47:25 -05:00
return context.traverse(this);
2019-03-17 23:45:48 -05:00
}
}
toJSON() {
return {
type: 'traversal',
steps: this.steps.map((step) => {
switch (step.type) {
case 'key':
return step;
case 'invoke':
return {
type: 'invoke',
args: step.args.map((arg) => arg.toJSON()),
};
}
}),
2019-04-09 09:42:29 -05:00
value: this.value ? this.value.toJSON() : undefined,
2019-03-17 23:45:48 -05:00
};
}
}