w3resource logo


CoffeeScript exercises

CoffeeScript function: Convert an amount to coins

CoffeeScript Function : Exercise-18 with Solution

Write a CoffeeScript function to convert an amount to coins.

Sample function : amountTocoins(46, [25, 10, 5, 2, 1])
Here 46 is the amount. and 25, 10, 5, 2, 1 are coins.
Output : 25, 10, 10, 1

Solution :

HTML Code :

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>

</body>
</html>

CoffeeScript Code :

amountTocoins = (amount, coins) ->
  if amount == 0
    []
  else
    if amount >= coins[0]
      left = amount - coins[0]
      [ coins[0] ].concat amountTocoins(left, coins)
    else
      coins.shift()
      amountTocoins amount, coins

console.log amountTocoins(46, [
  25
  10
  5
  2
  1
])

Live Demo :

JS Bin

Post your code through Disqus :



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

PHP: Loop

JavaScript: Delete duplicates in an array

Oracle: Round the number