Skip to content

Commit

Permalink
Add preventing infinity loop
Browse files Browse the repository at this point in the history
  • Loading branch information
marcingajda committed Mar 31, 2024
1 parent afc7cd6 commit 40463f5
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
12 changes: 12 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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!'));
});
10 changes: 7 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@ const isObject = (object: unknown): object is Record<string, unknown> => {
type Formatter<Options> = (input: string, options?: Options) => string;

const changeKeysFactory = <Options extends changeCase.Options = changeCase.Options>(changeCase: Formatter<Options>) => {
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;
}
Expand All @@ -18,7 +22,7 @@ const changeKeysFactory = <Options extends changeCase.Options = changeCase.Optio

if (Array.isArray(input)) {
return input.map((item) => {
return changeKeys(item, options);
return changeKeys(item, options, level + 1);
});
}

Expand All @@ -30,7 +34,7 @@ const changeKeysFactory = <Options extends changeCase.Options = changeCase.Optio
const value = (input as Record<string, unknown>)[key];

const changedKey = changeCase(key, options);
const changedValue = changeKeys(value, options);
const changedValue = changeKeys(value, options, level + 1);

result[changedKey] = changedValue;
});
Expand Down

0 comments on commit 40463f5

Please sign in to comment.