JavaScript计算找零(freeCodeCamp项目)

编程 · 2023-09-22 · 315 人浏览

需求

编写一个用于收银机的函数 checkCashRegister():它的第一个参数为售价 price、第二个参数为支付金额 cash、第三个参数为收银机內的金额 cidcid 是包含货币面值的二维数组。

函数 checkCashRegister() 应返回含有 status 属性和 change 属性的对象。

如果收银机內的金额少于应找回的零钱数,或者无法返回确切的数目时,返回 {status: "INSUFFICIENT_FUNDS", change: []}

如果收银机內的金额恰好等于应找回的零钱数,返回 {status: "CLOSED", change: [...]},其中 change 的属性值就是收银机內的金额。

否则,返回 {status: "OPEN", change: [...]},其中 change 键值是应找回的零钱数,并将找零的面值由高到低排序。

货币单位 Unit面值
Penny0.01 美元(PENNY)
Nickel0.05 美元(NICKEL)
Dime0.1 美元(DIME)
Quarter0.25 美元(QUARTER)
Dollar1 美元(ONE)
Five Dollars5 美元(五)
Ten Dollars10 美元(TEN)
Twenty Dollars20 美元(TWENTY)
One-hundred Dollars100美元(ONE HUNDRED)

下面是抽屉里现金数组示例:

[
  ["PENNY", 1.01],
  ["NICKEL", 2.05],
  ["DIME", 3.1],
  ["QUARTER", 4.25],
  ["ONE", 90],
  ["FIVE", 55],
  ["TEN", 20],
  ["TWENTY", 60],
  ["ONE HUNDRED", 100]
]

代码实现

function checkCashRegister(price, cash, cid) {
  let change = cash - price
  let response = { status: '', change: [] }
  // 当前收银机內总金额
  let cidAmount = cid.reduce((accumulator, current) => accumulator + current[1], 0)

  // 收银机內的金额 < 应找回的零钱数
  if (cidAmount < change) {
    response.status = 'INSUFFICIENT_FUNDS'
    return response
  }

  // 收银机內的金额 = 应找回的零钱数
  if (cidAmount === change) {
    response.status = 'CLOSED'
    response.change = cid
    return response
  }

  cid = cid.reverse()
  let moneyTable = []
  let amounts = [100, 20, 10, 5, 1, 0.25, 0.1, 0.05, 0.01]

  for (let i = 0; i < cid.length; i++) {
    let item = {}
    item['name'] = cid[i][0]
    item['amount'] = amounts[i]
    item['totalAmount'] = cid[i][1]
    moneyTable.push(item)
  }

  for (let i = 0; i < moneyTable.length; i++) {
    let ele = []

    if (change >= moneyTable[i].amount && change > 0 && moneyTable[i].totalAmount > 0) {
      ele.push(moneyTable[i].name)
      let money = Math.floor(change / moneyTable[i].amount) * moneyTable[i].amount
      if (money > moneyTable[i].totalAmount) {
        money = moneyTable[i].totalAmount
      }
      ele.push(money)
      change -= money
      change = +change.toFixed(2)
      response.change.push(ele)
    }

    if (change === 0) {
      break
    }
  }

  if (change === 0) {
    response.status = 'OPEN'

  } else {
    response.status = 'INSUFFICIENT_FUNDS'
    response.change = []
  }

  return response
}
JavaScript
Theme Jasmine by Kent Liao