Search code examples
javascriptinfinite-loophigher-order-functions

Cutom loop function looping infinitely


I'm new to JavaScript I need to make a function that works like this:

loop(3, n => n > 0, n => n - 1, console.log);
// → 3
// → 2
// → 1

Here is my code:

function loop(counter, condition, update, fun){
    while(condition(counter)){
        fun(counter);
        update(counter);
    }
}

The while loop is running infinitely, and nothing is logging on console.


Can someone please help. Thanks in advance.


Solution

  • An update approach.

    function loop(counter, check, update, fn) {
        while (check(counter)) {
            fn(counter);
            counter = update(counter);
        }
    }
    
    loop(3, n => n > 0, n => n - 1, console.log);

    An recursive approach.

    function loop(counter, check, update, fn) {
        if (!check(counter)) return;
        fn(counter);
        loop(update(counter), check, update, fn);
    }
    
    loop(3, n => n > 0, n => n - 1, console.log);