UNPKG

vtils

Version:

一个面向业务的 JavaScript/TypeScript 实用程序库。

73 lines (68 loc) 1.64 kB
"use strict"; exports.__esModule = true; exports.ms = ms; // 参考: https://github.com/vercel/ms/blob/master/src/index.ts var _ms = 1; var _s = _ms * 1000; var _m = _s * 60; var _h = _m * 60; var _d = _h * 24; var _w = _d * 7; var _y = _d * 365.25; var unitToTimes = Object.create({ y: _y, w: _w, d: _d, h: _h, m: _m, s: _s, ms: _ms }); var re = /^(\d+(?:\.\d+)?)(y|w|d|h|m|s|ms)$/; /** * 获取毫秒值。 * * @param value 值 * @param unit 单位 * @param returnSeconds 是否返回秒值 */ /** * 获取毫秒值。 * * @param value 值 * @param returnSeconds 是否返回秒值 */ function ms(value, unit, returnSeconds) { if (typeof unit === 'boolean') { returnSeconds = unit; unit = undefined; } var msValue; if (typeof value === 'string' && value.length > 0) { var match = re.exec(value); if (!match) { throw new TypeError("value \u503C\u975E\u6CD5: value=" + JSON.stringify(value)); } var v = parseFloat(match[1]); var u = match[2]; var t = unitToTimes[u]; msValue = v * t; } else if (typeof value === 'number' && isFinite(value)) { if (unit != null) { if (typeof unit === 'string') { var _t = unitToTimes[unit]; if (!_t) { throw new TypeError("unit \u503C\u975E\u6CD5: unit=" + JSON.stringify(unit)); } msValue = value * _t; } else { throw new TypeError('unit 必须是一个字符串'); } } else { msValue = value; } } else { throw new TypeError('value 必须是字符串或数字'); } return returnSeconds ? Math.round(msValue / 1000) : msValue; }