From 1348d08effa9e4f86c8966ef3d4905850430e198 Mon Sep 17 00:00:00 2001 From: seggev319 Date: Mon, 17 Jul 2017 15:16:38 +0300 Subject: [PATCH] objectPath.modify objectPath.modify: Modifies an existing value using a provided function --- index.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/index.js b/index.js index bba7e3d..788b5bb 100644 --- a/index.js +++ b/index.js @@ -124,6 +124,24 @@ return set(obj[currentPath], path.slice(1), value, doNotReplace); } + /** + * Modifies 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 assigned ifn none exists already + * @param {Boolean} [modifyDefault=false] Should the default value also be passed to the given function + * @return {*} [description] + * @author Seggev Shoresh + */ + objectPath.modify = function(obj, path, func, defaultValue, modifyDefault){ + var value = objectPath.get(obj, path, defaultValue); + if(modifyDefault || (defaultValue && value != defaultValue)){ + value = func(value, obj, path); + } + return objectPath.set(obj, path, value); + } + objectPath.has = function (obj, path) { if (typeof path === 'number') { path = [path];