JS2 Failures

These are solutions in JS2 that you should look out for when helping JS2 students. Make sure you learn from their mistakes and make sure you catch yourself from writing bad code.

2.js Array Callback Generator

const solution = (fun, arr = []) => {
  
  if(!fun(arr.length)){
    arr.push(arr.length)
    return solution(fun, arr)
  }
  return arr
  
}

3.js 2D Array Generator

4.js Closure Iterator

5.js Delayed Function Calls

const solution = (a, t) => {
	const runner = ( i = 0) => { 
	  if(i === a.length){
	    return
	  }
	  a[i]()
	  return runner(i+1)
	}
	setTimeout(runner, t)
}

The problem with this solution is that your code is taking longer to run than necessary.

solution([], 2000) should exit immediately, but with your solution it exits after 2000ms.

if (i === a.length) {
  return
}
a[i]()
return solution(a, t, i + 1)

6.js Sequential Function Calls

const solution = (arr, time, index = 0) => {
  if (index === arr.length) return;
  setTimeout(arr[index], time + time * index);
  return solution(arr, time, index + 1);
};

The goal here is to teach you how to call functions sequentially, which you are not doing. There are complex cases where you may not be able to do these simple calculations.

Pass a function into setTimeout as the first argument. Inside the function, call solution

9.js cReduce