Created
          August 18, 2023 19:03 
        
      - 
      
 - 
        
Save ksafranski/9f5438e82a5ff144e2bc19a726d163a5 to your computer and use it in GitHub Desktop.  
Revisions
- 
        
ksafranski created this gist
Aug 18, 2023 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal 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); }); }); This file contains hidden or 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 charactersOriginal 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; };