Zorbing icon

ByteConverter.ts

Zorbing | PRO | 05/23/16 12:28:47 PM UTC | 0 ⭐ | 266 👁️ | Never ⏰ | []
JavaScript |

2.28 KB

|

None

|

0 👍

/

0 👎

// for Typescript 1.7+
const si = false;
const byteUnitSize = si ? 1000 : 1024;
const decimalPoint = ',';
const thousandsSeperator = '.';
const filesizeRegex = /([\d\.,]+)\s*([KMGTPE]?i?B(?:ytes)?)\b/i;
const typeFactor = {
       'B': byteUnitSize ** 0
    , 'KB': byteUnitSize ** 1
    , 'MB': byteUnitSize ** 2
    , 'GB': byteUnitSize ** 3
    , 'TB': byteUnitSize ** 4
    , 'PB': byteUnitSize ** 5
    , 'EB': byteUnitSize ** 6
};
const byteUnits = si ? 'kMGTPE' : 'KMGTPE';
 
 
export class ByteConverter
{
    /**
     * Returns the size in bytes represented by the given string.
     *
     * @param  {!string} str
     *                   The size as a string
     * @return {number}  The size in bytes
     */
    public static fromString(str: string): number
    {
        const match = str.match(filesizeRegex);
        if (!match)
        {
            return null;
        }
 
        let size = parseFloat(match[1].replace(/,/g, ''));
        const sizeType = match[2].replace(/i|ytes/g, '').toUpperCase();
        size *= typeFactor[sizeType];
        // always round to the next higher integer
        size = Math.ceil(size);
        return size;
    }
 
    /**
     * Returns the given size in bytes as a readable string.
     *
     * @param  {number} bytes
     *                  The size in bytes
     * @param  {number=0} padp
     *                    How many decimal places should be displayed (padp = position after decimal point)
     * @return {string}  The size as a readable string
     */
    public static toString(bytes: number, padp = 0): string
    {
        let exp = 0;
        let type = 'B';
        const sign = bytes >= 0 ? '' : '-';
        bytes = Math.abs(bytes);
        if (bytes >= byteUnitSize)
        {
            exp = Math.min(Math.floor(Math.log(bytes) / Math.log(byteUnitSize)), byteUnits.length);
            type = byteUnits.charAt(exp-1) + (si ? '' : 'i') + 'B';
        }
        let num = bytes / (byteUnitSize ** exp);
        if (exp > 0)
        {
            const roundFactor = (10 ** padp);
            num = Math.round(num * roundFactor) / roundFactor;
        }
 
        // transform the decimal point into a comma
        let numStr = num.toString(10).replace('.', decimalPoint);
        // insert a thousand seperator if needed
        if (num >= 1000)
        {
            const parts = numStr.split(decimalPoint);
            parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousandsSeperator);
            numStr = parts.join(decimalPoint);
        }
        return sign + numStr + ' ' + type;
    }
}

Comments