1 | const minute = 60
|
2 | const hour = minute * 60
|
3 | const day = hour * 24
|
4 | const week = day * 7
|
5 | const year = day * 365.25
|
6 |
|
7 | const REGEX = /^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i
|
8 |
|
9 | module.exports = (str) => {
|
10 | const matched = REGEX.exec(str)
|
11 |
|
12 | if (!matched) {
|
13 | throw new TypeError(`invalid time period format ("${str}")`)
|
14 | }
|
15 |
|
16 | const value = parseFloat(matched[1])
|
17 | const unit = matched[2].toLowerCase()
|
18 |
|
19 | switch (unit) {
|
20 | case 'sec':
|
21 | case 'secs':
|
22 | case 'second':
|
23 | case 'seconds':
|
24 | case 's':
|
25 | return Math.round(value)
|
26 | case 'minute':
|
27 | case 'minutes':
|
28 | case 'min':
|
29 | case 'mins':
|
30 | case 'm':
|
31 | return Math.round(value * minute)
|
32 | case 'hour':
|
33 | case 'hours':
|
34 | case 'hr':
|
35 | case 'hrs':
|
36 | case 'h':
|
37 | return Math.round(value * hour)
|
38 | case 'day':
|
39 | case 'days':
|
40 | case 'd':
|
41 | return Math.round(value * day)
|
42 | case 'week':
|
43 | case 'weeks':
|
44 | case 'w':
|
45 | return Math.round(value * week)
|
46 | case 'year':
|
47 | case 'years':
|
48 | case 'yr':
|
49 | case 'yrs':
|
50 | case 'y':
|
51 | return Math.round(value * year)
|
52 | }
|
53 | }
|