Skip to content

Instantly share code, notes, and snippets.

@vaidd4

vaidd4/CustomPrettyMs.js

Last active Feb 1, 2018
Embed
What would you like to do?
pretty-ms with custom units https://github.com/sindresorhus/pretty-ms/
'use strict';
const parseMs = require('parse-ms');
const plur = require('plur');
const units = [{ s: 'y', l: 'year' },
{ s: 'd', l: 'day' },
{ s: 'h', l: 'hour' },
{ s: 'm', l: 'minute' },
{ s: 's', l: 'second' },
{ s: 'ms', l: 'millisecond' }];
module.exports = (ms, opts) => {
if (!Number.isFinite(ms)) {
throw new TypeError('Expected a finite number');
}
opts = opts || {};
if (!opt.units) opt.units = units;
if (ms < 1000) {
const msDecimalDigits = typeof opts.msDecimalDigits === 'number' ? opts.msDecimalDigits : 0;
return (msDecimalDigits ? ms.toFixed(msDecimalDigits) : Math.ceil(ms)) + (opts.verbose ? ' ' + plur(opt.units[5].l, Math.ceil(ms)) : opt.units[5].s);
}
const ret = [];
const add = (val, unit, valStr) => {
if (val === 0) {
return;
}
const postfix = opts.verbose ? ' ' + plur(unit.l, val) : unit.s;
ret.push((valStr || val) + postfix);
};
const parsed = parseMs(ms);
add(Math.trunc(parsed.days / 365), opt.units[0]);
add(parsed.days % 365, opt.units[1]);
add(parsed.hours, opt.units[2]);
add(parsed.minutes, opt.units[3]);
if (opts.compact) {
add(parsed.seconds, 'second', 's');
return '~' + ret[0];
}
const sec = ms / 1000 % 60;
const secDecimalDigits = typeof opts.secDecimalDigits === 'number' ? opts.secDecimalDigits : 1;
const secFixed = sec.toFixed(secDecimalDigits);
const secStr = opts.keepDecimalsOnWholeSeconds ? secFixed : secFixed.replace(/\.0+$/, '');
add(sec, opt.units[4], secStr);
return ret.join(' ');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment