Skip to content

Commit

Permalink
Refactor updateNestedField
Browse files Browse the repository at this point in the history
  • Loading branch information
LogvinovLeon committed Mar 6, 2024
1 parent cb52155 commit 9fb406b
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 15 deletions.
7 changes: 0 additions & 7 deletions ethereum_history_api/oracles/src/util/object.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,6 @@ describe('updateNestedField', () => {
updateNestedField(object, ['a', '0', 'bar', 'c'], (x: number) => x + 1);
expect(object.a[0].bar.c).to.eq(4);
});

it('non-existing key', () => {
const object = { a: [{ bar: { c: 3 } }] };
updateNestedField(object, ['x', '0', 'y', 'z'], () => 5);
/* eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access */
expect((object as any).x[0]?.y?.z).to.eq(5);
});
});

describe('copy', () => {
Expand Down
21 changes: 13 additions & 8 deletions ethereum_history_api/oracles/src/util/object.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
/* eslint-disable @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-argument */
interface NestedObject<V> {
[key: string]: NestedObject<V> | V;
}

export function updateNestedField<T, V>(obj: T, pathArray: string[], updater: (value: V) => V): void {
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
pathArray.reduce((acc: any, key: string, i: number) => {
if (acc[key] === undefined) acc[key] = {};
if (i === pathArray.length - 1) acc[key] = updater(acc[key]);
return acc[key];
}, obj);
let currentSubtree = obj as NestedObject<V>;
const pathWithoutLast = pathArray.slice(0, pathArray.length - 1);
const lastPathElem = pathArray[pathArray.length - 1];
for (const pathElem of pathWithoutLast) {
currentSubtree = currentSubtree[pathElem] as NestedObject<V>;
}

currentSubtree[lastPathElem] = updater(currentSubtree[lastPathElem] as V);
}

export const copy = <T>(obj: T): T => JSON.parse(JSON.stringify(obj));
export const copy = <T>(obj: T): T => JSON.parse(JSON.stringify(obj)) as T;

0 comments on commit 9fb406b

Please sign in to comment.