Skip to content

Commit

Permalink
fix(addon-doc): prevent convert invalid number to NaN
Browse files Browse the repository at this point in the history
  • Loading branch information
splincode committed Jan 27, 2023
1 parent 02b8a0b commit c436377
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
4 changes: 1 addition & 3 deletions projects/addon-doc/src/utils/coerce-value.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,7 @@ function isBooleanParamValue(value: string): boolean {
}

function isNumberParamValue(value: string): boolean {
// TODO: investigate to disallow potentially catastrophic exponential-time regular expressions.
// eslint-disable-next-line unicorn/no-unsafe-regex
return /^-?[\d.]+(?:e-?\d+)?$/.test(value);
return !!value.trim() && !Number.isNaN(Number(value)) && !value.startsWith(`+`);
}

function isPossibleArray(value: string): boolean {
Expand Down
10 changes: 10 additions & 0 deletions projects/addon-doc/src/utils/test/coerce-value.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,21 @@ describe(`coercing values`, () => {
expect(tuiCoerceValue(`Hello world`)).toBe(`Hello world`);
expect(tuiCoerceValue(`2+5`)).toBe(`2+5`);
expect(tuiCoerceValue(``)).toBe(``);
expect(tuiCoerceValue(` `)).toBe(``);
});

it(`string -> number`, () => {
expect(tuiCoerceValue(`123`)).toBe(123);
expect(tuiCoerceValue(`-123`)).toBe(-123);
expect(tuiCoerceValue(`.2`)).toBe(0.2);
expect(tuiCoerceValue(`-.2`)).toBe(-0.2);
expect(tuiCoerceValue(`2e5`)).toBe(200000);

expect(tuiCoerceValue(`.`)).not.toBeInstanceOf(Number);
expect(tuiCoerceValue(`1,2`)).not.toBeInstanceOf(Number);
expect(tuiCoerceValue(`abc`)).not.toBeInstanceOf(Number);
expect(tuiCoerceValue(`1+2`)).not.toBeInstanceOf(Number);
expect(tuiCoerceValue(` 123 `)).not.toBeInstanceOf(Number);
});

it(`string -> boolean`, () => {
Expand Down

0 comments on commit c436377

Please sign in to comment.