前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >关于单位转换问题(M, G, TB, PB)

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

作者头像
用户3579639
发布2018-10-19 14:21:28
8440
发布2018-10-19 14:21:28
举报
代码语言:javascript
复制
/**
 * @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);
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档