From 8ac725b3420da6039b9063eb8a970c05a6833a85 Mon Sep 17 00:00:00 2001 From: Marian Schubert Date: Thu, 18 Oct 2018 13:37:56 +0200 Subject: [PATCH] Implement updateIn method --- index.js | 15 +++++++++++++++ test/update-in.js | 18 ++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 test/update-in.js diff --git a/index.js b/index.js index 7540e3f..cefb574 100644 --- a/index.js +++ b/index.js @@ -400,6 +400,20 @@ DotObject.prototype.set = function (path, val, obj, merge) { return obj } +/** + * + * Use given function to update a property on an object using dot notation. + * + * @param {String} path + * @param {Function} fn + * @param {Object} obj + */ +DotObject.prototype.updateIn = function (path, fn, obj) { + var originalValue = this.pick(path, obj) + this.set(path, fn(originalValue), obj) + return obj +} + /** * * Transform an object @@ -479,6 +493,7 @@ DotObject.copy = wrap('copy') DotObject.object = wrap('object') DotObject.str = wrap('str') DotObject.set = wrap('set') +DotObject.updateIn = wrap('updateIn') DotObject.del = DotObject.remove = wrap('remove') DotObject.dot = wrap('dot') diff --git a/test/update-in.js b/test/update-in.js new file mode 100644 index 0000000..7627293 --- /dev/null +++ b/test/update-in.js @@ -0,0 +1,18 @@ +'use strict' + +require('should') +var Dot = require('../index') + +describe('updateIn:', function () { + it('Should be able to update value at given path using given function', function () { + var obj = { + counter: 1 + } + + Dot.updateIn('counter', function (currentValue) { + return currentValue + 1; + }, obj) + + obj.should.eql({counter: 2}) + }) +})