如何编写unlockedChest函数实现宝箱解锁逻辑并保持状态?
宝箱解锁函数实现问题
需求说明
- 当
count值等于或大于宝箱初始价格的一半时,将该宝箱的open属性设为true - 宝箱一旦被打开(
open为true),即使后续count回落至0,open也不会被重置为false
示例数据与测试用例
openData = { count: 0, chest: [ { id: 'Chest1', price: 50, open: false }, { id: 'Chest2', price: 200, open: false }, { id: 'Chest3', price: 500, open: false } ] }; // 测试用例1:count达标时解锁对应宝箱 ("changes `open` to `true` when the count is equal to or larger than half the initial price of the id", function() { openData.count = 100; code.unlockedChest(openData.chest, openData.count); expect(openData.chest[0].open).to.equal(true); expect(openData.chest[1].open).to.equal(true); expect(openData.chest[2].open).to.equal(false); }); // 测试用例2:已解锁宝箱不会因count回落而关闭 ('does not set `open` to `false` once a chest has been opened, even if the count drops again', function() { openData.count = 100; code.unlockedChest(openData.chest, openData.count); openData.count = 0; code.unlockedChest(openData.chest, openData.count); expect(openData.chest[0].open).to.equal(true); expect(openData.chest[1].open).to.equal(true); expect(openData.chest[2].open).to.equal(false); });
当前尝试的代码
function unlockedChest (id, count) { if (count === chest.price || count <= chest.price) { return chest.open === true; } if (chest.open === true) { return true; // trying to keep the value that it was changed to } }
存在的问题
- 参数不匹配:测试用例传入的是宝箱数组和
count,但函数定义的参数是id和count,无法正确接收数组 - 逻辑错误:
- 未处理“价格一半”的核心条件,当前判断逻辑和需求完全不符
- 没有遍历宝箱数组,无法批量处理每个宝箱的状态
- 仅返回布尔值,未实际修改宝箱的
open属性
- 未实现“一旦打开就保持true”的逻辑:没有判断宝箱当前状态,可能导致已解锁状态被错误重置
正确实现代码
function unlockedChest(chestArray, count) { // 遍历每个宝箱 chestArray.forEach(chest => { // 已打开的宝箱直接跳过,不做修改 if (chest.open) { return; } // 计算宝箱价格的一半 const halfPrice = chest.price / 2; // 当count达标时,将宝箱设为打开状态 if (count >= halfPrice) { chest.open = true; } }); }
代码说明
- 函数参数与测试用例传参匹配,接收宝箱数组和
count值 - 用
forEach遍历所有宝箱,批量处理状态 - 优先判断宝箱是否已打开,确保已解锁状态不会被修改
- 计算价格一半的阈值,判断
count达标后修改open属性
这个实现完全符合两个测试用例的要求:
- 测试用例1中,
count=100:Chest1(50/2=25,100≥25)、Chest2(200/2=100,100≥100)被解锁,Chest3(500/2=250,100<250)保持关闭 - 测试用例2中,
count回落至0时,已解锁的宝箱会被跳过,状态保持true
内容的提问来源于stack exchange,提问作者user19522560
相关产品推荐
相关产品推荐

