Skip to content

Commit 76463de

Browse files
authored
fix: enhance duration parser (#884)
* perf: replace some regexes with `str.includes()` * fix: enhance duration parser
1 parent 5d2ad78 commit 76463de

File tree

2 files changed

+14
-14
lines changed

2 files changed

+14
-14
lines changed

src/util.ts

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -284,13 +284,11 @@ export function parseDuration(d: Duration) {
284284
if (typeof d == 'number') {
285285
if (isNaN(d) || d < 0) throw new Error(`Invalid duration: "${d}".`)
286286
return d
287-
} else if (/\d+s/.test(d)) {
288-
return +d.slice(0, -1) * 1000
289-
} else if (/\d+ms/.test(d)) {
290-
return +d.slice(0, -2)
291-
} else if (/\d+m/.test(d)) {
292-
return +d.slice(0, -1) * 1000 * 60
293287
}
288+
if (/^\d+s$/.test(d)) return +d.slice(0, -1) * 1000
289+
if (/^\d+ms$/.test(d)) return +d.slice(0, -2)
290+
if (/^\d+m$/.test(d)) return +d.slice(0, -1) * 1000 * 60
291+
294292
throw new Error(`Unknown duration: "${d}".`)
295293
}
296294

@@ -344,9 +342,9 @@ export function formatCmd(cmd?: string): string {
344342
function root() {
345343
if (/\s/.test(ch)) return space
346344
if (isSyntax(ch)) return syntax
347-
if (/[$]/.test(ch)) return dollar
348-
if (/["]/.test(ch)) return strDouble
349-
if (/[']/.test(ch)) return strSingle
345+
if (ch.includes('$')) return dollar
346+
if (ch.includes('"')) return strDouble
347+
if (ch.includes("'")) return strSingle
350348
return word
351349
}
352350

@@ -366,13 +364,13 @@ export function formatCmd(cmd?: string): string {
366364
}
367365

368366
function dollar() {
369-
if (/[']/.test(ch)) return str
367+
if (ch.includes("'")) return str
370368
return root
371369
}
372370

373371
function str() {
374-
if (/[']/.test(ch)) return strEnd
375-
if (/[\\]/.test(ch)) return strBackslash
372+
if (ch.includes("'")) return strEnd
373+
if (ch.includes('\\')) return strBackslash
376374
return str
377375
}
378376

@@ -385,12 +383,12 @@ export function formatCmd(cmd?: string): string {
385383
}
386384

387385
function strDouble() {
388-
if (/["]/.test(ch)) return strEnd
386+
if (ch.includes('"')) return strEnd
389387
return strDouble
390388
}
391389

392390
function strSingle() {
393-
if (/[']/.test(ch)) return strEnd
391+
if (ch.includes("'")) return strEnd
394392
return strSingle
395393
}
396394

test/util.test.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,8 @@ describe('util', () => {
7474
assert.equal(parseDuration('2s'), 2000)
7575
assert.equal(parseDuration('500ms'), 500)
7676
assert.equal(parseDuration('2m'), 120000)
77+
assert.throws(() => parseDuration('f2ms'))
78+
assert.throws(() => parseDuration('2mss'))
7779
assert.throws(() => parseDuration('100'))
7880
assert.throws(() => parseDuration(NaN))
7981
assert.throws(() => parseDuration(-1))

0 commit comments

Comments
 (0)