Skip to content

Commit

Permalink
fix: parse leading zeroes in milliseconds (#50)
Browse files Browse the repository at this point in the history
Fixes #49, which identified a regression from #47
  • Loading branch information
dvorakroth authored Jan 29, 2024
1 parent 1b15151 commit 8bad2de
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 24 deletions.
41 changes: 17 additions & 24 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -157,34 +157,27 @@ function readNextNum (interval) {
}

function parseMillisecond (interval) {
const previousPosition = position.value
const currentValue = readNextNum(interval)

if (currentValue < 10) {
return currentValue * 100
}

if (currentValue < 100) {
return currentValue * 10
}

if (currentValue < 1000) {
return currentValue
}

if (currentValue < 10000) {
return currentValue / 10
}

if (currentValue < 100000) {
return currentValue / 100
}

if (currentValue < 1000000) {
return currentValue / 1000
const valueStringLength = position.value - previousPosition

switch (valueStringLength) {
case 1:
return currentValue * 100
case 2:
return currentValue * 10
case 3:
return currentValue
case 4:
return currentValue / 10
case 5:
return currentValue / 100
case 6:
return currentValue / 1000
}

// slow path
const remainder = currentValue.toString().length - 3
const remainder = valueStringLength - 3
return currentValue / Math.pow(10, remainder)
}

Expand Down
6 changes: 6 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@ test(function (t) {
t.equal(interval('00:00:00.5000').milliseconds, 500)
t.equal(interval('00:00:00.100500').milliseconds, 100.5)
t.equal(interval('00:00:00.1005005').milliseconds, 100.5005)
t.equal(interval('00:00:00.05').milliseconds, 50)
t.equal(interval('00:00:00.005').milliseconds, 5)
t.equal(interval('00:00:00.0005').milliseconds, 0.5)
t.equal(interval('00:00:00.00005').milliseconds, 0.05)
t.equal(interval('00:00:00.000005').milliseconds, 0.005)
t.equal(interval('00:00:00.0000005').milliseconds, 0.0005)

t.test('zero', function (t) {
const result = interval('00:00:00')
Expand Down

0 comments on commit 8bad2de

Please sign in to comment.