Skip to content

Commit

Permalink
Fix binary and bits option being used together (#61)
Browse files Browse the repository at this point in the history
  • Loading branch information
nmoinvaz authored Aug 30, 2020
1 parent 1000ebe commit 1333349
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
16 changes: 15 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,18 @@ const BIT_UNITS = [
'Ybit'
];

const BIBIT_UNITS = [
'b',
'kibit',
'Mibit',
'Gibit',
'Tibit',
'Pibit',
'Eibit',
'Zibit',
'Yibit'
];

/*
Formats the given number using `Number#toLocaleString`.
- If locale is a string, the value is expected to be a locale-key (for example: `de`).
Expand All @@ -59,7 +71,9 @@ module.exports = (number, options) => {
}

options = Object.assign({bits: false, binary: false}, options);
const UNITS = options.bits ? (options.binary ? BIBYTE_UNITS : BIT_UNITS) : BYTE_UNITS;
const UNITS = options.bits ?
(options.binary ? BIBIT_UNITS : BIT_UNITS) :
(options.binary ? BIBYTE_UNITS : BYTE_UNITS);

if (options.signed && number === 0) {
return ' 0 ' + UNITS[0];
Expand Down
15 changes: 12 additions & 3 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,17 @@ test('binary option', t => {
t.is(prettyBytes(10, {binary: true}), '10 B');
t.is(prettyBytes(10.1, {binary: true}), '10.1 B');
t.is(prettyBytes(999, {binary: true}), '999 B');
t.is(prettyBytes(1025, {binary: true}), '1 kB');
t.is(prettyBytes(1025, {binary: true}), '1 kiB');
t.is(prettyBytes(1001, {binary: true}), '1000 B');
t.is(prettyBytes(1e16, {binary: true}), '8.88 PB');
t.is(prettyBytes(1e30, {binary: true}), '827000 YB');
t.is(prettyBytes(1e16, {binary: true}), '8.88 PiB');
t.is(prettyBytes(1e30, {binary: true}), '827000 YiB');
});

test('bits and binary option', t => {
t.is(prettyBytes(0, {bits: true, binary: true}), '0 b');
t.is(prettyBytes(4, {bits: true, binary: true}), '4 b');
t.is(prettyBytes(10, {bits: true, binary: true}), '10 b');
t.is(prettyBytes(999, {bits: true, binary: true}), '999 b');
t.is(prettyBytes(1025, {bits: true, binary: true}), '1 kibit');
t.is(prettyBytes(1e6, {bits: true, binary: true}), '977 kibit');
});

0 comments on commit 1333349

Please sign in to comment.