Last active
February 1, 2018 15:09
-
-
Save vaidd4/0d83ddba3fb218bb2a7949a4b93ee686 to your computer and use it in GitHub Desktop.
pretty-ms with custom units https://github.com/sindresorhus/pretty-ms/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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