59 lines
1.5 KiB
JavaScript
59 lines
1.5 KiB
JavaScript
function fmtIec(n, si) {
|
|
const base = si ? 1000 : 1024
|
|
const units = si
|
|
? ['', 'k', 'M', 'G', 'T', 'P']
|
|
: ['', 'K', 'M', 'G', 'T', 'P']
|
|
if (n === 0) return '0'
|
|
let sign = n < 0 ? -1 : 1
|
|
let x = Math.abs(n)
|
|
let u = 0
|
|
while (x >= base && u < units.length - 1) {
|
|
x /= base
|
|
u++
|
|
}
|
|
const s =
|
|
x >= 10 || u === 0 ? Math.round(x * 10) / 10 : Math.round(x * 100) / 100
|
|
const t = String(s).replace(/\.0$/, '')
|
|
return (sign < 0 ? '-' : '') + t + units[u]
|
|
}
|
|
|
|
async function run(ctx, argv) {
|
|
let toIec = false
|
|
let toSi = false
|
|
const rest = []
|
|
for (let i = 1; i < argv.length; i++) {
|
|
const a = argv[i]
|
|
if (a === '-h' || a === '--help') {
|
|
ctx.console.log(
|
|
'usage: numfmt [--to=iec|--to=si] [NUMBER]...\nFormat numbers; reads stdin lines if no operands.'
|
|
)
|
|
return
|
|
}
|
|
if (a === '--to=iec') toIec = true
|
|
else if (a === '--to=si') toSi = true
|
|
else if (a.startsWith('-')) {
|
|
ctx.console.error('numfmt: unsupported option ' + a)
|
|
ctx.exitCode = 1
|
|
return
|
|
} else rest.push(a)
|
|
}
|
|
if (!toIec && !toSi) toIec = true
|
|
const nums = []
|
|
if (!rest.length) {
|
|
for (const line of bareStdin(ctx).split('\n')) {
|
|
const t = line.trim()
|
|
if (!t) continue
|
|
nums.push(t)
|
|
}
|
|
} else nums.push(...rest)
|
|
for (const s of nums) {
|
|
const n = parseInt(s, 10)
|
|
if (!Number.isFinite(n)) {
|
|
ctx.console.error('numfmt: invalid number ' + s)
|
|
ctx.exitCode = 1
|
|
return
|
|
}
|
|
ctx.console.log(fmtIec(n, toSi))
|
|
}
|
|
}
|