Created
November 22, 2020 18:44
-
-
Save diegolameira/f4f7df2d14637dcafef729a076525a38 to your computer and use it in GitHub Desktop.
given money and price it would return coins as [1c, 5c, 10c, 25c, $1]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* getChangeInCoins | |
* @description given money and price it would return coins as [1c, 5c, 10c, 25c, $1] | |
* @param {float} money | |
* @param {float} price | |
*/ | |
const getChangeInCoins = (money, price) => { | |
let value = (money - price) * 100; | |
return [100, 25, 10, 5, 1] | |
.map((coin) => { | |
let coins = Math.floor(value / coin); | |
value = value % coin; | |
return coins; | |
}) | |
.reverse(); | |
}; | |
test.each` | |
money | price | coins | |
${5} | ${0.99} | ${[1, 0, 0, 0, 4]} | |
${5} | ${1} | ${[0, 0, 0, 0, 4]} | |
${5} | ${0} | ${[0, 0, 0, 0, 5]} | |
${0} | ${0} | ${[0, 0, 0, 0, 0]} | |
${4.25} | ${0.25} | ${[0, 0, 0, 0, 4]} | |
${4.25} | ${0.75} | ${[0, 0, 0, 2, 3]} | |
${4.25} | ${1.76} | ${[4, 0, 2, 1, 2]} | |
${4.25} | ${1.77} | ${[3, 0, 2, 1, 2]} | |
`( | |
"given money $money and price $price it should return $coins", | |
({ money, price, coins }) => { | |
expect(getChangeInCoins(money, price)).toEqual(coins); | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment