Last active
February 11, 2016 11:15
-
-
Save rohozhnikoff/d0e8dd2375050b6886f4 to your computer and use it in GitHub Desktop.
better assign for redux reducers
This file contains hidden or 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
import {isString, assign, reduce, map, keys, isPlainObject, isNull} from 'lodash'; | |
export const isKeyValue = function isKeyValue(h) { | |
return isPlainObject(h) && !isNull(h) | |
}; | |
export const assignAt = function assignAt(hash, path, newValue) { | |
if (isKeyValue(path)) { | |
return assign({}, hash, | |
keys(path).reduce((memo, key) => assignAt(memo, key, path[key]), hash) | |
); | |
} | |
isString(path) && (path = path.split('.')); | |
const val = hash[path[0]]; | |
return assign({}, hash, { | |
[path[0]]: (path.length === 1) | |
? isKeyValue(val) && isKeyValue(newValue) ? assign({}, val, newValue) : newValue | |
: assignAt(val, path.slice(1), newValue) | |
}); | |
}; | |
import deepEqual from 'deep-equal'; | |
console.log('[TESTS::assignAt]', { | |
'extend middle key': deepEqual( | |
assignAt( | |
{a: {b: {c: 1}, d: 3}, f: {a: {b: 27}}, xx: 1}, | |
{ | |
'a.b': {hey: true}, | |
'f.a': {hello: false, b: 32} | |
} | |
), | |
{a: {b: {c: 1, hey: true}, d: 3}, f: {a: {b: 32, hello: false}}, xx: 1} | |
) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment