UNPKG

nhb-toolbox

Version:

A versatile collection of smart, efficient, and reusable utility functions, classes and types for everyday development needs.

33 lines (32 loc) 1.31 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseMSec = parseMSec; const primitives_1 = require("../guards/primitives"); const specials_1 = require("../guards/specials"); const constants_1 = require("./constants"); const guards_1 = require("./guards"); function parseMSec(value, sec = false) { if ((0, primitives_1.isNumber)(value) || (0, specials_1.isNumericString)(value)) { return _parse(`${value}s`, sec); } else if ((0, guards_1.isTimeWithUnit)(value)) { return _parse(value, sec); } else { return NaN; } } function _parse(str, sec = false) { if (!(0, primitives_1.isNonEmptyString)(str) || str.length > 100) { throw new RangeError(`Value must be a string with length between 1 and 99!`); } const match = /^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(str); if (!match?.groups) return NaN; const unit = (match.groups.unit ?? 'ms').toLowerCase(); const multiplier = constants_1.MS_MAP[unit]; if (!multiplier) throw new RangeError(`Unknown unit "${unit}"!`); const ms = parseFloat(match.groups.value) * multiplier; return sec ? ms / 1000 : ms; }