diff --git a/src/index.test.ts b/src/index.test.ts index a2cc124..9d18966 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -79,3 +79,15 @@ test('Alows to pass custom options', (t) => { assert.deepEqual(changeEveryCase.dotKeys(input, { split }), output); assert.notDeepEqual(changeEveryCase.dotKeys(input), output); }); + +test('Prevents infinity loop', () => { + const input = { + recursive: { + value: {} + }, + }; + + input.recursive.value = input; + + assert.throws(() => changeEveryCase.kebabKeys(input), new Error('Maximum level of 1000 reached. Object is probably recursive!')); +}); \ No newline at end of file diff --git a/src/index.ts b/src/index.ts index 8ccf853..6910bdd 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,7 +7,11 @@ const isObject = (object: unknown): object is Record => { type Formatter = (input: string, options?: Options) => string; const changeKeysFactory = (changeCase: Formatter) => { - return function changeKeys(input: unknown, options?: Options): unknown { + return function changeKeys(input: unknown, options?: Options, level = 0): unknown { + if (level === 1000) { + throw new Error('Maximum level of 1000 reached. Object is probably recursive!'); + } + if (!isObject(input)) { return input; } @@ -18,7 +22,7 @@ const changeKeysFactory = { - return changeKeys(item, options); + return changeKeys(item, options, level + 1); }); } @@ -30,7 +34,7 @@ const changeKeysFactory = )[key]; const changedKey = changeCase(key, options); - const changedValue = changeKeys(value, options); + const changedValue = changeKeys(value, options, level + 1); result[changedKey] = changedValue; });