wallet-core/node_modules/pretty-ms/index.js

49 lines
1.3 KiB
JavaScript
Raw Normal View History

2017-05-28 00:38:50 +02:00
'use strict';
2017-12-27 19:33:54 +01:00
const parseMs = require('parse-ms');
const plur = require('plur');
2017-05-28 00:38:50 +02:00
2017-12-27 19:33:54 +01:00
module.exports = (ms, opts) => {
if (!Number.isFinite(ms)) {
2017-05-28 00:38:50 +02:00
throw new TypeError('Expected a finite number');
}
opts = opts || {};
if (ms < 1000) {
2017-12-27 19:33:54 +01:00
const msDecimalDigits = typeof opts.msDecimalDigits === 'number' ? opts.msDecimalDigits : 0;
2017-05-28 00:38:50 +02:00
return (msDecimalDigits ? ms.toFixed(msDecimalDigits) : Math.ceil(ms)) + (opts.verbose ? ' ' + plur('millisecond', Math.ceil(ms)) : 'ms');
}
2017-12-27 19:33:54 +01:00
const ret = [];
2017-05-28 00:38:50 +02:00
2017-12-27 19:33:54 +01:00
const add = (val, long, short, valStr) => {
2017-05-28 00:38:50 +02:00
if (val === 0) {
return;
}
2017-12-27 19:33:54 +01:00
const postfix = opts.verbose ? ' ' + plur(long, val) : short;
2017-05-28 00:38:50 +02:00
ret.push((valStr || val) + postfix);
};
2017-12-27 19:33:54 +01:00
const parsed = parseMs(ms);
2017-05-28 00:38:50 +02:00
2017-12-27 19:33:54 +01:00
add(Math.trunc(parsed.days / 365), 'year', 'y');
add(parsed.days % 365, 'day', 'd');
2017-05-28 00:38:50 +02:00
add(parsed.hours, 'hour', 'h');
add(parsed.minutes, 'minute', 'm');
if (opts.compact) {
add(parsed.seconds, 'second', 's');
return '~' + ret[0];
}
2017-12-27 19:33:54 +01:00
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+$/, '');
2017-05-28 00:38:50 +02:00
add(sec, 'second', 's', secStr);
return ret.join(' ');
};