Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add binary option #60

Merged
merged 8 commits into from
Aug 29, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Added binary option to enable 1024 based counting.
  • Loading branch information
SBPLtdProgrammers authored and nmoinvaz committed Aug 11, 2020
commit ae082c6d069fb0471fd7de097db82d05afe3d84c
16 changes: 16 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,22 @@ declare namespace prettyBytes {
```
*/
readonly bits?: boolean;

/**
Format the number using the [Binary Prefix](https://en.wikipedia.org/wiki/Binary_prefix) instead of the [SI Prefix](https://en.wikipedia.org/wiki/SI_Prefix). This can be useful as memory is much better represented by powers of 2.

@default false

```
import prettyBytes = require('pretty-bytes');

prettyBytes(1000, {binary: true});
//=> '1000 bit'
prettyBytes(1024, {binary: true});
//=> '1 kiB'
```
*/
readonly binary?: boolean;
}
}

Expand Down
20 changes: 16 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,18 @@ const BYTE_UNITS = [
'YB'
];

const BIBYTE_UNITS = [
'B',
'kiB',
'MiB',
'GiB',
'TiB',
'PiB',
'EiB',
'ZiB',
'YiB'
];

const BIT_UNITS = [
'b',
'kbit',
Expand Down Expand Up @@ -46,8 +58,8 @@ module.exports = (number, options) => {
throw new TypeError(`Expected a finite number, got ${typeof number}: ${number}`);
}

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

if (options.signed && number === 0) {
return ' 0 ' + UNITS[0];
Expand All @@ -65,9 +77,9 @@ module.exports = (number, options) => {
return prefix + numberString + ' ' + UNITS[0];
}

const exponent = Math.min(Math.floor(Math.log10(number) / 3), UNITS.length - 1);
const exponent = Math.min(Math.floor(Math.log(number) / Math.log(options.binary ? 1024 : 1000)), UNITS.length - 1);
// eslint-disable-next-line unicorn/prefer-exponentiation-operator
number = Number((number / Math.pow(1000, exponent)).toPrecision(3));
number = Number((number / Math.pow(options.binary ? 1024 : 1000, exponent)).toPrecision(3));
const numberString = toLocaleString(number, options.locale);

const unit = UNITS[exponent];
Expand Down