12 handwritten js interview questions

1 compose

aifou
6 min readMar 15, 2024

Topic description: Implement a compose function.

// Usage is as follows:
function fn1(x) {
return x + 1;
}
function fn2(x) {
return x + 2;
}
function fn3(x) {
return x + 3;
}
function fn4(x) {
return x + 4;
}
const a = compose(fn1, fn2, fn3, fn4);
console.log(a(1)); // 1+4+3+2+1=11

The implementation code is as follows:

function compose(...fn) {
if (!fn.length) return (v) => v;
if (fn.length === 1) return fn[0];
return fn.reduce(
(pre, cur) =>
(...args) =>
pre(cur(...args))
);
}

2. Implement `setInterval` using `setTimeout` (with a version that clears the timer)

Topic description: `setInterval` is used for cyclic timed calls which may have certain issues. Can `setTimeout` solve this?

The implementation code is as follows:

function mySettimeout(fn, t) {
let timer = null;
function interval() {
fn();
timer = setTimeout(interval, t);
}
interval();
return {
cancel:()=>{
clearTimeout(timer)
}
}
}
// let a=mySettimeout(()=>{
// console.log(111);
// },1000)
// let b=mySettimeout(() => {
// console.log(222)
// }, 1000)

Extension: Can we use `setInterval` to simulate the implementation of `setTimeout`?

const mySetTimeout = (fn, time) => {
const timer = setInterval(() => {
clearInterval(timer);
fn();
}, time);
};
//…

--

--