HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Dealing with KB, MB, GB and TB and bytes

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withandbytesdealing

Problem

This function is simple, it gets a number of bytes and returns its representation in either Bytes, KB, MB, GB and TB.

As simple as it is, I am sure there are other (and perhaps better ways) to write it.

function kmgtbytes (num) {
    if (num > 0 ){
        if (num < 1024)             { return [num, "Bytes"] }
        if (num < 1048576)          { return [num/1024, "KB"] }
        if (num < 1073741824)       { return [num/1024/1024, "MB"] }
        if (num < 1099511600000)    { return [num/1024/1024/1024, "GB"] }

        return [num/1024/1024/1024/1024, "TB"]
    }

    return num
}

Solution

Here's a slightly less repetitive way to write it since we know each unit is 1024 as large as the last:

function kmgtbytes (num) {
    var unit, units = ["TB", "GB", "MB", "KB", "Bytes"];
    for (unit = units.pop(); units.length && num >= 1024; unit = units.pop()) {
        num /= 1024;
    }
    return [num, unit];
}

Code Snippets

function kmgtbytes (num) {
    var unit, units = ["TB", "GB", "MB", "KB", "Bytes"];
    for (unit = units.pop(); units.length && num >= 1024; unit = units.pop()) {
        num /= 1024;
    }
    return [num, unit];
}

Context

StackExchange Code Review Q#29858, answer score: 15

Revisions (0)

No revisions yet.