Skip to content

Instantly share code, notes, and snippets.

@maximilian-krauss
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maximilian-krauss/b09d797387e30ad9d772 to your computer and use it in GitHub Desktop.
Save maximilian-krauss/b09d797387e30ad9d772 to your computer and use it in GitHub Desktop.
dynamo
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var dynamo = function(obj, path, value) {
if(obj === undefined || path === undefined) {
return undefined;
}
var pathSegments = path.split('.'),
write = (value !== undefined),
isPrimitive = function(o) {
return ['string', 'number', 'boolean'].indexOf(typeof o) > -1;
};
if(pathSegments.length === 1) {
if(write) {
obj[pathSegments[0]] = value;
}
return obj[pathSegments[0]];
}
var nextUp = pathSegments[0];
if(write && !obj.hasOwnProperty(nextUp) || (write && isPrimitive(obj[nextUp]))) {
obj[nextUp] = {};
}
if(obj.hasOwnProperty(nextUp)) {
return dynamo( obj[nextUp], pathSegments.splice(1).join('.'), value );
}
return undefined;
};
var x = {
a: {
b: {
c: {
d: 1
}
}
}
};
console.log(dynamo(x, 'a.b.c.d'));
console.log(dynamo(x, 'a.b.c'));
console.log(dynamo(x, 'a.b.c'));
console.log(dynamo(x, 'b'));
console.log(dynamo(x, '1'));
console.log(dynamo(x, 'd.e.f', 2));
console.log(dynamo(x, 'a.b.c.d.e.f.g.h.i.j.k.l.m', { x: { y: { z: 3 } } }));
console.log(x);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment