diff --git a/index.js b/index.js index bba7e3d..0282f7b 100644 --- a/index.js +++ b/index.js @@ -124,6 +124,21 @@ return set(obj[currentPath], path.slice(1), value, doNotReplace); } + /** + * Updates an existing value using a provided function + * @param {Object} obj The object to modify + * @param {String|Array} path The path of the property to modify + * @param {Function} func The function to apply to the existing property + * @param {*} [defaultValue] The value to be used by the function if none exists already + * @return {Object} The modified object + * @author Jared Rewerts + */ + objectPath.update = function(obj, path, func, defaultValue, modifyDefault){ + var value = objectPath.get(obj, path, defaultValue); + value = func(value, obj, path); + return objectPath.set(obj, path, value); + } + objectPath.has = function (obj, path) { if (typeof path === 'number') { path = [path]; diff --git a/test.js b/test.js index d3a3f01..17470db 100644 --- a/test.js +++ b/test.js @@ -237,6 +237,34 @@ describe('set', function() { }); }); +describe('update', function() { + it('should update an existing array of values', function() { + var obj = getTestObj(); + objectPath.update(obj, ['b', 'd'], function(value, object, path) { + var newValue = [] + for (var i = 0; i < value.length; i++) { + newValue.push(value[i].charCodeAt(0)) + } + return newValue; + }) + expect(obj.b.d[0]).to.be.equal(97) + expect(obj.b.d[1]).to.be.equal(98) + }); + + it('should update an array of values that doesn\'t exist', function() { + var obj = getTestObj(); + objectPath.update(obj, ['b', 'z'], function(value, object, path) { + var newValue = [] + for (var i = 0; i < value.length; i++) { + newValue.push(value[i].charCodeAt(0)) + } + return newValue; + }, ['x', 'y', 'z']) + expect(obj.b.z[0]).to.be.equal(120) + expect(obj.b.z[1]).to.be.equal(121) + expect(obj.b.z[2]).to.be.equal(122) + }); +}); describe('push', function() { it('should push value to existing array using unicode key', function() {