Last active
February 6, 2018 19:07
-
-
Save a-x-/08b9660e63c9e467acef06730cf86a4d to your computer and use it in GitHub Desktop.
Immutable set like lodash.set but immutable with minimal updates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Пересоздаёт объекты только по пути (path)