Skip to content

Instantly share code, notes, and snippets.

@JonathonAshworth
Last active September 19, 2019 06:21
Show Gist options
  • Save JonathonAshworth/3b66d4d18e8ae0e9cca1136a31630d8d to your computer and use it in GitHub Desktop.
Save JonathonAshworth/3b66d4d18e8ae0e9cca1136a31630d8d to your computer and use it in GitHub Desktop.
Immutable Set
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