Functional Programming - Simple For Loop For Incrementing Counter
Solution 1
So, how would one do this in functional programming?
It is not doing much actually, you can still use forEach
with a little workaround
Array.apply(null, Array(5)).forEach(function(){
console.log( "funtional programming is a religion")
});
5 is the number of times you want to iterate.
Solution 2
The whole point would be to make most of your code testable. For you example I guess the best would be to create the text without printing it.
function unFold(fnStopPredicate, fnTerm, fnGenerate, aSeed) {
var arr = [];
while( ! fnStopPredicate(aSeed) ){
arr.push(fnTerm(aSeed));
aSeed = fnGenerate(aSeed);
}
return arr;
}
You might say this is not functional and that is true, BUT it has a functional interface. It does not mutate it's arguments and the value returned is always a direct result of it's initial arguments.
var strValues = unFold(x => x > 10,
x => "functional programming is a religion",
x => x+1,
0).join("\n");
// Real side effect goes here
console.log(strValues);
The main point here is that you may unit test the use of unFold as long as the function you provide does not do side effects themselves.
Solution 3
Why not build a Higher Order Function for Numbers.
Number.prototype.repeat = function (fn) {
var i,
n = Math.abs(Math.floor(this)) || 0;
for (i = 0; i < n; i++) fn(i, this);
};
(10).repeat(function (i, n) { document.write(i + ' of ' + n + ': your claim<br>'); });
(NaN).repeat(function (i, n) { document.write(i + ' of ' + n + ': your claim<br>'); });
Comments
-
Kayote almost 2 years
We dont use
for loop
in functional programming, instead, we usehigher order functions
like map, filter, reduce etc. These are fine for iterating through an array.However, I wonder how do I do a simple counter loop.
let i = 0; for( i; i < 10; i++) { console.log( "functional programming is a religion") };
So, how would one do this in functional programming?
-
sudo97 about 5 yearsfunctional programming does not mutate input, so the scnd function would return x+1
-
Phil Tune about 3 yearsI had the same thought to do a HOF, so +1. Not purely FP, but I'm a pragmatist, not a purist.
-
Francois Carstens about 3 years
Array.apply
is a pretty straightforward solution here. Nice.