UNPKG

972 BJavaScriptView Raw
1/**
2 * Converts human friendly time to milliseconds. Supports the format
3 * 00:00:00.000 for hours, minutes, seconds, and milliseconds respectively.
4 * And 0ms, 0s, 0m, 0h, and together 1m1s.
5 *
6 * @param {string|number} time
7 * @return {number}
8 */
9const numberFormat = /^\d+$/;
10const timeFormat = /^(?:(?:(\d+):)?(\d{1,2}):)?(\d{1,2})(?:\.(\d{3}))?$/;
11const timeUnits = {
12 ms: 1,
13 s: 1000,
14 m: 60000,
15 h: 3600000,
16};
17module.exports = (time) => {
18 if (typeof time === 'number') { return time; }
19 if (numberFormat.test(time)) { return +time; }
20 const firstFormat = timeFormat.exec(time);
21 if (firstFormat) {
22 return +(firstFormat[1] || 0) * timeUnits.h +
23 +(firstFormat[2] || 0) * timeUnits.m +
24 +firstFormat[3] * timeUnits.s +
25 +(firstFormat[4] || 0);
26 } else {
27 let total = 0;
28 const r = /(-?\d+)(ms|s|m|h)/g;
29 let rs;
30 while ((rs = r.exec(time)) != null) {
31 total += +rs[1] * timeUnits[rs[2]];
32 }
33 return total;
34 }
35};