js商品多单位转换

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个
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值