forked from jkroso/parse-duration
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.mjs
71 lines (54 loc) · 1.14 KB
/
index.mjs
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
let durationRE = /(-?(?:\d+\.?\d*|\d*\.?\d+)(?:e[-+]?\d+)?)\s*([\p{L}]*)/uig
/**
* 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'){
var result = null
// ignore commas/placeholders
str = (str+'').replace(/(\d)[,_](\d)/g, '$1$2')
str.replace(durationRE, function(_, n, units){
units = unitRatio(units)
if (units) result = (result || 0) + parseFloat(n, 10) * units
})
return result && (result / (unitRatio(format) || 1))
}
function unitRatio(str) {
return parse[str] || parse[str.toLowerCase().replace(/s$/, '')]
}
export default parse