forked from jkroso/parse-duration
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
76 lines (59 loc) · 1.25 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
'use strict'
var durationRE = /(-?(?:\d+\.?\d*|\d*\.?\d+)(?:e[-+]?\d+)?)\s*([\p{L}]*)/uig
module.exports = parse
// enable default import syntax in typescript
module.exports.default = parse
/**
* conversion ratios
*/
parse.nanosecond =
parse.ns = 1 / 1e6
parse['µs'] =
parse['μs'] =
parse.us =
parse.microsecond = 1 / 1e3
parse.millisecond =
parse.ms =
parse[''] = 1
parse.second =
parse.sec =
parse.s = parse.ms * 1000
parse.minute =
parse.min =
parse.m = parse.s * 60
parse.hour =
parse.hr =
parse.h = parse.m * 60
parse.day =
parse.d = parse.h * 24
parse.week =
parse.wk =
parse.w = parse.d * 7
parse.month =
parse.b =
parse.d * (365.25 / 12)
parse.year =
parse.yr =
parse.y = parse.d * 365.25
/**
* convert `str` to ms
*
* @param {String} str
* @param {String} format
* @return {Number}
*/
function parse(str='', format='ms'){
let results = [];
// ignore commas/placeholders
str = (str+'').replace(/(\d)[,_](\d)/g, '$1$2')
str.replace(durationRE, function(_, n, units){
units = unitRatio(units)
if (units) {
results.push(parseFloat(n, 10) * units);
}
})
return results.map((result) => result / (unitRatio(format) || 1));
}
function unitRatio(str) {
return parse[str] || parse[str.toLowerCase().replace(/s$/, '')]
}