const transformUnit = (unit: 'NUM'|'FLOW', value: number) => {
const data = {
NUM: [{value: 100000000, unit: '亿'}, {value: 10000, unit: '万'}],
FLOW: [{value: 1099511627776, unit: 'TB'}, {value: 1073741824, unit: 'GB'}, {value: 1048576, unit: 'MB'},
{value: 1024, unit: 'KB'}, {value: 1, unit: 'Bytes'}],
};
const tempObj = data[unit];
if (!tempObj) {
return 'transformUnit 参数错误';
}
for (const v of tempObj) {
if (value >= v.value) {
return `${Math.round(value / v.value * 100) / 100}${v.unit}`;
}
}
return value;
};
console.log(transformUnit('NUM', 10000 * 10000));
console.log(transformUnit('FLOW', 1024 * 1024 * 1024 * 1024));
写成可以扩展的(瞎写)
interface IMeasure {
value: number;
unit: string;
}
interface IConfig {
[key: string]: IMeasure[];
}
class TransformUnit {
private data: IConfig = {
NUM: [
{value: 100000000, unit: '亿'},
{value: 10000, unit: '万'}
],
FLOW: [
{value: 1099511627776, unit: 'TB'},
{value: 1073741824, unit: 'GB'},
{value: 1048576, unit: 'MB'},
{value: 1024, unit: 'KB'},
{value: 1, unit: 'Bytes'},
]
}
public setConfig(config: IConfig) {
const configObj = JSON.parse(JSON.stringify(config || {}));
if (Object.keys(configObj).length) {
const [k, v] = Object.entries<IMeasure[]>(configObj)[0];
this.data[k] = v.sort((a, b) => b.value - a.value);
}
}
public get(unit: 'NUM'|'FLOW'|string, value: number) {
let tempObj = this.data[unit];
if (!tempObj) {
throw 'transformUnit.get 参数错误';
}
for (const v of tempObj) {
if (value >= v.value) {
return Math.round(value / v.value * 100) / 100 + v.unit;
}
}
return value;
}
}
const transformUnit1 = new TransformUnit();
console.log(transformUnit1.get('NUM', 10000));
console.log(transformUnit1.get('FLOW', 1024 * 1024 * 1024 * 1024));
transformUnit1.setConfig({
'个': [
{value: 1, unit: '个'},
{value: 100, unit: '百个'},
{value: 1000, unit: '千个'}
]
});
const res = transformUnit1.get('个', 3000);
console.log(res);