Skip to content

Instantly share code, notes, and snippets.

@ksafranski
Created August 18, 2023 19:03
Show Gist options
  • Save ksafranski/9f5438e82a5ff144e2bc19a726d163a5 to your computer and use it in GitHub Desktop.
Save ksafranski/9f5438e82a5ff144e2bc19a726d163a5 to your computer and use it in GitHub Desktop.

Revisions

  1. ksafranski created this gist Aug 18, 2023.
    10 changes: 10 additions & 0 deletions get.spec.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,10 @@
    describe('get', () => {
    it('return undefined on non-existent key', () => {
    const res = get({ hello: 'world' }, 'foo');
    expect(res).toBeUndefined();
    });
    it('returns key when nested', () => {
    const res = get({ hello: { world: false } }, 'hello.world');
    expect(res).toEqual(false);
    });
    });
    19 changes: 19 additions & 0 deletions get.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,19 @@
    export const get = <T>(obj: T, path: string): any => {
    const paths: string[] = path.split('.'); // array of path keys
    let currentNode: T = obj; // pointer to current node, start at root
    let value: any = undefined; // placeholder for eventual value

    // Loop nodes of path as pointer
    for (const p of paths) {
    if (typeof currentNode[p] === 'object') {
    // Move pointer if object
    currentNode = currentNode[p];
    } else {
    // Set value if last node
    value = currentNode[p];
    }
    }

    // value returned or undefined if not found
    return value;
    };