timestring/index.js

112 lines
2.4 KiB
JavaScript
Raw Normal View History

2016-01-15 12:00:03 +01:00
/**
* Exports
*/
2016-01-15 11:00:12 +01:00
module.exports = Timestring;
2016-01-15 12:00:03 +01:00
/**
* Create a new Timestring instance
*
* @param {Object} opts
* @constructor
*/
function Timestring(opts) {
var defaultOpts = {
2016-01-15 11:00:12 +01:00
hoursPerDay: 24,
daysPerWeek: 7,
weeksPerMonth: 4,
monthsPerYear: 12,
};
2016-01-15 12:00:03 +01:00
opts = opts || {};
this.opts = defaultOpts;
for (var s in opts) { this.opts[s] = opts[s]; }
2016-01-15 11:00:12 +01:00
this.units = {
s: ['s', 'sec', 'secs', 'second', 'seconds'],
m: ['m', 'min', 'mins', 'minute', 'minutes'],
h: ['h', 'hr', 'hrs', 'hour', 'hours'],
d: ['d', 'day', 'days'],
w: ['w', 'week', 'weeks'],
mth: ['mth', 'mths','month', 'months'],
y: ['y', 'yr', 'yrs', 'year', 'years'],
};
this.unitValues = {
s: 1,
m: 60,
h: 3600,
};
2016-01-15 12:00:03 +01:00
this.unitValues.d = this.opts.hoursPerDay * this.unitValues.h;
this.unitValues.w = this.opts.daysPerWeek * this.unitValues.d;
this.unitValues.mth = this.opts.weeksPerMonth * this.unitValues.w;
this.unitValues.y = this.opts.monthsPerYear * this.unitValues.mth;
2016-01-15 11:00:12 +01:00
}
2016-01-15 12:00:03 +01:00
/**
* Parse a timestring
*
* @param {string} string
* @param {string} returnUnit
* @return {string}
*/
2016-01-15 11:00:12 +01:00
2016-01-15 12:00:03 +01:00
Timestring.prototype.parse = function parse(string, returnUnit) {
2016-01-15 11:00:12 +01:00
function getUnitKey(unit) {
2016-01-15 12:00:03 +01:00
for (var k in this.units) {
for (var u in this.units[k]) {
if (unit === this.units[k][u]) {
2016-01-15 11:00:12 +01:00
return k;
}
}
}
throw new Error('The unit [' + unit + '] is not supported by timestring');
}
function convert(value, unit) {
2016-01-15 12:00:03 +01:00
var baseValue = this.unitValues[getUnitKey.call(this, unit)];
2016-01-15 11:00:12 +01:00
return value / baseValue;
}
function getSeconds(value, unit) {
2016-01-15 12:00:03 +01:00
var baseValue = this.unitValues[getUnitKey.call(this, unit)];
2016-01-15 11:00:12 +01:00
return value * baseValue;
}
var totalSeconds = 0;
var groups = string
2016-01-15 12:00:03 +01:00
.toLowerCase()
.replace(/[^\.\w+-]+/g, '')
.match(/[-+]?[0-9]+[a-z]+/g);
2016-01-15 11:00:12 +01:00
if (groups !== null) {
for (var i = 0; i < groups.length; i++) {
var g = groups[i];
var value = g.match(/[0-9]+/g)[0];
var unit = g.match(/[a-z]+/g)[0];
2016-01-15 12:00:03 +01:00
totalSeconds += getSeconds.call(this, value, unit);
2016-01-15 11:00:12 +01:00
}
}
2016-01-15 12:00:03 +01:00
return (returnUnit) ?
convert.call(this, totalSeconds, returnUnit) :
totalSeconds;
2016-01-15 11:00:12 +01:00
};
2016-01-15 12:00:03 +01:00
/**
* Parse a timestring
*
* @param {string} unit
* @param {Object} opts
* @return {string}
*/
String.prototype.parseTime = function parseTime(unit, opts) {
return (new Timestring(opts)).parse(this, unit);
2016-01-15 11:00:12 +01:00
};