Skip to content

Instantly share code, notes, and snippets.

@alexnoise79
Created March 5, 2023 09:03
Show Gist options
  • Save alexnoise79/e49cf41b9133941d4ec12054f45c94ba to your computer and use it in GitHub Desktop.
Save alexnoise79/e49cf41b9133941d4ec12054f45c94ba to your computer and use it in GitHub Desktop.
deep patch functions to update from websockets
export function updateObject<T>(obj: T, partial: T): T {
if (!partial) {
return obj;
}
return Object.keys(partial).reduce((acc, key) => {
const value = partial[key];
if (Array.isArray(value)) {
// @ts-ignore
acc[key] = updateArray(obj[key], value);
} else if (typeof value === 'object' && value !== null) {
acc[key] = updateObject(obj[key], value);
} else {
acc[key] = value;
}
return acc;
}, {...obj});
}
export function updateArray<T extends { id: number }>(arr: T[], partial: T): T[] {
if (!Array.isArray(arr)) {
return arr;
}
let updatedArray = [...arr];
if (Array.isArray(partial)) {
partial.forEach(p => updatedArray = updateArray(updatedArray, p));
} else {
const index = updatedArray.findIndex((item) => item.id === partial.id);
if (index !== -1) {
updatedArray[index] = updateObject(updatedArray[index], partial);
}
}
return updatedArray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment