Functional Programming - Simple For Loop For Incrementing Counter

13,909

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>'); });
Share:
13,909
Kayote
Author by

Kayote

A javascript fan

Updated on June 05, 2022

Comments

  • Kayote
    Kayote almost 2 years

    We dont use for loop in functional programming, instead, we use higher 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
    sudo97 about 5 years
    functional programming does not mutate input, so the scnd function would return x+1
  • Phil Tune
    Phil Tune about 3 years
    I had the same thought to do a HOF, so +1. Not purely FP, but I'm a pragmatist, not a purist.
  • Francois Carstens
    Francois Carstens about 3 years
    Array.apply is a pretty straightforward solution here. Nice.