Created
October 2, 2013 06:49
-
-
Save mathiasverraes/6789907 to your computer and use it in GitHub Desktop.
@MikeBild posted this on twitter. As an exercise, I made the same thing in an FP style, using recursion instead of mutable state. It's slightly longer :-) Because there's no native pattern matching, I have a calc/2 (public) and a calcX/3 (private) function. https://twitter.com/mikebild/status/385276260089225216
This file contains hidden or 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
'use strict'; | |
var assert = require('assert'); | |
var _ = require('lodash'); | |
var calcX = function (acc, coinSizes, totalAmount) { | |
if (coinSizes.length == 0) return acc; | |
var currentCoinSize = _.head(coinSizes); | |
var restAmount = totalAmount % currentCoinSize; | |
var newAcc = acc.concat([ | |
{ | |
coinSize: currentCoinSize, | |
amountOfCoins: Math.floor(totalAmount / currentCoinSize), | |
rest: restAmount | |
} | |
] | |
); | |
return calcX(newAcc, _.tail(coinSizes), restAmount); | |
}; | |
var calc = _.partial(calcX, []); | |
var totalAmount = 99; | |
var coinSizes = [1, 2, 5, 10, 20, 50, 100].reverse(); | |
var result = calc(coinSizes, totalAmount); | |
console.log(result); | |
var expected = [ | |
{ coinSize: 100, amountOfCoins: 0, rest: 99 }, | |
{ coinSize: 50, amountOfCoins: 1, rest: 49 }, | |
{ coinSize: 20, amountOfCoins: 2, rest: 9 }, | |
{ coinSize: 10, amountOfCoins: 0, rest: 9 }, | |
{ coinSize: 5, amountOfCoins: 1, rest: 4 }, | |
{ coinSize: 2, amountOfCoins: 2, rest: 0 }, | |
{ coinSize: 1, amountOfCoins: 0, rest: 0 } | |
]; | |
assert.deepEqual(result, expected); |
This file contains hidden or 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
var a=99;[1,2,5,10,20,50,100].reverse().map(function(n){return{C:n,N: Math.floor(a/n),R:(a%=n)};}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
next one without shared state ;-)