Skip to content

Commit

Permalink
feat(esl-utils): restrict negative values
Browse files Browse the repository at this point in the history
  • Loading branch information
Natalie-Smirnova committed Aug 16, 2024
1 parent 29baee8 commit ab981e5
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
6 changes: 5 additions & 1 deletion src/modules/esl-utils/misc/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,11 @@ export function format(str: string, source: Record<string, any>, matcher: RegExp
*/
export function parseTime(timeStr: string): number {
const str = timeStr.trim().toLowerCase();
const parseNoEmpty = (s: string): number => s ? +s : NaN;
const parseNoEmpty = (s: string): number => {
const num = s ? +s : NaN;
if (Object.is(num, -0) || num < 0) return NaN;
return num;
};
if (str.endsWith('ms')) return parseNoEmpty(str.slice(0, -2));
if (str.endsWith('s')) return parseNoEmpty(str.slice(0, -1)) * 1000;
return +str; // empty string without unit is treated as 0
Expand Down
8 changes: 4 additions & 4 deletions src/modules/esl-utils/misc/test/format.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,13 +160,13 @@ describe('misc/format helper tests', () => {
['.124s', 124],
['.3ms', 0.3],
// Negative integer
['-456ms', -456],
['-456ms', NaN],
// Case insensitive
['14mS', 14],
['14S', 14000],
// Zero with leading +/-
['+0s', 0],
['-0ms', -0],
['-0ms', NaN],
// Digits without unit should be parsed as milliseconds
['0', 0],
['100', 100],
Expand Down Expand Up @@ -213,13 +213,13 @@ describe('misc/format helper tests', () => {
['.124s', 124],
['.3ms', 0.3],
// Negative integer
['-456ms', -456],
['-456ms', NaN],
// Case insensitive
['14mS', 14],
['14S', 14000],
// Zero with leading +/-
['+0s', 0],
['-0ms', -0]
['-0ms', NaN]
])(
'valid time = %s parsed as %s',
(time: string, result: number) => expect(parseCSSTime(time)).toBe(result)
Expand Down

0 comments on commit ab981e5

Please sign in to comment.