UNPKG

@modern-kit/utils

Version:
30 lines (27 loc) 994 B
import { cloneDeep } from '../../common/cloneDeep/index.mjs'; import { hasProperty } from '../../validator/hasProperty/index.mjs'; import { isNil } from '../../validator/isNil/index.mjs'; import { get } from '../get/index.mjs'; function set(obj, path, value, options = {}) { const immutable = options?.immutable ?? false; const clonedObj = immutable ? cloneDeep(obj) : obj; const resolvedPath = path.replace(/\?/g, ""); const paths = resolvedPath.split("."); let current = clonedObj; for (let i = 0; i < paths.length - 1; i++) { const currentPath = paths[i]; if (!hasProperty(current, currentPath) || isNil(current[currentPath])) { current[currentPath] = {}; } current = current[currentPath]; } const lastPath = paths[paths.length - 1]; if (typeof value === "function") { current[lastPath] = value(get(clonedObj, resolvedPath)); } else { current[lastPath] = value; } return clonedObj; } export { set }; //# sourceMappingURL=index.mjs.map