How to convert any digital storage unit into all others (B, KB, MB, GB, TB, PB, EB, ZB, YB) in JavaScript

1 Answer

0 votes
/*
    Digital storage conversion table:
    Each unit is a power of 1024 relative to bytes.

    Bytes (B)      = 1024^0
    Kilobytes (KB) = 1024^1
    Megabytes (MB) = 1024^2
    Gigabytes (GB) = 1024^3
    Terabytes (TB) = 1024^4
    Petabytes (PB) = 1024^5
    Exabytes (EB)  = 1024^6
    Zettabytes (ZB)= 1024^7
    Yottabytes (YB)= 1024^8
*/

// Convert any unit to bytes using its exponent
function toBytes(value, exponent) {
    // 1024^exponent gives the multiplier for the unit
    return value * Math.pow(1024, exponent);
}

// Convert bytes to any unit using its exponent
function fromBytes(bytes, exponent) {
    return bytes / Math.pow(1024, exponent);
}

// Print all conversions from a given byte value
function printAll(bytes) {
    const names = [
        "Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"
    ];

    names.forEach((name, exp) => {
        console.log(`${name.padStart(8)}: ${fromBytes(bytes, exp).toFixed(6)}`);
    });
}

console.log("Digital Storage Unit Converter\n");

const readline = require("readline").createInterface({
    input: process.stdin,
    output: process.stdout
});

readline.question("Enter value: ", valueInput => {
    const value = parseFloat(valueInput);

    readline.question("Enter unit (B, KB, MB, GB, TB, PB, EB, ZB, YB): ", unit => {

        // Map unit string to exponent
        let exponent = -1;

        if (unit === "B")  exponent = 0;
        if (unit === "KB") exponent = 1;
        if (unit === "MB") exponent = 2;
        if (unit === "GB") exponent = 3;
        if (unit === "TB") exponent = 4;
        if (unit === "PB") exponent = 5;
        if (unit === "EB") exponent = 6;
        if (unit === "ZB") exponent = 7;
        if (unit === "YB") exponent = 8;

        if (exponent < 0) {
            console.log("Unknown unit.");
            readline.close();
            return;
        }

        // Convert input to bytes
        const bytes = toBytes(value, exponent);

        // Print all conversions
        console.log("\nConverted values:");
        printAll(bytes);

        readline.close();
    });
});


/*
run:

Digital Storage Unit Converter

Enter value: 380
Enter unit (B, KB, MB, GB, TB, PB, EB, ZB, YB): PB

Converted values:
   Bytes: 427841964600197120.000000
      KB: 417814418554880.000000
      MB: 408021893120.000000
      GB: 398458880.000000
      TB: 389120.000000
      PB: 380.000000
      EB: 0.371094
      ZB: 0.000362
      YB: 0.000000

*/

 



answered Aug 28 by avibootz

Related questions

...