Closed
Description
I am often (in multiple projects) reimplementing the same utility function, that replaces a value in an array based on some condition (a position or a field is equal to X), without mutating the original array (like map
in that regard):
array.map(function(value) {
if (value.id !== ID) {
return value;
}
return REPLACEMENT;
});
array.map(function(value, index) {
if (index !== POSITION) {
return value;
}
return REPLACEMENT;
});
I would like to dip my toe in the water and see if others would be interested in having a function that does this.
/**
* Replace a value in `array` when `condition` matches.
*
* @param {Array} array The collection to iterate over.
* @param {Function|number|Object} condition Condition to match.
* @param {*} iteratee The function invoked if `condition` matches, or the replacement value.
* @return {Array} Returns the new mapped array.
*/
function mapReplace(array, condition, iteratee) {
// ...
}
// Mapped in lodash/fp ([2, 0, 1])
_.mapReplace(condition, iteratee, array);
Example
function plusTen(x) {
return x + 10;
}
function isEven(x) {
return x % 2 === 0;
}
var array = [0, 1, 2, 3];
// Using index as condition and simple value as iteratee ( = replacement)
_.mapReplace(array, 2, 'replacement');
// => [0, 1, 'replacement', 3]
// Using index as condition and function as iteratee
_.mapReplace(array, 2, plusTen);
// => [0, 1, 12, 3]
// Using function as condition and function as iteratee
_.mapReplace(array, isEven, plusTen);
// => [10, 1, 12, 3]
// or if it is only applied to the first found element, and a mapReplaceAll exists:
// => [10, 1, 2, 3]
// Using object to get field as condition and value as iteratee
_.mapReplace([{id: 0, val: 0}, {id: 1, val: 1}], {id: 1}, {id: 1, foo: 'bar'});
// => [{id: 0, val: 0}, {id: 1, foo: 'bar'}]
I would have liked it to be named replace
, but since that is already taken... ^^'
I used mapReplace
in the example but open to su
682D
ggestions.
I'd argue it would be nice to have one function to update the first found item, and one to update them all (kind of like the proposal for replaceAll
).