JSFiddle - React, Tailwind, and code Playground
by Tim Hagn
JavaScript
/**
* -------------------------------------------------------------------------------------------------
* fCC - JavaScript Algorithms and Data Structures Projects
* -------------------------------------------------------------------------------------------------
*/
/*
// Cash Register
function checkCashRegister(price, cash, cid) {
// Cash Mapping.
const mapping = {
"PENNY": 0.01,
"NICKEL": 0.05,
"DIME": 0.1,
"QUARTER": 0.25,
"ONE": 1,
"FIVE": 5,
"TEN": 10,
"TWENTY": 20,
"ONE HUNDRED": 100,
}
// Function rounds mathematically correct to two decimal points.
const roundToTwo = (num) => +(Math.round(num + "e+2") + "e-2")
// Function to return quotient and rest of division.
const modRest = (val, div) => [Math.trunc(val / div), roundToTwo(val % div)]
// Calculate available Cash and money to return. / mapping[curr[0]])
const cashAvailable = roundToTwo(cid.reduce((acc, curr) => acc + curr[1], 0))
const toChange = cash - price
// Fail on insufficient funds.
if (cashAvailable < toChange) return {'status': "INSUFFICIENT_FUNDS", 'change': []}
// Return cid if change due equals available cash.
if (cashAvailable === toChange) {
return {'status': "CLOSED", 'change': cid}
}
// Map over reversed cid ($100->$0).
let remaining = toChange
let change = []
cid.reverse().forEach((amount) => {
let val = modRest(remaining, mapping[amount[0]])
if (val[0] !== 0) {
// If we don't have sufficient funds for current unit, only return available funds.
if (val[0] * mapping[amount[0]] > amount[1]) {
remaining -= amount[1]
return change.push([amount[0], amount[1]])
}
// Else return mapped amount.
else {
remaining = val[1]
return change.push([amount[0], val[0] * mapping[amount[0]]])
}
}
return change
}, [])
// Now to be on the save side, calculate real cash.
const realReturn =...