Skip to content

Commit

Permalink
feat: add fallbackToInput parameter
Browse files Browse the repository at this point in the history
  • Loading branch information
RealShadowNova committed Apr 12, 2022
1 parent 79ed672 commit e41226c
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/lib/getProperty.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@ export const PROPERTY_NOT_FOUND = Symbol('PROPERTY_NOT_FOUND');
* @since 1.0.0
* @param input The object or array to get the property from.
* @param path The path to the property to get.
* @param fallbackToInput Whether to return the input if path has a length of 0.
* @returns The property at the path or {@link PROPERTY_NOT_FOUND} if the property does not exist.
*/
export function getProperty<T = unknown>(input: unknown, path: string[]): T | typeof PROPERTY_NOT_FOUND {
if (path.length === 0) return input as unknown as T;
export function getProperty<T = unknown>(input: unknown, path: string[], fallbackToInput = true): T | typeof PROPERTY_NOT_FOUND {
if (path.length === 0) return fallbackToInput ? (input as unknown as T) : PROPERTY_NOT_FOUND;
if (!isObjectOrArray(input)) return PROPERTY_NOT_FOUND;

return path.reduce<Record<PropertyKey, any>>((previousStep, step) => {
Expand Down
5 changes: 5 additions & 0 deletions tests/lib/getProperty.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ describe('getProperty', () => {
expect(getProperty({ a: { b: 'c' } }, [])).toEqual({ a: { b: 'c' } });
});

test('GIVEN object w/ empty path THEN returns symbol', () => {
expect(getProperty({ a: 'b' }, [], false)).toEqual(PROPERTY_NOT_FOUND);
expect(getProperty({ a: { b: 'c' } }, [], false)).toEqual(PROPERTY_NOT_FOUND);
});

test('GIVEN object w/ path THEN gets value at path', () => {
expect(getProperty({ a: 'b' }, ['a'])).toBe('b');
expect(getProperty({ a: { b: 'c' } }, ['a'])).toEqual({ b: 'c' });
Expand Down

0 comments on commit e41226c

Please sign in to comment.