Use lodash's map, it's faster
This commit is contained in:
parent
1e9e43b118
commit
324b165e2a
35
lib/map.js
35
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;
|
||||
|
||||
// exit early
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
return { ...object };
|
||||
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);
|
||||
|
Loading…
Reference in New Issue
Block a user