Skip to content

Instantly share code, notes, and snippets.

@lski
Created March 9, 2022 10:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lski/5c6240c0448c5d97bdc0360fda28a265 to your computer and use it in GitHub Desktop.
Save lski/5c6240c0448c5d97bdc0360fda28a265 to your computer and use it in GitHub Desktop.
Simple upsert function
/**
* 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