I work with Redux, and I often have to write reducers with expressions like this:
return users.map(user => user.id !== selectedUserID ? user : { ... user, removed: false } );
The goal should be clear enough: only change the element in the array that has the given identifier when copying the rest, since they are . Also note that ordering is important, otherwise I could just use the filter() function.
This snippet causes a no-confusing-arrow error in eslint, which makes sense to me. This can also be easily solved by adding a parenthesis around the body of the arrow function, so there is nothing to do 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 parentheses around the arrow function body, returning to version 1 of the snippet.
The obvious solution here is to write the arrow function in a verbal way:
return users.map(user => { if(user.id !== selectedUserID) { return user;
but I honestly think this is too awkward.
Besides the specific context and tools used (eslint and prettier, which can be configured differently / disabled / independently), is there a better way to write this?
In my wildest dreams, there is a function with a signature similar to:
Array.mapIf(callback, condition)
which loops through all the elements in the array and calls the callback function only for those that satisfy the specified condition , returning other unmodified elements.
I could write the same function, but maybe there is something already existing in other functional languages ββthat might be worth a look at the general culture / inspiration.