Make u.map return same instance if nothing changes

main
Aaron Jensen 2015-08-09 00:21:24 -07:00
parent 8e82692be2
commit 92ae098659
3 changed files with 42 additions and 6 deletions

View File

@ -1,6 +1,7 @@
# Change Log
## [unreleased]
* `u.map` will now return the same instance if nothing changes.
* Removed a couple lodash dependencies.
## [0.5.0]

View File

@ -1,15 +1,37 @@
import mapValues from 'lodash/object/mapValues';
import update from './update';
import wrap from './wrap';
function map(iteratee, object) {
const updater = update(iteratee);
function forEach(object, callback) {
if (Array.isArray(object)) {
return object.map(updater);
object.forEach(callback);
} else {
Object.keys(object).forEach((key) => callback(object[key], key));
}
}
function clone(object) {
if (Array.isArray(object)) {
return [...object];
}
return mapValues(object, updater);
return { ...object };
}
function map(iteratee, object) {
const updater = update(iteratee);
let newObject;
forEach(object, (value, index) => {
const newValue = updater(value, index);
if (newValue === value) return;
newObject = newObject || clone(object);
newObject[index] = newValue;
});
return newObject || object;
}
export default wrap(map);

View File

@ -25,6 +25,19 @@ describe('u.map', () => {
expect(result).to.eql([{ a: 1 }, { a: 1 }]);
});
it('returns the same object if no updates are made', () => {
const array = [0, 1];
const ident = x => x;
let result = u.map(ident, array);
expect(result).to.equal(array);
const object = { a: 0 };
result = u.map(ident, object);
expect(result).to.equal(object);
});
it('passes the key or index as the second parameter to the iteratee', () => {
const object = {
a: { x: 0 },