UNPKG

mahler

Version:

A automated task composer and HTN based planner for building autonomous system agents

80 lines 2.39 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.View = void 0; const is_array_index_1 = require("./is-array-index"); const path_1 = require("./path"); const pointer_1 = require("./pointer"); /** * Returns a view builder function from a given path */ function createView(ref, path) { const parts = path_1.Path.split(path); // Save the last element of the path so we can delete it const last = parts.pop(); const obj = ref._; let parent = obj; for (const p of parts) { if (!Array.isArray(parent) && typeof parent !== 'object') { throw new pointer_1.InvalidPointer(path, obj); } if (Array.isArray(parent) && !(0, is_array_index_1.isArrayIndex)(p)) { throw new pointer_1.InvalidPointer(path, obj); } if (!(p in parent)) { // Cannot create a view if the path does not exist throw new pointer_1.InvalidPointer(path, obj); } parent = parent[p]; } let pointer = parent; if (last != null) { if (!Array.isArray(parent) && typeof parent !== 'object') { throw new pointer_1.InvalidPointer(path, obj); } if (Array.isArray(parent) && !(0, is_array_index_1.isArrayIndex)(last)) { throw new pointer_1.InvalidPointer(path, obj); } pointer = parent[last]; } const view = { _: pointer, delete() { if (last != null) { if (Array.isArray(parent)) { parent.splice(+last, 1); } else { delete parent[last]; } } }, }; function update() { if (last != null) { if (Array.isArray(parent)) { parent.splice(+last, 1, view._); } else { parent[last] = view._; } } else { ref._ = view._; } } // We return a proxy so changes to the view._ value change // the parent's value return new Proxy(view, { set(target, prop, value) { const res = Reflect.set(target, prop, value); if (res) { update(); } return res; }, }); } exports.View = { from: createView, }; //# sourceMappingURL=view.js.map