Created
August 18, 2023 19:03
-
-
Save ksafranski/9f5438e82a5ff144e2bc19a726d163a5 to your computer and use it in GitHub Desktop.
Lodash `get` alternative
This file contains 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 characters
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 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 characters
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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment