关于单位转换问题(M, G, TB, PB)


/**
 * @param array such as [1024, 2048, 20480, 102400]
 * @param unit such as M
 * @return return proper unit from units
 */
var units = ['M', 'G', 'TB', 'PB'];
function solveUnit(array, unit) { 
    var power, unitIndex;
    var lastChooseIndex = units.indexOf(unit);
    for(var i = 0, len = array.length; i < len; i++) {
        power = 1024; // set back to 1024
        unitIndex = units.indexOf(unit);
        while(Math.floor(array[i] / power) > 100 ) {
            unitIndex++;
            power = power * power;
        }
        if(unitIndex > lastChooseIndex) {
            lastChooseIndex = unitIndex;
        }   
    }
    return units[lastChooseIndex];
}
function formatArray(array, unit, _get) {
    if(unit == _get) {
        array.forEach(function(item) {
            console.log(item + ''+unit);
        });
        return array;
    }
    var gap = units.indexOf(_get) - units.indexOf(unit);
    var power = 1024;
    while(gap>1) {
        power = power * power;
        gap--;
    }
    var ret  = array.map(function(item) {
        console.log( (item/power).toFixed(1) + '' + _get );
        return (item/power).toFixed(1);
    });
    return ret;
}
// test
var array = [112640, 141312];
var unit = 'M';
var _get = solveUnit(array, unit);
formatArray(array, unit, _get);

发表评论

电子邮件地址不会被公开。 必填项已用*标注

您可以使用这些HTML标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>