Skip to content

Instantly share code, notes, and snippets.

@notgiorgi
Created June 30, 2016 21:07
Show Gist options
  • Save notgiorgi/36c40b1601fd48ae9b450610e774b42a to your computer and use it in GitHub Desktop.
Save notgiorgi/36c40b1601fd48ae9b450610e774b42a to your computer and use it in GitHub Desktop.
// 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