From 317c7e67a3c44ce4a528228d42b92d9835a1bd49 Mon Sep 17 00:00:00 2001 From: wuyangfan Date: Mon, 25 May 2026 15:38:02 +0800 Subject: [PATCH] fix(parse): support scientific notation for format() roundtrip Extend the numeric capture group to accept exponent suffixes so parse() can handle strings produced by format() for very large values like Number.MAX_VALUE. Fixes vercel/ms#284 Co-authored-by: Cursor --- src/index.test.ts | 4 ++++ src/index.ts | 2 +- src/parse.test.ts | 16 +++++++++++++++- 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/index.test.ts b/src/index.test.ts index 5035ab9..6b03629 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -327,6 +327,10 @@ describe('ms(number)', () => { expect(ms(-234234234)).toBe('-3d'); }); + + it('should roundtrip very large values that format in scientific notation', () => { + expect(ms(ms(Number.MAX_VALUE))).toBe(Number.MAX_VALUE); + }); }); // invalid inputs diff --git a/src/index.ts b/src/index.ts index d50e3c7..0796c11 100644 --- a/src/index.ts +++ b/src/index.ts @@ -75,7 +75,7 @@ export function parse(str: string): number { ); } const match = - /^(?-?\d*\.?\d+) *(?milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec( + /^(?-?(?:\d*\.?\d+)(?:e[+-]?\d+)?) *(?milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec( str, ); diff --git a/src/parse.test.ts b/src/parse.test.ts index 9182411..a8e8f1b 100644 --- a/src/parse.test.ts +++ b/src/parse.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from '@jest/globals'; -import { parse } from './index'; +import { format, parse } from './index'; describe('parse(string)', () => { it('should not throw an error', () => { @@ -66,6 +66,20 @@ describe('parse(string)', () => { expect(parse('.5ms')).toBe(0.5); }); + it('should parse scientific notation values', () => { + expect(parse('1e3ms')).toBe(1000); + expect(parse('1.5e2s')).toBe(150000); + expect(parse('-1e3ms')).toBe(-1000); + expect(parse('1E3ms')).toBe(1000); + expect(parse('1e+3ms')).toBe(1000); + }); + + it('should roundtrip format output with scientific notation', () => { + const formatted = format(Number.MAX_VALUE); + expect(formatted).toMatch(/e[+-]\d+y$/i); + expect(parse(formatted)).toBe(Number.MAX_VALUE); + }); + it('should work with negative integers', () => { expect(parse('-100ms')).toBe(-100); });