Created
June 30, 2016 21:07
-
-
Save notgiorgi/36c40b1601fd48ae9b450610e774b42a to your computer and use it in GitHub Desktop.
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
// Get x[path] | |
// Path may be nested, with dot notation, | |
// e.g. get(x, 'foo.bar.baz.name') => x.foo.bar.baz.name | |
function get(path, x){ | |
checkPath(path); | |
var keys = path.split('.'); | |
return keys.reduce((obj, key) => { | |
return obj[key]; | |
}, x) | |
} | |
function set(path, val, x){ | |
checkPath(path); | |
var keys = path.split('.'); | |
var last = keys.pop(); | |
var reduced = keys.reduce((obj, key) => { | |
return obj[key]; | |
}, x); | |
reduced[last] = val; | |
return reduced; | |
} | |
function checkPath(path){ | |
if(typeof path !== 'string') | |
throw new Error('first arg should be string'); | |
if(path.length === 0) | |
throw new Error('first arg should contain str'); | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment