UNPKG

@visactor/vmind

Version:

<div align="center"> <a href="https://github.com/VisActor#gh-light-mode-only" target="_blank"> <img alt="VisActor Logo" width="200" src="https://github.com/VisActor/.github/blob/main/profile/logo_500_200_light.svg"/> </a> <a href="https://githu

64 lines (55 loc) 2.07 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: !0 }), exports.deleteByPath = exports.set = void 0; const vutils_1 = require("@visactor/vutils"); function set(object, path, value) { return null == object ? object : baseSet(object, path, value); } function deleteByPath(object, path) { return null == object ? object : baseDelete(object, path); } function castPath(path, object) { if (object[path]) return [ path ]; const arr = []; return path.split(".").forEach((entry => { const res = /\[(\d)\]/g.exec(entry); res ? (arr.push(entry.replace(res[0], "")), arr.push(res[1])) : arr.push(entry); })), arr; } function isIndex(key) { return /\d/.exec(key); } function baseSet(object, pathString, value) { if (!(0, vutils_1.isObject)(object)) return object; const path = castPath(pathString, object); let index = -1; const length = path.length, lastIndex = length - 1; let nested = object; for (;null != nested && ++index < length; ) { const key = path[index]; let newValue = value; if (index !== lastIndex) { const objValue = nested[key]; newValue = (0, vutils_1.isValid)(objValue) ? objValue : isIndex(path[index + 1]) ? [] : {}; } (0, vutils_1.isValid)(nested[key]) ? (0, vutils_1.merge)(nested, { [key]: newValue }) : nested[key] = newValue, nested = nested[key]; } return object; } function baseDelete(object, pathString) { if (!(0, vutils_1.isObject)(object)) return object; const path = castPath(pathString, object); let index = -1; const length = path.length, lastIndex = length - 1; let nested = object; for (;null != nested && ++index < length; ) { const key = path[index]; key in nested && (index === lastIndex ? (0, vutils_1.isArray)(nested) ? nested.splice(Number(key), 1) : delete nested[key] : nested = nested[key]); } return object; } //# sourceMappingURL=set.js.map exports.set = set, exports.deleteByPath = deleteByPath;