Skip to content

Instantly share code, notes, and snippets.

@juliovedovatto
Created January 21, 2021 01:03
Show Gist options
  • Save juliovedovatto/47e9d6e4ec62336918b03d181aa7f6fe to your computer and use it in GitHub Desktop.
Save juliovedovatto/47e9d6e4ec62336918b03d181aa7f6fe to your computer and use it in GitHub Desktop.
exercise to calculate the amount of US coins, based on a given amount of money
/**
* Making Change Exercise
*
* Given an amount of money in USD, calculate the least number of
* coins needed to create the given amount of money.
*
* Example:
*
* Input: $1.67
*
* { quarters: 6, dimes: 1, nickels: 1, pennies: 2 }
*/
function currencyToCoins(amount) {
let n = amount * 100
const coins = { quarters: 0, dimes: 0, nickels: 0, pennies: 0 }
const currencyValue = {
quarters: 25,
dimes: 10,
nickels: 5,
pennies: 1
}
Object.entries(currencyValue).forEach(([type, value]) => {
coins[type] = parseInt(n / value)
n -= coins[type] * value
})
return coins
}
console.log(currencyToCoins(1.67)) // { quarters: 6, dimes: 1, nickels: 1, pennies: 2 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment