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.
Student code:
const solution = (fun, i = 0, arr = []) => {
if (fun(i)) return arr
if (!fun(i)) {arr.push(i)}
return solution(fun, i+1, arr)
}
const solution = (fun, arr = []) => {
if(!fun(arr.length)){
arr.push(arr.length)
return solution(fun, arr)
}
return arr
}
i=-1
, then set i=0
, then set i = i + 1
. It makes the code confusing to understand.
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)
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