Skip to content

Instantly share code, notes, and snippets.

@cho45
Created January 13, 2009 10:26
Show Gist options
  • Save cho45/46391 to your computer and use it in GitHub Desktop.
Save cho45/46391 to your computer and use it in GitHub Desktop.
function duration (str) {
var ret = 0, units = arguments.callee.units;
str.replace(/(\d+)\s*(msec|sec|min|hour|day|week|month|year)s?/g, function (_, num, unit) {
ret += +num * units[unit];
});
return ret * 1000;
}
duration.units = {
sec : 1, min : 60, hour : 3600, day : 86400, week : 604800, month : 2592000, year : 31536000
};
this.duration = duration;
#!/usr/bin/env node
TAP();
var duration = require('./duration.js').duration
is(duration("1 sec"), 1000);
is(duration("1 min"), 60 * 1000);
is(duration("1 hour"), 60 * 60 * 1000);
is(duration("1 day"), 24 * 60 * 60 * 1000);
is(duration("1 week"), 7 * 24 * 60 * 60 * 1000);
is(duration("1 month"), 30 * 24 * 60 * 60 * 1000);
is(duration("1 year"), 365 * 24 * 60 * 60 * 1000);
is(duration("2 secs"), 2000);
is(duration("2 mins"), 60 * 2000);
is(duration("2 hours"), 60 * 60 * 2000);
is(duration("2 days"), 24 * 60 * 60 * 2000);
is(duration("2 weeks"), 7 * 24 * 60 * 60 * 2000);
is(duration("2 months"), 30 * 24 * 60 * 60 * 2000);
is(duration("2 years"), 365 * 24 * 60 * 60 * 2000);
is(duration("1 day, 12 hour"), (24 * 60 * 60 + 12 * 60 * 60) * 1000);
is(duration("1 day, 12 hours"), (24 * 60 * 60 + 12 * 60 * 60) * 1000);
is(duration("1 day 12 hour"), (24 * 60 * 60 + 12 * 60 * 60) * 1000);
is(duration("1 day 12 hours"), (24 * 60 * 60 + 12 * 60 * 60) * 1000);
done_testing();
function TAP () {
var util = require('util');
this.ok = function (bool, name) {
done_testing.n++;
var r = bool ? 'ok' : 'not ok';
r += " " + done_testing.n;
console.log(name ? r + " # " + name : r);
};
this.is = function (got, expected, name) {
got = util.inspect(got, true, 2);
expected = util.inspect(expected, true, 2);
if (got === expected) {
ok(true, name);
} else {
ok(false, name);
console.log("# got:\n" + got.replace(/^/m, "# "));
console.log("# expected:\n" + expected.replace(/^/m, "# "));
}
}
this.done_testing = function () {
var n = done_testing.n;
console.log('1..' + n);
}
this.done_testing.n = 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment