UNPKG

@edirect/form-engine

Version:

Achieve form logic reusage with forms expressed in json format.

50 lines (49 loc) 1.44 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getValueByPath = exports.encapsulateIn = void 0; /** * Encapsulates in a given object, at a given path the provided value * * @example * ORIGINAL object * * encapsulateIn({maintain: 'spread_me'}, 'a.b.c','test') * * RESULT * * { * maintain: 'spread_me', * c: 'test * } * } * * @param origin - The original object where the new value will be appended * @param path - The path at which the new value will be placed * @param value - The new value * @returns One new object with the new value at the provided path merged with the given object */ const encapsulateIn = (origin, path, value) => { const parts = path.split('.'); if (parts.length === 1) { return Object.assign(Object.assign({}, origin), { [path]: value }); } const getNewPart = (parts, subObject) => { const clonedParts = [...parts]; clonedParts.splice(0, 1); const part = parts.length !== 1 ? getNewPart(clonedParts, subObject ? subObject[parts[0]] : {}) : value; return Object.assign(Object.assign({}, subObject), { [parts[0]]: part }); }; return getNewPart(parts, origin); }; exports.encapsulateIn = encapsulateIn; const getValueByPath = (object = {}, path = '') => { const parts = path.split('.'); return parts.reduce((acc, part) => (acc || {})[part], object); }; exports.getValueByPath = getValueByPath;