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 update from './update';
|
||||||
import wrap from './wrap';
|
import wrap from './wrap';
|
||||||
import forEach from 'lodash/collection/forEach';
|
import forEach from 'lodash/collection/forEach';
|
||||||
|
import mapArray from 'lodash/collection/map';
|
||||||
|
import mapObject from 'lodash/object/mapValues';
|
||||||
|
|
||||||
function clone(object) {
|
function shallowEqual(object, otherObject) {
|
||||||
if (Array.isArray(object)) {
|
let equal = true;
|
||||||
return [...object];
|
forEach(otherObject, (value, key) => {
|
||||||
|
if (value !== object[key]) {
|
||||||
|
equal = false;
|
||||||
|
|
||||||
|
// exit early
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
});
|
||||||
|
|
||||||
return { ...object };
|
return equal;
|
||||||
}
|
}
|
||||||
|
|
||||||
function map(iteratee, object) {
|
function map(iteratee, object) {
|
||||||
@ -15,19 +23,16 @@ function map(iteratee, object) {
|
|||||||
iteratee :
|
iteratee :
|
||||||
update(iteratee);
|
update(iteratee);
|
||||||
|
|
||||||
let newObject;
|
const mapper = Array.isArray(object) ?
|
||||||
|
mapArray :
|
||||||
|
mapObject;
|
||||||
|
|
||||||
forEach(object, (value, index) => {
|
const newObject = mapper(object, updater);
|
||||||
const newValue = updater(value, index);
|
const equal = shallowEqual(object, newObject);
|
||||||
|
|
||||||
if (newValue === value) return;
|
return equal ?
|
||||||
|
object :
|
||||||
newObject = newObject || clone(object);
|
newObject;
|
||||||
|
|
||||||
newObject[index] = newValue;
|
|
||||||
});
|
|
||||||
|
|
||||||
return newObject || object;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export default wrap(map);
|
export default wrap(map);
|
||||||
|
Loading…
Reference in New Issue
Block a user