Skip to main content
Module

x/ramda/source/modifyPath.js

:ram: Practical functional Javascript
Latest
File
import _curry3 from './internal/_curry3.js';import _isArray from './internal/_isArray.js';import _isObject from './internal/_isObject.js';import _has from './internal/_has.js';import _assoc from './internal/_assoc.js';import _modify from './internal/_modify.js';

/** * Creates a shallow clone of the passed object by applying an `fn` function * to the value at the given path. * * The function will not be invoked, and the object will not change * if its corresponding path does not exist in the object. * All non-primitive properties are copied to the new object by reference. * * @func * @memberOf R * @category Object * @sig [Idx] -> (v -> v) -> {k: v} -> {k: v} * @param {Array} path The path to be modified. * @param {Function} fn The function to apply to the path. * @param {Object} object The object to be transformed. * @return {Object} The transformed object. * @example * * const person = {name: 'James', address: { zipCode: '90216' }}; * R.modifyPath(['address', 'zipCode'], R.reverse, person); //=> {name: 'James', address: { zipCode: '61209' }} * * // Can handle arrays too * const person = {name: 'James', addresses: [{ zipCode: '90216' }]}; * R.modifyPath(['addresses', 0, 'zipCode'], R.reverse, person); //=> {name: 'James', addresses: [{ zipCode: '61209' }]} */var modifyPath = _curry3(function modifyPath(path, fn, object) { if ((!_isObject(object) && !_isArray(object)) || path.length === 0) { return object; }
var idx = path[0]; if (!_has(idx, object)) { return object; }
if (path.length === 1) { return _modify(idx, fn, object); }
var val = modifyPath(Array.prototype.slice.call(path, 1), fn, object[idx]); if (val === object[idx]) { return object; } return _assoc(idx, val, object);
});export default modifyPath;