From 8bad2dee59d5b19a00297bf1378da907ea4eb90c Mon Sep 17 00:00:00 2001 From: Amit Ron Date: Mon, 29 Jan 2024 23:55:31 +0100 Subject: [PATCH] fix: parse leading zeroes in milliseconds (#50) Fixes #49, which identified a regression from #47 --- index.js | 41 +++++++++++++++++------------------------ test.js | 6 ++++++ 2 files changed, 23 insertions(+), 24 deletions(-) diff --git a/index.js b/index.js index 87dfff0..aba05a5 100644 --- a/index.js +++ b/index.js @@ -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) } diff --git a/test.js b/test.js index 513a1ed..3336941 100644 --- a/test.js +++ b/test.js @@ -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')