JavaScript Allonge: Code Snippet

JavaScript Allonge: Code Snippet
0.0 0

#1
function repeat( num, fn ){
  return (num > 0) ? (repeat(num - 1, fn), fn(num)) : undefined
}

repeat(3, function(n){
  console.log("Hello " + n)
})
 //=>
    'Hello 1'
    'Hello 2'
    'Hello 3'

I’m trying to go through this code line by line but I’m confused as to what’s going on with:
(repeat(num - 1, fn), fn(num)) after the function is invoked with both arguments passed.

Is it invoking repeat(num,fn) recursively? How does fn(num) play a role in this?


#3

If you wrote it like this, it becomes clearer.

function repeat( num, fn ) {
  if (num > 0) {
    repeat(num - 1, fn);
    return fn(num);
  }
  else {
    return undefined;
  }
}

#4

@kevcomedia Much clearer. Thank you :slight_smile: