nhb-toolbox
Version:
A versatile collection of smart, efficient, and reusable utility functions, classes and types for everyday development needs.
30 lines (29 loc) • 1.16 kB
JavaScript
import { isNonEmptyString, isNumber } from '../guards/primitives.js';
import { isNumericString } from '../guards/specials.js';
import { MS_MAP } from './constants.js';
import { isTimeWithUnit } from './guards.js';
export function parseMSec(value, sec = false) {
if (isNumber(value) || isNumericString(value)) {
return _parse(`${value}s`, sec);
}
else if (isTimeWithUnit(value)) {
return _parse(value, sec);
}
else {
return NaN;
}
}
function _parse(str, sec = false) {
if (!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 = MS_MAP[unit];
if (!multiplier)
throw new RangeError(`Unknown unit "${unit}"!`);
const ms = parseFloat(match.groups.value) * multiplier;
return sec ? ms / 1000 : ms;
}