Created
March 9, 2022 10:05
-
-
Save lski/5c6240c0448c5d97bdc0360fda28a265 to your computer and use it in GitHub Desktop.
Simple upsert function
This file contains 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
/** | |
* Updates or adds an item to a new array. | |
* | |
* @param arr The array to check if item exists | |
* @param item The item to add/insert | |
* @param comparer Run against each item in the array to see if it matches an existing item | |
* @returns A new array with the item replaced if found, or added to the end if not found. | |
*/ | |
export const upsert = <T,>(arr: T[], item: T, comparer: (existingItem: T, newItem: T, index: number) => boolean = (item1, item2) => item1 === item2): T[] => { | |
const output = []; | |
let found = false; | |
for (let index = 0, end = arr.length; index < end; index++) { | |
const existingItem = arr[index]; | |
const hasMatched = comparer(existingItem, item, index); | |
if (hasMatched) { | |
output.push(item); | |
found = true; | |
} else { | |
output.push(existingItem); | |
} | |
} | |
if (!found) output.push(item); | |
return output; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment