Skip to content

Instantly share code, notes, and snippets.

@mikaturk
Created June 16, 2017 10:02
Show Gist options
  • Save mikaturk/19668152c806583eaa186dc442291082 to your computer and use it in GitHub Desktop.
Save mikaturk/19668152c806583eaa186dc442291082 to your computer and use it in GitHub Desktop.
<label for="euroinput">€</label>
<input name="euro" id="euroinput" type="number" min="0.05" step="0.05"></input>
<p id="coins"></p>
<script>
const euroCoins = [0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50, 100, 200, 500];
function toCoins(amount, coins) {
coins.sort((a,b)=>{
return a===b?0:a<b?1:-1;
});
return coins
.map(coinValue => {
let coinAmount = 0;
while (amount>=coinValue) {
amount -= coinValue;
coinAmount++;
}
return [coinValue, coinAmount];
})
.filter(coin=>coin[1]!==0);
}
const coinsToString = coins => coins.reduce((acc, [coinValue, coinAmount])=>`${acc}${coinAmount}x ${coinValue>=1?coinValue:coinValue*100} ${coinValue>=1?'Euro':'Cent'}\n`, '');
const euroInput = document.getElementById('euroinput');
euroInput.addEventListener('input', => {
document.getElementById('coins').innerText = coinsToString(toCoins(parseFloat(euroInput.value.replace(',','.')), euroCoins));
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment