diff --git a/lib/map.js b/lib/map.js index b10ee4e..15110ae 100644 --- a/lib/map.js +++ b/lib/map.js @@ -1,13 +1,21 @@ import update from './update'; import wrap from './wrap'; import forEach from 'lodash/collection/forEach'; +import mapArray from 'lodash/collection/map'; +import mapObject from 'lodash/object/mapValues'; -function clone(object) { - if (Array.isArray(object)) { - return [...object]; - } +function shallowEqual(object, otherObject) { + let equal = true; + forEach(otherObject, (value, key) => { + if (value !== object[key]) { + equal = false; - return { ...object }; + // exit early + return false; + } + }); + + return equal; } function map(iteratee, object) { @@ -15,19 +23,16 @@ function map(iteratee, object) { iteratee : update(iteratee); - let newObject; + const mapper = Array.isArray(object) ? + mapArray : + mapObject; - forEach(object, (value, index) => { - const newValue = updater(value, index); + const newObject = mapper(object, updater); + const equal = shallowEqual(object, newObject); - if (newValue === value) return; - - newObject = newObject || clone(object); - - newObject[index] = newValue; - }); - - return newObject || object; + return equal ? + object : + newObject; } export default wrap(map);