nhb-toolbox
Version:
A versatile collection of smart, efficient, and reusable utility functions, classes and types for everyday development needs.
95 lines (94 loc) • 2.97 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.fromNowPlugin = void 0;
const convert_1 = require("../../string/convert");
const constants_1 = require("../constants");
const fromNowPlugin = ($Chronos) => {
const { toNewDate } = $Chronos[constants_1.INTERNALS];
$Chronos.prototype.fromNow = function (level = 'second', wSP = true, time) {
const now = toNewDate(this, time);
const target = this.toDate();
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 unitOrder = [
'year',
'month',
'day',
'hour',
'minute',
'second',
'millisecond',
];
const lvlIdx = unitOrder.indexOf(level);
const parts = [];
const _pushToParts = (value, unit) => {
parts.push((0, convert_1.formatUnitWithPlural)(value, unit));
};
const _isLevelRequired = (unit) => {
return lvlIdx >= unitOrder.indexOf(unit);
};
if (y > 0) {
_pushToParts(y, 'year');
}
if (_isLevelRequired('month') && mo > 0) {
_pushToParts(mo, 'month');
}
if (_isLevelRequired('day') && d > 0) {
_pushToParts(d, 'day');
}
if (_isLevelRequired('hour') && h > 0) {
_pushToParts(h, 'hour');
}
if (_isLevelRequired('minute') && m > 0) {
_pushToParts(m, 'minute');
}
if (_isLevelRequired('second') && s > 0) {
_pushToParts(s, 'second');
}
if (_isLevelRequired('millisecond') && (ms > 0 || parts?.length === 0)) {
_pushToParts(ms, 'millisecond');
}
let prefix = '';
let suffix = '';
if (wSP) {
if (isFuture) {
prefix = 'in ';
}
else {
suffix = ' ago';
}
}
return `${prefix}${parts.length ? parts?.join(' ') : `0 ${level}s`}${suffix}`;
};
};
exports.fromNowPlugin = fromNowPlugin;