Last active
August 29, 2015 14:04
-
-
Save maximilian-krauss/b09d797387e30ad9d772 to your computer and use it in GitHub Desktop.
dynamo
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
<!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