Last active
September 19, 2019 06:21
-
-
Save JonathonAshworth/3b66d4d18e8ae0e9cca1136a31630d8d to your computer and use it in GitHub Desktop.
Immutable Set
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
const imSet = (objOrArray, path, valueOrFunc) => { | |
const multipath = Array.isArray(path) && path.length > 1 | |
const pathItem = Array.isArray(path) ? path[0] : path // unwrap single item array | |
const isFunc = typeof valueOrFunc === "function" | |
const value = multipath | |
? imSet(objOrArray[pathItem], path.slice(1), valueOrFunc) | |
: isFunc ? valueOrFunc(objOrArray[pathItem]) : valueOrFunc | |
if (Array.isArray(objOrArray)) { | |
return [ | |
...objOrArray.slice(0, pathItem), | |
value, | |
...objOrArray.slice(pathItem + 1), | |
] | |
} else { | |
return { | |
...objOrArray, | |
[pathItem]: value, | |
} | |
} | |
} | |
export default imSet |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment