Write createBatcher(flush): collect values scheduled in the same synchronous run and pass them to flush once, in a microtask.
createBatcher(flush) returns a function, schedule(value).
All values scheduled before the current code finishes go to a single flush(values) call, in the order they were scheduled. That call is made in a microtask.
Values scheduled after that, including from inside flush, start a new batch. If nothing is scheduled, flush is never called.
function createBatcher(flush) {
// your code
}
// const schedule = createBatcher((values) => console.log(values));
// schedule(1);
// schedule(2);
// schedule(3);
// console.log("sync code done");
// setTimeout(() => schedule(4), 0);
// logs "sync code done", then [1, 2, 3] in one call, then [4] in a new batch
The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…