Skip to content

Commit

Permalink
Merge ea1d9de into 98c0096
Browse files Browse the repository at this point in the history
  • Loading branch information
pocesar committed Apr 13, 2014
2 parents 98c0096 + ea1d9de commit f35adb1
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
33 changes: 33 additions & 0 deletions index.js
Expand Up @@ -66,6 +66,35 @@ function set(obj, path, value, doNotReplace) {
return undefined;
}

function del(obj, path) {
if (isEmpty(path)) {
return obj;
}
if (isEmpty(obj)) {
return undefined;
}
if(isString(path)) {
return del(obj, path.split('.'));
}
var currentPath = getKey(path[0]);
var oldVal = obj[currentPath];

if(path.length === 1) {
if (oldVal !== void 0) {
if (isArray(obj[currentPath])) {
obj.splice(currentPath, 1);
} else {
delete obj[currentPath];
}
}
} else if (path.length > 1) {
if (obj[currentPath] !== void 0) {
return del(obj[currentPath], path.slice(1));
}
}

return obj;
}

var objectPath = module.exports = {};

Expand Down Expand Up @@ -105,3 +134,7 @@ objectPath.get = function(obj, path) {
}
return objectPath.get(obj[currentPath], path.slice(1));
};

objectPath.del = function(obj, path) {
return del(obj, path);
};
23 changes: 23 additions & 0 deletions test.js
Expand Up @@ -123,3 +123,26 @@ describe('ensureExists', function() {
expect(objectPath.ensureExists(obj, [], "test")).to.have.property('a', 'b');
});
});

describe('del', function(){
it('should delete deep paths', function(){
var obj = getTestObj();


objectPath.set(obj, 'b.g.1.1', "test");
objectPath.set(obj, 'b.g.1.2', "test");
expect(obj).to.have.deep.property("b.g.1.1","test");
expect(obj).to.have.deep.property("b.g.1.2","test");

expect(objectPath.del(obj)).to.be.equal(obj);

objectPath.del(obj, 'b.g.1.1');
expect(obj).to.not.have.deep.property("b.g.1.1");
expect(obj).to.have.deep.property("b.g.1.2","test");
objectPath.del(obj, ['b','g','1','2']);
expect(obj).to.not.have.deep.property("b.g.1.2");
expect(obj).to.have.deep.property("b.g.1");
expect(objectPath.del(obj, ['b'])).to.not.have.deep.property("b.g");
expect(obj).to.be.deep.equal({'a':'b'});
});
});

0 comments on commit f35adb1

Please sign in to comment.