Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Created August 31, 2011 20:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanflorence/1184675 to your computer and use it in GitHub Desktop.
Save ryanflorence/1184675 to your computer and use it in GitHub Desktop.
define({
/*
* Simplified prototypal inheritance, see http://javascript.crockford.com/prototypal.html
*/
create: function (obj){
function F() {}
F.prototype = obj;
return new F();
},
/*
* Dynamic property setting
* for example
* var o = {};
* object.set(o, 'a.b.c', 'foo');
* console.log(o) // {a: {b: { c: 'foo' }}}
*/
set: function (obj, property, value) {
var tree = obj,
split = property.split('.'),
last = split.pop(),
next;
while (next = split.shift()){
if (typeof tree[next] !== 'object') tree[next] = {};
tree = tree[next];
}
tree[last] = value;
},
/*
* Dynamically delete properties of an object, similar to above
* deletes the last property in the chain
* for example:
* var o = {a: { b: { c: { d: 'foo' }}}}
* object.unset(o, 'a.b.c');
* o; // { a: {b: {} }}
*/
unset: function (obj, property){
var tree = obj,
split = property.split('.'),
last = split.pop();
while (next = split.shift()) tree = tree[next];
delete tree[last]
}
});
@ryanflorence
Copy link
Author

Usage

require(['util/obj'], function (obj) {
  var o = {};
  obj.set(o, 'foo.bar.baz', { more: 'stuff' });
  console.log(o); //> { foo: { bar: { baz: { more: 'stuff' } } } }
});

@millermedeiros
Copy link

set/unset are good candidates for the amd-utils object "package" :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment