Skip to content

Instantly share code, notes, and snippets.

@AmmarHasan
Created May 10, 2023 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AmmarHasan/fae5b18d70f6a90ab575f95486508ef0 to your computer and use it in GitHub Desktop.
Save AmmarHasan/fae5b18d70f6a90ab575f95486508ef0 to your computer and use it in GitHub Desktop.
// cashMachine, returningAmount -> 5,5,5 | 10, 5
function calculate(customerBills) {
const cashMachine = {
5: 0,
10: 0,
20: 0
};
let totalCashInHand = 0;
for (let index = 0; index < customerBills.length; index++) {
const customerBill = customerBills[index];
const returningAmount = customerBill - 5;
if (returningAmount > totalCashInHand) {
return false;
}
if (returningAmount === 5) {
if (cashMachine[5] === 0) {
return false;
}
cashMachine[5]--;
}
if (returningAmount === 15) {
if (cashMachine[5] === 0 && cashMachine[10] === 0) {
return false;
}
cashMachine[5]--;
cashMachine[10]--;
}
totalCashInHand += 5;
cashMachine[customerBill]++;
}
return true;
}
console.log('[5,10,5,20] -> true', calculate([5,10,5,20]))
console.log('[5, 20, 5, 20] -> false', calculate([5, 20, 5, 20]))
console.log('[5, 10, 5, 5, 5, 20, 10] -> true', calculate([5, 10, 5, 5, 5, 20, 10]))
console.log('[] -> false', calculate([]))
console.log('[5,10,10] -> false', calculate([5,10,10]))
console.log('[5,5,10,5] -> ', calculate([5,5,10,5]))
console.log('[10,5,5] -> ', calculate([10,5,5]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment