-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathisDuration.js
More file actions
59 lines (52 loc) · 1.07 KB
/
isDuration.js
File metadata and controls
59 lines (52 loc) · 1.07 KB
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
import assertString from './util/assertString';
const BaseDurationUnits = [
'Years',
'Year',
'Yrs',
'Yr',
'Y',
'Weeks',
'Week',
'W',
'Days',
'Day',
'D',
'Hours',
'Hour',
'Hrs',
'Hr',
'H',
'Minutes',
'Minute',
'Mins',
'Min',
'M',
'Seconds',
'Second',
'Secs',
'Sec',
's',
'Milliseconds',
'Millisecond',
'Msecs',
'Msec',
'Ms',
];
const AllDurationUnits = new Set(BaseDurationUnits.flatMap(unit => [
unit, unit.toUpperCase(), unit.toLowerCase(),
]));
/**
* Checks if the string is a valid duration.
* It is designed to match the format used by the [ms](https://github.com/vercel/ms) package.
* The duration can be "1 week","2 days","1h", "30m", "15 s", etc.
*/
export default function isDuration(value) {
assertString(value);
// using the same number regex used in the `ms` package
const match = value.match(/^(?<nbr>-?(?:\d+)?\.?\d+)(?:\s?(?<unit>[a-zA-Z]+))?$/);
if (!match || !match.groups) {
return false;
}
const { unit } = match.groups;
return unit === undefined || AllDurationUnits.has(unit);
}