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.

Revisions

  1. alexnoise79 created this gist Mar 5, 2023.
    33 changes: 33 additions & 0 deletions deep-patch.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    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;
    }