I realized that js doesn't actually have sum or product fuctions, so let's build them and then show how we could implement min or max in a functional style. Here are the sum and product callbacks, which we will need shortly.js> sum = function(total, num){ return total + num }
(function (total, num){ return total + num })
js> product = function(total, num){ return total * num }
(function (total, num){ return total * num })
With these, an identity, and the js Array.reduce function we can now sum or product an array. We will also check they are right by comparing with writing them out longhand.js> [1,3,5,7].reduce(sum,0)
16
js> [1,3,5,7].reduce(sum,0) == 1+3+5+7
true
We can verify that all sorts of trouble ensues if we give the wrong identity to our reducesjs> [1,3,5,7].reduce(sum,1) == 1+3+5+7
false
js> [1,3,5,7].reduce(sum,1)
17
js> [1,3,5,7].reduce(product,0) == 1*3*5*7
false
js> [1,3,5,7].reduce(product,0)
0
Let's do the same thing with max and check it works as expectedjs> max = function(total, num){ return total>=num ? total : num}
(function (total, num){ return total>=num ? total : num})
js> [1,3,5,7].reduce(max,‐Infinity)
7
Now what would happen if the identity were Infinity?js> [1,3,5,7].reduce(max,Infinity)
Infinity
So there you have it. Not entirely crazy after all ;-)
…continued from previous post.
I realized that js doesn't actually have sum or product fuctions, so let's build them and then show how we could implement min or max in a functional style. Here are the sum and product callbacks, which we will need shortly.
js> sum = function(total, num){ return total + num }
With these, an identity, and the js Array.reduce function we can now sum or product an array. We will also check they are right by comparing with writing them out longhand.(function (total, num){ return total + num }) js> product = function(total, num){ return total * num } (function (total, num){ return total * num })
js> [1,3,5,7].reduce(sum,0) 16 js> [1,3,5,7].reduce(sum,0) == 1+3+5+7 true
We can verify that all sorts of trouble ensues if we give the wrong identity to our reducesjs> [1,3,5,7].reduce(sum,1) == 1+3+5+7
Let's do the same thing with max and check it works as expectedfalse js> [1,3,5,7].reduce(sum,1)
17 js> [1,3,5,7].reduce(product,0) == 1*3*5*7 false js> [1,3,5,7].reduce(product,0)
0
js> max = function(total, num){ return total>=num ? total : num} (function (total, num){ return total>=num ? total : num}) js> [1,3,5,7].reduce(max,‐Infinity) 7
Now what would happen if the identity were Infinity?js> [1,3,5,7].reduce(max,Infinity)
So there you have it. Not entirely crazy after all ;-)Infinity