@bemedev/decompose
Version:
Decompose object and so more
42 lines (41 loc) • 1.56 kB
JavaScript
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_helpers = require("../helpers.cjs");
//#region src/contexts/assign.ts
const _assignByKey = (obj, key, value) => {
const [first, ...rest] = require_helpers.splitKey(key);
const out = obj ?? require_helpers.nextDefault(first);
if (rest.length === 0) {
if (require_helpers.isArrayIndex(first)) {
let idx = require_helpers.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 = require_helpers.nextDefault(next);
if (require_helpers.isArrayIndex(first)) {
let idx = require_helpers.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
exports.assignByKey = assignByKey;
//# sourceMappingURL=assign.cjs.map