const

repeat

by I Sang Hyeon

HTML

<div id="divTemp">
  <p>START</p>
</div>

JavaScript

$(document).ready(function(){

const times = x => f => {
console.log('x: '+x);
  if (x > 0) {
    f();
    times (x - 1) (f);
  }
}

// use it
times (3) (() => $('#divTemp').append('<p>hi</p>'));

// or define intermediate functions for reuse
let twice = times (2);

// twice the power !
twice (() => $('#divTemp').append('<p>double vision</p>'));

});
/*
The code below is written using ES6 syntaxes but could just as easily be written in ES5 or even less. ES6 is not a requirement to create a "mechanism to loop x times"

If you don't need the iterator in the callback, this is the most simple implementation

const times = x => f => {
  if (x > 0) {
    f()
    times (x - 1) (f)
  }
}

// use it
times (3) (() => console.log('hi'))

// or define intermediate functions for reuse
let twice = times (2)

// twice the power !
twice (() => console.log('double vision'))
 Run code snippetHide results
Full page
If you do need the iterator, you can use a named inner function with a counter parameter to iterate for you

const times = n => f => {
  let iter = i => {
    if (i === n) return
    f (i)
    iter (i + 1)
  }
  return iter (0)
}

times (3) (i => console.log(i, 'hi'))
 Run code snippetExpand snippet
Stop reading here if you don't like learning more things ...

But something should feel off about those...

single branch if statements are ugly — what happens on the other branch ?
multiple statements/expressions in the function bodies — are procedure concerns being mixed ?
implicitly returned undefined — indication of impure, side-effecting function
"Isn't there a better way ?"

There is. Let's first revisit our initial implementation

// times :: Int -> (void -> void) -> void
const times = x => f => {
  if (x > 0) {
    f()               // has to be side-effecting function
    times (x - 1) (f)
  }
}
Sure, it's simple, but notice how we just call f() and don't do anything with it. This really limits the type of function we can repeat multiple times. Even if we have the...