Last active
September 6, 2019 09:21
-
-
Save StrongerMyself/51253b7673cb4e290e192993a55dd460 to your computer and use it in GitHub Desktop.
dotobj
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 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