Skip to content

Commit

Permalink
set now can handle multiple objects
Browse files Browse the repository at this point in the history
  • Loading branch information
borovin committed Aug 31, 2015
1 parent 001d757 commit c9bda63
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 7 deletions.
38 changes: 34 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,34 @@
var _ = require('bower_components/lodash/lodash.js'),
deepExtend = require('bower_components/deepExtend/index.js');
var _ = require('bower_components/lodash/lodash.js');

function deepExtend(obj) {

var cloneArray = function(arr){
return _.map(arr, function(item){
if (_.isPlainObject(item)) {
return deepExtend({}, item);
} else if (_.isArray(item)) {
return cloneArray(item);
} else {
return item;
}
})
};

_.each([].slice.call(arguments, 1), function(source) {
_.forOwn(source, function(value, key) {
if (_.isPlainObject(value)) {
obj[key] = deepExtend({}, obj[key], value);
} else if (_.isArray(value)) {
obj[key] = cloneArray(value);
} else {
obj[key] = value;
}
});
});

return obj;

}

function getChanges(newData, oldData) {

Expand Down Expand Up @@ -51,14 +80,15 @@ module.exports = function (object, path, data) {
var changedData;

if (typeof path === 'string') {
data = pathToObject(path, data);
data = pathToObject(path, deepExtend.apply(null, [].slice.call(arguments, 2)));
} else {
data = path;
data = deepExtend.apply(null, [].slice.call(arguments, 1));
}

changedData = getChanges(data, object);

deepExtend(object, changedData);

return changedData;

};
50 changes: 47 additions & 3 deletions index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ describe(module.id, function(){

set(obj, 'a.b.c', 'abc');

expect(obj.a.b.c).toBe('abc');
expect(obj.a.b.c).toEqual('abc');
});

it('Set return only changed properties', function(){
Expand Down Expand Up @@ -63,7 +63,7 @@ describe(module.id, function(){

set(object, 'a.b', false);

expect(object.a.b).toBeFalsy();
expect(object.a.b).toEqual(false);
});

it('Set number', function(){
Expand All @@ -76,7 +76,7 @@ describe(module.id, function(){

set(object, 'a.b', 1);

expect(object.a.b).toBe(1);
expect(object.a.b).toEqual(1);
});

it('Set array', function(){
Expand Down Expand Up @@ -106,4 +106,48 @@ describe(module.id, function(){

});

it('Set multiple objects on object', function(){

var object = {
a: 1
};

set(object, {
b: 2
}, {
c: 3
});

expect(object).toEqual({a: 1, b: 2, c: 3});

});

it('Set multiple objects on object path', function(){

var object = {
a: 1
};

set(object, 'a.b', {
c: 2
}, {
d: 3
});

expect(object).toEqual({a: {b: {c: 2, d: 3}}});

});

it('Set multiple objects on empty object return all new properties', function(){

var object = set({}, {
a: 1
}, {
b: 2
});

expect(object).toEqual({a: 1, b: 2});

});

});

0 comments on commit c9bda63

Please sign in to comment.