Skip to content

Commit

Permalink
fix: enhance duration parser (#884)
Browse files Browse the repository at this point in the history
* perf: replace some regexes with `str.includes()`

* fix: enhance duration parser
  • Loading branch information
antongolub authored Sep 6, 2024
1 parent 5d2ad78 commit 76463de
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 14 deletions.
26 changes: 12 additions & 14 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -284,13 +284,11 @@ export function parseDuration(d: Duration) {
if (typeof d == 'number') {
if (isNaN(d) || d < 0) throw new Error(`Invalid duration: "${d}".`)
return d
} else if (/\d+s/.test(d)) {
return +d.slice(0, -1) * 1000
} else if (/\d+ms/.test(d)) {
return +d.slice(0, -2)
} else if (/\d+m/.test(d)) {
return +d.slice(0, -1) * 1000 * 60
}
if (/^\d+s$/.test(d)) return +d.slice(0, -1) * 1000
if (/^\d+ms$/.test(d)) return +d.slice(0, -2)
if (/^\d+m$/.test(d)) return +d.slice(0, -1) * 1000 * 60

throw new Error(`Unknown duration: "${d}".`)
}

Expand Down Expand Up @@ -344,9 +342,9 @@ export function formatCmd(cmd?: string): string {
function root() {
if (/\s/.test(ch)) return space
if (isSyntax(ch)) return syntax
if (/[$]/.test(ch)) return dollar
if (/["]/.test(ch)) return strDouble
if (/[']/.test(ch)) return strSingle
if (ch.includes('$')) return dollar
if (ch.includes('"')) return strDouble
if (ch.includes("'")) return strSingle
return word
}

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

function dollar() {
if (/[']/.test(ch)) return str
if (ch.includes("'")) return str
return root
}

function str() {
if (/[']/.test(ch)) return strEnd
if (/[\\]/.test(ch)) return strBackslash
if (ch.includes("'")) return strEnd
if (ch.includes('\\')) return strBackslash
return str
}

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

function strDouble() {
if (/["]/.test(ch)) return strEnd
if (ch.includes('"')) return strEnd
return strDouble
}

function strSingle() {
if (/[']/.test(ch)) return strEnd
if (ch.includes("'")) return strEnd
return strSingle
}

Expand Down
2 changes: 2 additions & 0 deletions test/util.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ describe('util', () => {
assert.equal(parseDuration('2s'), 2000)
assert.equal(parseDuration('500ms'), 500)
assert.equal(parseDuration('2m'), 120000)
assert.throws(() => parseDuration('f2ms'))
assert.throws(() => parseDuration('2mss'))
assert.throws(() => parseDuration('100'))
assert.throws(() => parseDuration(NaN))
assert.throws(() => parseDuration(-1))
Expand Down

0 comments on commit 76463de

Please sign in to comment.