-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
upsertObjectArray -> syncResourceArray
- Loading branch information
Showing
2 changed files
with
22 additions
and
7 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,22 @@ | ||
export const upsertObjectArray = <T extends { id?: string }>(arr: T[], obj: T): T[] => { | ||
import { Resource } from "@medplum/fhirtypes"; | ||
|
||
/** | ||
* Syncs an array of resources by adding the new resource if it doesn't exist, | ||
* or replacing it if it does and has a newer lastUpdated date. | ||
* @param arr - The array of resources. | ||
* @param obj - The resource to sync. | ||
* @returns The updated array of resources. | ||
*/ | ||
export const syncResourceArray = <T extends Resource>(arr: T[], obj: T): T[] => { | ||
const existingIndex = arr.findIndex((t) => t.id != null && obj.id != null && t.id === obj.id); | ||
if (existingIndex !== -1) { | ||
return [...arr.slice(0, existingIndex), obj, ...arr.slice(existingIndex + 1)]; | ||
if ( | ||
obj.meta?.lastUpdated != null && | ||
arr[existingIndex].meta?.lastUpdated != null && | ||
obj.meta?.lastUpdated > arr[existingIndex].meta?.lastUpdated | ||
) { | ||
return [...arr.slice(0, existingIndex), obj, ...arr.slice(existingIndex + 1)]; | ||
} | ||
} | ||
return [...arr, obj]; | ||
}; |