From 089f11438135a80c1d8fea1dcca59f3c1f32b7f9 Mon Sep 17 00:00:00 2001 From: Eugen Manea Date: Mon, 23 Sep 2024 13:59:20 +0200 Subject: [PATCH] fix: Traverse on null --- packages/easy/src/utils/Traverse.ts | 3 ++- packages/easy/test/utils/Traverse.test.ts | 20 ++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/packages/easy/src/utils/Traverse.ts b/packages/easy/src/utils/Traverse.ts index 195366516..872433645 100644 --- a/packages/easy/src/utils/Traverse.ts +++ b/packages/easy/src/utils/Traverse.ts @@ -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('.')); diff --git a/packages/easy/test/utils/Traverse.test.ts b/packages/easy/test/utils/Traverse.test.ts index d74dae140..f581bcb9b 100644 --- a/packages/easy/test/utils/Traverse.test.ts +++ b/packages/easy/test/utils/Traverse.test.ts @@ -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(); }); @@ -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', () => {