Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added options.from #101

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 18 additions & 1 deletion index.js
Expand Up @@ -27,7 +27,7 @@ module.exports = function(val, options) {
options = options || {};
var type = typeof val;
if (type === 'string' && val.length > 0) {
return parse(val);
return options.from ? calcFrom(val, options.from) : parse(val);
} else if (type === 'number' && isNaN(val) === false) {
return options.long ? fmtLong(val) : fmtShort(val);
}
Expand Down Expand Up @@ -157,3 +157,20 @@ function plural(ms, n, name) {
}
return Math.ceil(ms / n) + ' ' + name + 's';
}

/**
* Calculate the milliseconds for given date
* @param {String} str
* @param {Date} date
* @return {Number}
* @api private
*/
function calcFrom(str, date) {
if (new Date(date).toString() === 'Invalid Date' || date === true)
throw new Error(
'option.from is not a valid Date. options.from=' + JSON.stringify(date)
);
var ms = parse(str);

return new Date(date).getTime() + ms;
}
20 changes: 20 additions & 0 deletions tests.js
Expand Up @@ -229,3 +229,23 @@ describe('ms(invalid inputs)', function() {
}).to.throwError();
});
});

describe('ms(string, { from: Number })', function() {
it('should throw an error when options.from is true', function() {
expect(function() {
ms('1h', { from: true });
}).to.throwError();
});

it('should ignore options.from when it is not Number', function() {
expect(ms('1h', { from: '' })).to.be(3600000);
expect(ms('1h', { from: NaN })).to.be(3600000);
});

it('should add time to unix epoch time', function() {
expect(ms('1ms', { from: new Date(0) })).to.be(1);
expect(ms('1s', { from: new Date(0) })).to.be(1000);
expect(ms('1m', { from: new Date(0) })).to.be(60000);
expect(ms('1h', { from: new Date(0) })).to.be(3600000);
});
});