Skip to content

Commit

Permalink
chore: refactor digital size
Browse files Browse the repository at this point in the history
  • Loading branch information
zdm committed Jan 19, 2025
1 parent 3eb0268 commit f81e909
Showing 1 changed file with 14 additions and 49 deletions.
63 changes: 14 additions & 49 deletions lib/digital-size.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,18 +82,6 @@ export default class DigitalSize {
#nginx;
#formatDifitalSizeParam;

// XXX remove
#negative = false;
#units = {
"petabyte": 0,
"terabyte": 0,
"gigabyte": 0,
"megabyte": 0,
"kilobyte": 0,
"byte": 0,
};

// XXX
constructor ( size, unit = "byte" ) {
if ( size ) {

Expand Down Expand Up @@ -143,35 +131,6 @@ export default class DigitalSize {
}

this.#bytes = Math.trunc( this.#bytes );

// XXX --------------------------

this.#units.byte = Math.abs( this.#bytes );

if ( this.#units.byte >= 1000 ) {
this.#units.kilobyte += Math.floor( this.#units.byte / 1000 );
this.#units.byte = this.#units.byte % 1000;
}

if ( this.#units.kilobyte >= 1000 ) {
this.#units.megabyte += Math.floor( this.#units.kilobyte / 1000 );
this.#units.kilobyte = this.#units.kilobyte % 1000;
}

if ( this.#units.megabyte >= 1000 ) {
this.#units.gigabyte += Math.floor( this.#units.megabyte / 1000 );
this.#units.megabyte = this.#units.megabyte % 1000;
}

if ( this.#units.gigabyte >= 1000 ) {
this.#units.terabyte += Math.floor( this.#units.gigabyte / 1000 );
this.#units.gigabyte = this.#units.gigabyte % 1000;
}

if ( this.#units.terabyte >= 1000 ) {
this.#units.petabyte += Math.floor( this.#units.terabyte / 1000 );
this.#units.terabyte = this.#units.terabyte % 1000;
}
}

// static
Expand Down Expand Up @@ -214,21 +173,27 @@ export default class DigitalSize {
}

// public
// XXX notmalize
toString () {
if ( this.#string == null ) {
const units = [];
const units = [],
sign = this.#bytes < 0
? "-"
: "";

for ( const [ unit, value ] of Object.entries( this.#units ) ) {
if ( !value ) continue;
let bytes = Math.abs( this.#bytes );

units.push( value + " " + UNIT_ABBR[ unit ] );
for ( const [ unit, abbr ] of Object.entries( UNIT_ABBR ) ) {
if ( bytes >= UNIT_BYTES[ unit ] ) {
const remainder = bytes % UNIT_BYTES[ unit ];

units.push( sign + ( bytes - remainder ) / UNIT_BYTES[ unit ] + " " + abbr );

bytes = remainder;
}
}

if ( units.length ) {
this.#string = ( this.#negative
? "-"
: "" ) + units.join( " " );
this.#string = units.join( " " );
}
else {
this.#string = "0 " + UNIT_ABBR.byte;
Expand Down

0 comments on commit f81e909

Please sign in to comment.