negative sizes support, add more tests

This commit is contained in:
Dave Eddy 2015-09-01 13:47:35 -04:00
parent 12c9cb64a6
commit d76535b4d2
2 changed files with 11 additions and 2 deletions

View File

@ -206,12 +206,15 @@ function humanSizeFromBytes(opts, bytes) {
if (opts.narrow) {
sizes = ['B', 'K', 'M', 'G', 'T', 'P'];
}
var template = opts.narrow ? '%s%s' : '%s %s';
var template = opts.narrow ? '%s%s%s' : '%s%s %s';
if (bytes === 0) {
return '0 B';
}
var sign = bytes < 0 ? '-' : '';
bytes = Math.abs(bytes);
var i = Number(Math.floor(Math.log(bytes) / Math.log(1024)));
var s = String(bytes / Math.pow(1024, i));
var hasDecimal = s.indexOf('.') !== -1;
@ -238,7 +241,7 @@ function humanSizeFromBytes(opts, bytes) {
//var precision1 = (s.indexOf('.') === -1
// ? s + '.0' : s.slice(0, s.indexOf('.') + 2));
return format(template, s, sizes[i]);
return format(template, sign, s, sizes[i]);
}
function capitalize(s) {

View File

@ -43,8 +43,14 @@ test('humanDurationFromMs', function (t) {
test('humanSizeFromBytes', function (t) {
var humanSizeFromBytes = common.humanSizeFromBytes;
t.equal(humanSizeFromBytes(-1), '-1.0 B');
t.equal(humanSizeFromBytes(0), '0 B');
t.equal(humanSizeFromBytes(1), '1.0 B');
t.equal(humanSizeFromBytes({}, 0), '0 B');
t.equal(humanSizeFromBytes({}, 1024), '1.0 KiB');
t.equal(humanSizeFromBytes({narrow: true}, 1024), '1K');
t.equal(humanSizeFromBytes({precision: 2}, 1024), '1.00 KiB');
t.end();
});