I work with Redux and it often happens to me to write reducers with expressions like this one:
return users.map(user =>
user.id !== selectedUserID ? user : {
... user,
removed: false
}
);
The intent should be clear enough: modify just the item in the array that has the given id, while copying the others as they are. Also note that ordering is important, otherwise I could just have used a filter()
function.
This snippet triggers a no-confusing-arrow error on eslint, which makes sense to me. This can also be easily solved by adding round parenthesis around the arrow function body, so no big deal here:
return users.map(user => (
user.id !== selectedUserID ? user : {
... user,
removed: false
}
));
I also want to parse this code through prettier, which automatically removes the parenthesis around the arrow function body, going back to version 1 of the snippet.
The obvious solution here is to write the arrow function the verbose way:
return users.map(user => {
if(user.id !== selectedUserID) {
return user; // unmodified user
}
return {
... user,
removed: false
};
});
but I honestly find it a bit too clumsy.
Aside from the specific context and the used tools (eslint and prettier, which can be configured differently/turned off/whatever), is there any better way to write this?
In my wildest dreams it exists a function with a signature similar to:
Array.mapIf(callback, condition)
that cycles all the elements in the array, and calls the callback
function only to the ones satisfying the given condition
, while returning the other elements unmodified.
I could obviously write a function like this myself, but maybe there is something already existing in other functional languages that may be worth to look at for general culture/inspiration.