Skip to content

Instantly share code, notes, and snippets.

@QMaximillian
Last active March 25, 2021 17:09
Show Gist options
  • Save QMaximillian/e7dcda51b74f059ea7dd72ceb84dd900 to your computer and use it in GitHub Desktop.
Save QMaximillian/e7dcda51b74f059ea7dd72ceb84dd900 to your computer and use it in GitHub Desktop.
ChangeMaker - HackerRank
function ChangeMaker(price, payment) {
    let priceInCents = Math.round(price * 100)
    let paymentInCents = payment.reduce((acc, curr) => { 
      return acc += curr
    }) * 100
    

  if (paymentInCents > priceInCents){
    console.log('can purchase, subtract the amount given from the price')
    calculateChange(paymentInCents - priceInCents)
  } else {
    console.log(`can't purchase, return the paymentInCents`)
    calculateChange(paymentInCents)
  }
    
}



function calculateChange(change){
  let changeArray = []
  let currentChange = change
  
  const quarters = calculateAmountOfDenomination(currentChange, 25)

  changeArray.unshift(quarters)
  currentChange -= (quarters * 25)

   const dimes = calculateAmountOfDenomination(currentChange, 10)
  changeArray.unshift(dimes)
  currentChange -= (dimes * 10)

  const nickels = calculateAmountOfDenomination(currentChange, 5)
  changeArray.unshift(nickels)
  currentChange -= (nickels * 5)

  changeArray.unshift(currentChange)

  
  console.log(changeArray)
}

function calculateAmountOfDenomination(change, denomination){
  if (change < denomination){
    return 0
  } else {
    return Number(parseInt(change / denomination))
  }
}

I wrote an entire blog about a better solution here!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment