utils.js
1.51 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
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import padStart from 'lodash/padStart'; // Countdown
var timeUnits = [['Y', 1000 * 60 * 60 * 24 * 365], ['M', 1000 * 60 * 60 * 24 * 30], ['D', 1000 * 60 * 60 * 24], ['H', 1000 * 60 * 60], ['m', 1000 * 60], ['s', 1000], ['S', 1]];
export function formatTimeStr(duration, format) {
var leftDuration = duration;
var escapeRegex = /\[[^\]]*]/g;
var keepList = (format.match(escapeRegex) || []).map(function (str) {
return str.slice(1, -1);
});
var templateText = format.replace(escapeRegex, '[]');
var replacedText = timeUnits.reduce(function (current, _ref) {
var _ref2 = _slicedToArray(_ref, 2),
name = _ref2[0],
unit = _ref2[1];
if (current.indexOf(name) !== -1) {
var value = Math.floor(leftDuration / unit);
leftDuration -= value * unit;
return current.replace(new RegExp("".concat(name, "+"), 'g'), function (match) {
var len = match.length;
return padStart(value.toString(), len, '0');
});
}
return current;
}, templateText);
var index = 0;
return replacedText.replace(escapeRegex, function () {
var match = keepList[index];
index += 1;
return match;
});
}
export function formatCountdown(value, config) {
var _config$format = config.format,
format = _config$format === void 0 ? '' : _config$format;
var target = new Date(value).getTime();
var current = Date.now();
var diff = Math.max(target - current, 0);
return formatTimeStr(diff, format);
}