@bemedev/decompose
Version:
Decompose object and so more
41 lines (40 loc) • 1.39 kB
JavaScript
import { isArrayIndex, nextDefault, parseIndex, splitKey } from "../helpers.js";
//#region src/contexts/assign.ts
const _assignByKey = (obj, key, value) => {
const [first, ...rest] = splitKey(key);
const out = obj ?? nextDefault(first);
if (rest.length === 0) {
if (isArrayIndex(first)) {
let idx = parseIndex(first);
if (idx > out.length) idx = out.length;
out[idx] = value;
} else out[first] = value;
return out;
}
const nextKey = rest.join(".");
const next = rest[0];
const _nextDefault = nextDefault(next);
if (isArrayIndex(first)) {
let idx = parseIndex(first);
if (idx > out.length) idx = out.length;
out[idx] = _assignByKey(out[idx] ?? _nextDefault, nextKey, value);
} else out[first] = _assignByKey(out[first] ?? _nextDefault, nextKey, value);
return out;
};
/**
* Assigns a value to a path in an object.
* @param obj The object to assign the value to
* @param path The key to assign the value to, can be a nested key (e.g. 'a.b.c')
* @param value The value to assign to the key
* @returns The modified object with the value assigned to the specified key
*
* @see {@linkcode Decompose} for more details on object decomposition.
*/
const assignByKey = (obj, path, value) => {
return _assignByKey(obj, path, value);
};
assignByKey.low = assignByKey;
assignByKey.typed = assignByKey;
//#endregion
export { assignByKey };
//# sourceMappingURL=assign.js.map