Skip to content

Instantly share code, notes, and snippets.

@abiodun0
Last active April 10, 2017 22:18
Show Gist options
  • Save abiodun0/f5143c8da2656fa95d780cdb222aea1d to your computer and use it in GitHub Desktop.
Save abiodun0/f5143c8da2656fa95d780cdb222aea1d to your computer and use it in GitHub Desktop.
A simple idiomatic way of upserting and replace
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