From d76535b4d2bd07de8d531b8d9499929c725382fb Mon Sep 17 00:00:00 2001 From: Dave Eddy Date: Tue, 1 Sep 2015 13:47:35 -0400 Subject: [PATCH] negative sizes support, add more tests --- lib/common.js | 7 +++++-- test/unit/common.test.js | 6 ++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/lib/common.js b/lib/common.js index 3248a83..a6b90d2 100755 --- a/lib/common.js +++ b/lib/common.js @@ -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) { diff --git a/test/unit/common.test.js b/test/unit/common.test.js index 096c377..c32079f 100644 --- a/test/unit/common.test.js +++ b/test/unit/common.test.js @@ -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(); });