Last active
April 10, 2017 22:18
-
-
Save abiodun0/f5143c8da2656fa95d780cdb222aea1d to your computer and use it in GitHub Desktop.
A simple idiomatic way of upserting and replace
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function upsert(ary, pred, val) { | |
if (ary.some(item => pred(val, item))) { | |
return ary.map(item => (pred(val, item) ? val : item)) | |
} | |
return ary.concat(val); | |
} | |
// greedy replace as it replaces all matches of predicate | |
const replace = (predicate, value, collection) => { | |
return collection.map(item => predicate(item, value) ? value : item) | |
} | |
// then | |
replace(item => item.workOrder.id === action.work.id, action.work, workOrders) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment