From 21d4c649efe728e0c102aec855e39ceb339af55b Mon Sep 17 00:00:00 2001 From: naveentehrpariya Date: Sun, 28 Jun 2026 22:08:10 +0530 Subject: [PATCH 1/2] Fix leading whitespace dropping the negative sign The global sign was decided by `str[0] === '-'`, reading the raw first character. The parser already tolerates leading whitespace for the magnitude (` 1h` parses to 3600000), but with a leading minus the sign check saw the whitespace instead of the `-`, so ` -1h` returned +3600000 rather than -3600000. Test the first non-whitespace character with `/^\s*-/` instead. This only affects a leading minus preceded by whitespace; the intentional mid-string-minus behavior (`1h-30m`, `2hr -40mins`) is unchanged since those inputs do not start with optional-whitespace-then-minus. --- index.js | 2 +- test.js | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index 3e2b5dc..db755c1 100644 --- a/index.js +++ b/index.js @@ -33,5 +33,5 @@ export default function parse(str = '', format = 'ms') { if (units) result = (result || 0) + n * units }) - return result && ((result / (parse.unit[format] || 1)) * (str[0] === '-' ? -1 : 1)) + return result && ((result / (parse.unit[format] || 1)) * (/^\s*-/.test(str) ? -1 : 1)) } diff --git a/test.js b/test.js index ed7c11e..422ee3d 100644 --- a/test.js +++ b/test.js @@ -97,6 +97,9 @@ t('combined', t => { t.equal(parse('running length: 1hour:20mins'), 1 * h + 20 * m) t.equal(parse('2hr -40mins'), 2 * h + 40 * m) t.equal(parse('-1hr 40mins'), -1 * h - 40 * m) + t.equal(parse(' -1hr 40mins'), -1 * h - 40 * m) + t.equal(parse(' -1h'), -1 * h) + t.equal(parse('\t-30m'), -30 * m) t.equal(parse('2e3s'), 2000 * s) t.end() }) From 4202551629d17150ce1cffc515cf769e44447a3f Mon Sep 17 00:00:00 2001 From: naveentehrpariya Date: Mon, 29 Jun 2026 12:45:34 +0530 Subject: [PATCH 2/2] Simplify sign check with trimStart instead of regex --- index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.js b/index.js index db755c1..d05d5c8 100644 --- a/index.js +++ b/index.js @@ -33,5 +33,5 @@ export default function parse(str = '', format = 'ms') { if (units) result = (result || 0) + n * units }) - return result && ((result / (parse.unit[format] || 1)) * (/^\s*-/.test(str) ? -1 : 1)) + return result && ((result / (parse.unit[format] || 1)) * (String(str).trimStart()[0] === '-' ? -1 : 1)) }