From 324b165e2a22c20d8c7b4bf09eaf5d405677d69a Mon Sep 17 00:00:00 2001 From: Aaron Jensen Date: Wed, 12 Aug 2015 00:23:51 -0700 Subject: [PATCH] Use lodash's map, it's faster --- lib/map.js | 37 +++++++++++++++++++++---------------- 1 file changed, 21 insertions(+), 16 deletions(-) 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);