@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
56 lines (50 loc) • 1.84 kB
JavaScript
import { isArray, isObject, isValid, merge } from "@visactor/vutils";
export function set(object, path, value) {
return null == object ? object : baseSet(object, path, value);
}
export 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 (!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 = isValid(objValue) ? objValue : isIndex(path[index + 1]) ? [] : {};
}
isValid(nested[key]) ? merge(nested, {
[key]: newValue
}) : nested[key] = newValue, nested = nested[key];
}
return object;
}
function baseDelete(object, pathString) {
if (!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 ? isArray(nested) ? nested.splice(Number(key), 1) : delete nested[key] : nested = nested[key]);
}
return object;
}
//# sourceMappingURL=set.js.map