Skip to content

Commit

Permalink
fix: Traverse on null
Browse files Browse the repository at this point in the history
  • Loading branch information
manea-ibood committed Sep 23, 2024
1 parent 85e9b51 commit 089f114
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
3 changes: 2 additions & 1 deletion packages/easy/src/utils/Traverse.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { AnyKey } from '../types/AnyKey';

export const traverse = (subject: unknown = {}, property = ''): unknown => {
export const traverse = (subject: unknown, property = ''): unknown => {
subject ??= {};
const props = property.split('.');
const p = props.shift() as string;
return props.length === 0 ? (subject as any)[p] : traverse((subject as any)[p], props.join('.'));
Expand Down
20 changes: 20 additions & 0 deletions packages/easy/test/utils/Traverse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,22 @@ describe('traverse', () => {
expect(traverse(undefined, '')).toBeUndefined();
});

test('traverse with null subject', () => {
expect(traverse(null, '')).toBeUndefined();
});

test('traverse with false subject', () => {
expect(traverse(false, '')).toBeUndefined();
});

test('traverse with null subject nested', () => {
expect(traverse({ group: null }, 'group.name')).toBeUndefined();
});

test('traverse with undefined subject nested', () => {
expect(traverse({ group: undefined }, 'group.name')).toBeUndefined();
});

test('traverse with undefined property', () => {
expect(traverse(Dev.Jeroen, undefined as unknown as string)).toBeUndefined();
});
Expand Down Expand Up @@ -35,6 +51,10 @@ describe('traverse', () => {
test('traverse with existing double-nested property', () => {
expect(traverse(Dev.Jeroen, 'created.by.id')).toBe(0);
});

test('traverse with existing triple-nested property', () => {
expect(traverse({}, 'created.by.id')).toBeUndefined();
});
});

describe('traverseSet', () => {
Expand Down

0 comments on commit 089f114

Please sign in to comment.