diff --git a/index.js b/index.js index 656ca4e..c5198c1 100644 --- a/index.js +++ b/index.js @@ -10,6 +10,18 @@ units.month = units.day * 30; units.year = units.day * 365; const regexp = /(second|minute|hour|day|week|month|year)s?/; +const article = /^an?$/; + +// numbered.parse() returns 0 for anything it cannot parse, which is +// indistinguishable from a genuine zero, so only trust 0 when the words say so. +const parseWords = words => { + if (article.test(words)) { + return 1; + } + + const number = numbered.parse(words); + return number === 0 && !/\bzero\b/.test(words) ? Number.NaN : number; +}; const humanInterval = time => { if (!time || typeof time === 'number') { @@ -32,7 +44,7 @@ const humanInterval = time => { if (matchedNumber.length > 0) { number = Number.parseFloat(matchedNumber); if (Number.isNaN(number)) { - number = numbered.parse(matchedNumber); + number = parseWords(matchedNumber); } } diff --git a/test.js b/test.js index 23a6b2f..cd76959 100644 --- a/test.js +++ b/test.js @@ -123,3 +123,14 @@ test('Understands mixed time expressions with singulars', macro, ['one minute an test('Understands 2 digit english numbers', macro, 'thirty three seconds', 33 * units.second); test('Understands mix units + multi digit english numbers', macro, 'hundred and three seconds and twelve minutes', (103 * units.second) + (12 * units.minute)); test('Understands hyphenated numbers', macro, 'three hundred and twenty-five seconds', (325 * units.second)); + +// Articles +test('Understands "a second"', macro, 'a second', units.second); +test('Understands "an hour"', macro, 'an hour', units.hour); +test('Understands "a day"', macro, 'a day', units.day); +test('Understands an article in a mixed expression', macro, 'an hour and 30 minutes', units.hour + (30 * units.minute)); + +// Unparseable quantities are NaN, not zero +test('Returns NaN for an unknown quantity word', macro, + ['a few minutes', 'some seconds', 'several hours', 'couple of hours', 'half an hour'], Number.NaN); +test('Still understands an explicit zero', macro, 'zero seconds', 0);