Skip to content

Instantly share code, notes, and snippets.

@stevenschobert
Created December 30, 2014 15:12
Show Gist options
  • Select an option

  • Save stevenschobert/ca76531b46f2ac00cbd8 to your computer and use it in GitHub Desktop.

Select an option

Save stevenschobert/ca76531b46f2ac00cbd8 to your computer and use it in GitHub Desktop.
Object extending - supports N... arguments
function extend() {
var args = [].slice.call(arguments);
args[0] = (typeof args[0] === 'object') ? args[0] : {};
for (var i=1; i<args.length; i++) {
if (typeof args[i] === 'object') {
for (var key in args[i]) {
if (args[i].hasOwnProperty(key)) {
args[0][key] = args[i][key];
}
}
}
}
return args[0];
}
describe('#extend', function() {
it('should return the first object', function() {
var testObj = {};
assert.equal(extend(testObj), testObj);
});
it('should copy properties from the second object to the first', function() {
var obj1 = { one: 1 };
var obj2 = { two: 2 };
extend(obj1, obj2);
assert.equal(obj1.two, 2);
});
it('should not modify properties from the second object', function() {
var obj1 = { one: 1 };
var obj2 = { two: 2 };
extend(obj1, obj2);
assert.deepEqual({two: 2}, obj2);
});
it('should overwrite properties with the same name from right to left', function() {
var obj1 = { one: 1 };
var obj2 = { one: 2 };
extend(obj1, obj2);
assert.equal(obj1.one, 2);
});
it('should support n number of objects to extend from', function() {
assert.deepEqual({
name: 'Force Push',
power: 100,
available: true
}, extend({name: 'force push', power: 50}, {power: 75}, {available: true, power: 100}, {name: 'Force Push'}));
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment