基于指定总量填充对象数组amountFilled字段的实现需求
数组填充与总量扣除逻辑实现
需求说明
现有一个包含数量属性的对象数组,每个对象包含amountToFill(待填充值)和amountFilled(已填充值)字段。要求:
- 给定初始总量
amount=50,自动将amountFilled填充至amountToFill的数值,同时逐步扣除amount,直至amount为0 - 若
amountFilled初始值大于0,计算总量扣除时仅针对还需填充的差值(即amountToFill - amountFilled)
初始数组
amountArray = [ { option:'text', amountToFill: 5, amountFilled:0, }, { option:'text1', amountToFill: 3, amountFilled:1, }, { option:'text2', amountToFill: 10, amountFilled:0, }, { option:'text3', amountToFill: 4, amountFilled:1, }, { option:'text4', amountToFill: 4, amountFilled:1, }, { option:'text5', amountToFill: 15, amountFilled:0, }, { option:'text6', amountToFill: 5, amountFilled:2, }, { option:'text7', amountToFill:25, amountFilled:3, }, { option:'text8', amountToFill: 15, amountFilled:0, }, { option:'text9', amountToFill: 25, amountFilled:0, }, { option:'text10', amountToFill: 5, amountFilled:0, } ];
期望结果
amountArray1 = [ { option:'text', amountToFill: 5, amountFilled:5, filled: true }, { option:'text1', amountToFill: 3, amountFilled:3, filled: true }, { option:'text2', amountToFill: 10, amountFilled:10, filled: true }, { option:'text3', amountToFill: 4, amountFilled:4, filled: true }, { option:'text4', amountToFill: 4, amountFilled:4, filled: true }, { option:'text5', amountToFill: 15, amountFilled:15, filled: true }, { option:'text6', amountToFill: 5, amountFilled:5, filled: true }, { option:'text7', amountToFill:25, amountFilled:12, // 此时amount已耗尽为0 filled: true }, { option:'text8', amountToFill: 15, amountFilled:0, filled: false }, { option:'text9', amountToFill: 25, amountFilled:0, filled: false }, { option:'text10', amountToFill: 5, amountFilled:0, filled: false } ];
实现逻辑
- 维护剩余可分配的
amount值,遍历数组每个对象 - 计算当前对象还需填充的数量:
need = amountToFill - amountFilled - 剩余
amount >= need时:- 将
amountFilled设为amountToFill - 剩余
amount扣除need - 标记
filled: true
- 将
- 剩余
amount < need时:- 若剩余
amount > 0:把剩余量全部分配给当前对象,amount置0,标记filled: true - 若剩余
amount == 0:保持原amountFilled不变,标记filled: false
- 若剩余
示例代码
function fillAmounts(originalArray: any[], initialAmount: number) { let remainingAmount = initialAmount; // 深拷贝原数组,避免修改原数据 return originalArray.map(item => { const newItem = {...item}; const need = newItem.amountToFill - newItem.amountFilled; if (remainingAmount <= 0) { newItem.filled = false; return newItem; } if (need <= remainingAmount) { newItem.amountFilled = newItem.amountToFill; remainingAmount -= need; newItem.filled = true; } else { newItem.amountFilled += remainingAmount; remainingAmount = 0; newItem.filled = true; } return newItem; }); } // 使用示例 const amountArray = [/* 初始数组内容 */]; const result = fillAmounts(amountArray, 50); console.log(result);
内容的提问来源于stack exchange,提问作者John w.
相关产品推荐
相关产品推荐

