0
這是一個代碼戰爭kata:Vending Machine自動販賣機不返回更改
在這裏,我試圖模擬自動販賣機。到目前爲止,如果插入的信用不夠,我可以退還硬幣,並且我可以讓機器告訴我需要多少更改,但我無法讓它恢復更改。
的變化應當根據自動售貨機在其掌握的硬幣被返回的對象。
//if this.coins = {1:1, 2:0, 4:3, 6:2}
//and the change needed is 8
//the change should be changeObj = {1: 1, 6: 1}
//the machine is sneaky and can return less than the required amount, but not more.
這裏,用於計算變化和返回變化對象的循環按預期工作。
let vmCoins = {1:1, 2:0, 4:3, 6:2}
let changeObj = {}
let changeNeeded = 8
for (let d=changeNeeded; d>0; d--){
\t while (vmCoins[d]>0 && (changeNeeded-d)>=0){
\t changeObj[d] ? changeObj[d] ++ : changeObj[d] = 1
vmCoins[d] --
changeNeeded -= d
}
}
console.log(changeObj)
但是當我把它變成主要的解決方案,for循環似乎沒有運行。
function VendingMachine(coins){
this.coins = coins
}
VendingMachine.prototype.vending = function(price,credit){
//Calculate total value of coins inserted
var changeObj = {}
let totalCredit =[]
let arrKeys = Object.keys(credit).map(x=>parseInt(x))
let arrValues = Object.values(credit)
for (var i=0; i<arrKeys.length; i++){
\t totalCredit.push(arrKeys[i]*arrValues[i])
}
totalCredit = totalCredit.reduce((a,b) => a+b)
//if coins inserted less than price, return the inserted coins
if (totalCredit<price){
\t return credit
}
//if coins inserted more than item price, put coins into vending machine & return change.
if (totalCredit>price){
\t arrKeys.forEach(x => this.coins[x] += credit[x])// put coins in vending machine
\t changeNeeded = totalCredit - price
// PROBLEM BEGINS HERE
for(let d=changeNeeded; d<0; d--){
\t while(this.coins[d]>0 && (changeNeeded - d)>=0){
\t changeObj[d] ? changeObj[d] ++ : changeObj[d] = 1
this.coins[d]--
changeNeeded -=d
}
}
return changeObj //does not return as expected
}
}
let vm = new VendingMachine({1:1, 2:0, 4:3, 6:2})
let result = vm.vending(12, {2:1, 6:3})
console.log(vm) //check if the credit is put into the machine (yes)
console.log(result)// returns empty object
如何讓程序返回更改對象?
在你的工作版本'd> 0',但它在非工作版本改爲'd <0'。那是故意的嗎? – Barmar
*嘆*它是錯誤的。現在工作... –