UNPKG

attrpath

Version:
78 lines 2.3 kB
/** * Copyright © 2020 2021 2022 7thCode.(http://seventh-code.com/) * This software is released under the MIT License. * opensource.org/licenses/mit-license.php */ "use strict"; import { AttributeParser, FormulaParser } from './parser'; import { ParserStream } from './stream'; import { BaseHandler, Updater, ValueHandler } from './handler'; export { AttributeParser, FormulaParser, ParserStream, BaseHandler, ValueHandler }; /** * AttrPath */ export class AttrPath { /** * traverse * * @remarks * Traverse an object's attributes to get its value. * * @param target - Object * @param path - ObjectPath e.g. ".x.Y.z[1]" * @param default_value - The value to return if there is no corresponding value in the object path. default is "undefined" * @returns The value at the position of the path. * */ static traverse(target, path, default_value = undefined) { let result = default_value; if (target) { const handler = new ValueHandler(target); if (new AttributeParser(handler, new ParserStream(path)).parse_path()) { if (handler.value) { result = handler.value; } } if (default_value && typeof default_value === 'function') { default_value(result); return null; } } return result; } /* * update * * @remarks * * @param target - Object * @param path - ObjectPath e.g. ".x.Y.z[1]" * @param value - value to update. * @returns - update successful * * */ static update(target, path, value) { let result = false; if (target) { const updater = new Updater(target, value); if (new AttributeParser(updater, new ParserStream(path)).parse_path()) { result = (updater.value); } } return result; } /** * is_valid * * @remarks * Is the path grammatically correct? * * @param path - ObjectPath e.g. ".x.Y.z[1]" * @returns true/false * */ static is_valid(path) { return new AttributeParser(null, new ParserStream(path)).parse_path(); } } //# sourceMappingURL=index.js.map