Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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') {
Expand All @@ -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);
}
}

Expand Down
11 changes: 11 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);