js商品多单位转换
1、日常开发中,经常遇到,比如:倒计时剩余 xx天xx时xx分xx秒,
2、下面我们是商品的单位转换: 如1000个商品转换为 xx箱xx包xx个
/**
* 问题描述:
* 1. 根据相关数量 X 换算出对应的(车、箱、包、个)
* 单位:
* 车: 50个
* 箱: 10个
* 包: 3个
* 个: 1个
*/
// 单位列表
const unitList = [
{
unitKey: '1',
name: '个',
rate: 1
},
{
unitKey: '2',
name: '包',
rate: 30
},
{
unitKey: '3',
name: '箱',
rate: 100
},
{
unitKey: '4',
name: '车',
rate: 300
}
]
/**
* 单位转换
* @param {Number} count 总数
* @param {String} unitKey 单位key
* @return {String}
*/
function unitFormat(count, unitKey) {
const baseUnitRate = unitList.find(u => u.unitKey === unitKey) // 找出单位
if (!baseUnitRate) return []
// 把单位转为基本单位
let countRate = count * baseUnitRate.rate
for (var i = unitList.length - 1; i >= 0; i--) {
const { rate } = unitList[i]
unitList[i].formatVal = Math.floor(countRate / rate) // 给list中添加了format中添加了字段
countRate = countRate % rate // 存储余数
// 如果余数为0,则直接跳出
if (countRate === 0) break
}
return unitList
}
const formatValue = unitFormat(583517, '1')
const formatStr = formatValue.reverse().reduce((res, cur) => {
res += `${cur.formatVal || 0}${cur.name}`
return res
}, '')
console.log(formatValue) // List
console.log(formatStr) // 1945车0箱0包17个