Skip to content

Instantly share code, notes, and snippets.

@a-x-
Last active February 6, 2018 19:07
Show Gist options
  • Select an option

  • Save a-x-/08b9660e63c9e467acef06730cf86a4d to your computer and use it in GitHub Desktop.

Select an option

Save a-x-/08b9660e63c9e467acef06730cf86a4d to your computer and use it in GitHub Desktop.
Immutable set like lodash.set but immutable with minimal updates
/**
* Immutable set like lodash.set but immutable with minimal updates
* @param {Object} o
* @param {String} path e.g. 'a.b.c'
* @param {*} val target value
*
* @example var o = {a: {b: 1}}, o_ = set(o, 'a.c', 2) // o_ ==== {a: {b: 1, c: 2}}; o is untouched
*
* @returns {Object}
*/
export default function set(o, path, val) {
const keys = path.split('.');
let isPathComplete = true;
const root = { ...o };
const deepestObject = keys.slice(0, keys.length - 1).reduce((o_, key) => {
if (!o_[key] || o_[key].toString() !== '[object Object]') isPathComplete = false;
if (!isPathComplete) return o_;
const o__ = { ...o_[key] };
Object.assign(o_, { [key]: o__ });
return o__;
}, root);
if (!isPathComplete) {
console.warn(new Error(`tried to set through incomplete key path "${ path }"`));
return o;
}
deepestObject[keys[keys.length - 1]] = val;
return root;
}
@a-x-

a-x- commented Feb 6, 2018

Copy link
Copy Markdown
Author

Пересоздаёт объекты только по пути (path)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment