avocado-old/packages/behavior/item/traversal.js
2019-09-08 04:18:11 -05:00

82 lines
1.6 KiB
JavaScript

import {fromJSON as behaviorItemFromJSON} from './registry';
export class Traversal {
static type() {
return 'traversal';
}
constructor() {
this.steps = [];
this.value = undefined;
}
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();
}
}
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)),
};
}
});
if (json.value) {
this.value = behaviorItemFromJSON(json.value);
}
return this;
}
get(context) {
return this.traverse(context);
}
traverse(context) {
if (context) {
return context.traverse(this);
}
}
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()),
};
}
}),
value: this.value ? this.value.toJSON() : undefined,
};
}
}