immutable-path
Version:
Immutable `get`, `set`, `has`, `unset` deep path operations libraray for object, array and `Map`.
46 lines • 2.02 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const has_1 = __importDefault(require("./has"));
const get_1 = __importDefault(require("./get"));
const helper_1 = require("./helper");
/**
* If value is a function, executes it and returns it's result. Otherwise returns value.
*
* @ignore
* @param root is the root object. Root is provided to given function.
* @param source is the object index/key is in. Source is provided to given function.
* @param key is the index/key to be set. Key is provided to given function.
* @param oldValue is current value of index/key. Old value is provided to given function.
* @param newValue is the new value or function to be executed.
* @returns value to be set.
*/
function getValue(root, source, key, oldValue, newValue) {
return typeof newValue === "function" ? newValue(oldValue, key, source, root) : newValue;
}
/**
* (Immutable) Sets value of given key/index of object/array/Map. Does not change original object/array/Map.
* Returns new value.
*
* @ignore
* @param source is the array/object/Map to update.
* @param key is the key/index to change value of.
* @param value is the value to set.
* @returns new object/array/Map.
*/
function _set(source, key, value, root) {
const currentValue = get_1.default(source, key);
if (has_1.default(source, key) && currentValue === value)
return source;
if (source instanceof Map)
return new Map(source).set(key, getValue(root, source, key, currentValue, value));
if (Array.isArray(source) && !helper_1.doesLookLikeArrayIndex(key) && typeof key !== "function")
return source;
const newSource = Object.assign(Array.isArray(source) ? [] : {}, source);
newSource[key] = getValue(root, source, key, currentValue, value);
return newSource;
}
exports.default = _set;
//# sourceMappingURL=set.js.map