Skip to content

Instantly share code, notes, and snippets.

@StrongerMyself
Last active September 6, 2019 09:21
Show Gist options
  • Save StrongerMyself/51253b7673cb4e290e192993a55dd460 to your computer and use it in GitHub Desktop.
Save StrongerMyself/51253b7673cb4e290e192993a55dd460 to your computer and use it in GitHub Desktop.
dotobj
const pathToRoute = (path = '') => {
return path.split('.').map(key => `['${key}']`).join('')
}
const onGet = (path = '') => {
return new Function('obj', `return obj${pathToRoute(path)}`)
}
const onSet = (path = '') => {
return new Function('obj', 'val', `obj${pathToRoute(path)} = val; return obj`)
}
const dotObj = (path = '') => {
return {
get: onGet(path),
set: onSet(path),
}
}
// a = {b: {c: 1}}
// dotObj('b.c').get(a)
// --> 1
// dotObj('b.c').set(a, 2)
// --> {b: {c: 2}}
// a.b.c
// --> 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment