nhb-toolbox
Version:
A versatile collection of smart, efficient, and reusable utility functions, classes and types for everyday development needs.
97 lines (96 loc) • 3.26 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.durationPlugin = void 0;
const constants_1 = require("../constants");
const durationPlugin = ($Chronos) => {
const { toNewDate } = $Chronos[constants_1.INTERNALS];
const _normalizeDuration = (result, absolute, isFuture) => {
const entries = Object.entries(result);
const updated = { ...result };
if (!absolute && !isFuture) {
for (const [key, value] of entries) {
if (value !== 0) {
updated[key] = value * -1;
}
}
}
else if (absolute) {
for (const [key, value] of entries) {
updated[key] = Math.abs(value);
}
}
return updated;
};
$Chronos.prototype.duration = function (toTime, absolute = true) {
const now = this.toDate();
const target = toNewDate(this, toTime);
const isFuture = target > now;
const from = isFuture ? now : target;
const to = isFuture ? target : now;
const _getDiff = (suffix) => {
return to[`get${suffix}`]() - from[`get${suffix}`]();
};
let y = _getDiff('FullYear'), mo = _getDiff('Month'), d = _getDiff('Date'), h = _getDiff('Hours'), m = _getDiff('Minutes'), s = _getDiff('Seconds'), ms = _getDiff('Milliseconds');
if (ms < 0) {
ms += 1000;
s--;
}
if (s < 0) {
s += 60;
m--;
}
if (m < 0) {
m += 60;
h--;
}
if (h < 0) {
h += 24;
d--;
}
if (d < 0) {
const prevMonth = new Date(to.getFullYear(), to.getMonth(), 0);
d += prevMonth.getDate();
mo--;
}
if (mo < 0) {
mo += 12;
y--;
}
const result = {
years: y,
months: mo,
days: d,
hours: h,
minutes: m,
seconds: s,
milliseconds: ms,
};
return _normalizeDuration(result, absolute, isFuture);
};
$Chronos.prototype.durationString = function (options) {
const { toTime, absolute = true, maxUnits = 7, separator = ', ', style = 'full', showZero = false, } = options ?? {};
const duration = this.duration(toTime, absolute);
const units = {
years: 'y',
months: 'mo',
days: 'd',
hours: 'h',
minutes: 'm',
seconds: 's',
milliseconds: 'ms',
};
const _formatUnit = (unit, value) => {
if (style === 'short') {
return `${value}${units[unit]}`;
}
const $unit = Math.abs(value) === 1 ? unit.slice(0, -1) : unit;
return `${value} ${$unit}`;
};
const parts = Object.entries(duration)
.filter(([_, value]) => showZero || Math.abs(value) > 0)
.slice(0, maxUnits)
.map(([unit, value]) => _formatUnit(unit, value));
return parts.length ? parts.join(separator) : style === 'short' ? '0s' : '0 seconds';
};
};
exports.durationPlugin = durationPlugin;