updeep-remeda/lib/map.js

38 lines
708 B
JavaScript
Raw Normal View History

2015-08-05 07:25:34 +00:00
import update from './update';
import wrap from './wrap';
2015-08-05 07:25:34 +00:00
function forEach(object, callback) {
if (Array.isArray(object)) {
object.forEach(callback);
} else {
Object.keys(object).forEach((key) => callback(object[key], key));
}
}
2015-08-05 07:25:34 +00:00
function clone(object) {
2015-08-05 07:25:34 +00:00
if (Array.isArray(object)) {
return [...object];
2015-08-05 07:25:34 +00:00
}
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;
2015-08-05 07:25:34 +00:00
}
export default wrap(map);