Created
January 22, 2019 15:00
-
-
Save maxired/8de32f932d915a5a2c61ff15c4fcfd0d to your computer and use it in GitHub Desktop.
Set if needed
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
export const setPath = ([key, ...next], value, obj) => { | |
if (next.length === 0) { | |
return {...obj, [key]: value }; | |
} | |
return {...obj, [key]: setPath(next, value, obj[key]) }; | |
}; | |
export const getPath = ([key, ...next], obj) => { | |
if (next.length === 0) { | |
return obj[key]; | |
} | |
return getPath(next, obj); | |
} | |
const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b) | |
export const setPathIfNeeded = (path, value, obj) => { | |
const currentValue = getPath(path, obj); | |
if (isEqual(currentValue, obj)) return obj; | |
return setPath(path, value, obj); | |
} | |
export const set = (path, value, obj) => setPath(path.split('.'), value, obj); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment