These are the notes for JavaScript Coding Questions, episode 18, interview and placement practice for people who finished the SyntaxPilot JavaScript course. Last episode built closures; today we put them to work in four functions that take a function and return a better one, the higher-order functions that come up in almost every front-end interview: debounce and throttle, curry for any number of arguments, and compose and pipe. On the way: why fn.length is 0 for rest parameters, and why ["10", "20", "30"].map(parseInt) gives NaN.
Each question follows the same steps: read the problem, think out loud, the obvious attempt, a real failure, why, the fix, every test case, and the complexity.
Every program was run with Node.js 24 (node main.js), the SyntaxPilot compiler's JavaScript command, and every output below is real. Programs that use timers print times rounded to 100 ms, so the numbers are stable from run to run. Plain modern JavaScript, no packages.
Q1: Debounce a search box
Problem. debounce(fn, wait) returns a function that, however often it is called, runs fn only once the calls have stopped for wait milliseconds, with the arguments of the last call.
Real life: a food app's search box. The user types c, h, a, i, pauses, then types m, a. We want one request per pause, not one per key. Also: auto-saving a form, recalculating a layout after a window resize.
The problem: a request per keystroke
const t0 = Date.now();
const ms = () => Math.round((Date.now() - t0) / 100) * 100;
const search = (q) => console.log("request:", q, "at", ms(), "ms");
const typed = ["c", "ch", "cha", "chai", "chai m", "chai ma"];
const at = [0, 100, 200, 300, 1000, 1100];
typed.forEach((q, i) => setTimeout(() => search(q), at[i]));
request: c at 0 ms
request: ch at 100 ms
request: cha at 200 ms
request: chai at 300 ms
request: chai m at 1000 ms
request: chai ma at 1100 ms
setTimeout(fn, ms) runs fn after at least ms milliseconds; here it plays back the typing. Six requests, though the user meant two searches.
Attempt: just wait
const t0 = Date.now();
const ms = () => Math.round((Date.now() - t0) / 100) * 100;
function debounce(fn, wait) {
return function (...args) {
setTimeout(() => fn(...args), wait);
};
}
const search = debounce((q) => console.log("request:", q, "at", ms(), "ms"), 300);
const typed = ["c", "ch", "cha", "chai", "chai m", "chai ma"];
const at = [0, 100, 200, 300, 1000, 1100];
typed.forEach((q, i) => setTimeout(() => search(q), at[i]));
request: c at 300 ms
request: ch at 400 ms
request: cha at 500 ms
request: chai at 600 ms
request: chai m at 1300 ms
request: chai ma at 1400 ms
Still six requests, just 300 ms late. Every call starts its own timer and nobody cancels the earlier ones. Waiting alone isn't debounce.
Real life: a lift door. When someone steps in, the door doesn't close on them: the wait starts again. The lift moves once nobody has come for a few seconds, one trip for the whole group.
Fix: one timer in the closure, cleared on every call
const t0 = Date.now();
const ms = () => Math.round((Date.now() - t0) / 100) * 100;
function debounce(fn, wait) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), wait);
};
}
const search = debounce((q) => console.log("request:", q, "at", ms(), "ms"), 300);
const typed = ["c", "ch", "cha", "chai", "chai m", "chai ma"];
const at = [0, 100, 200, 300, 1000, 1100];
typed.forEach((q, i) => setTimeout(() => search(q), at[i]));
request: chai at 600 ms
request: chai ma at 1400 ms
setTimeoutreturns a timer id;clearTimeout(id)cancels that timer if it hasn't run yet (clearTimeout(undefined)on the first call does nothing).- The timer variable lives in the closure, so every call sees the same one.
- The inner arrow function keeps the wrapper's
this, andfn.apply(this, args)passes it on, so debouncing a method works.
Throttle: at most once per window
A page saves the scroll position while you scroll. Debounce would wait until scrolling stops. We want a save every so often during scrolling: at most once every 250 ms.
Real life: a metro ticket gate lets one person through every second, however big the crowd.
function throttle(fn, wait) {
let last = -Infinity;
return function (...args) {
const now = Date.now();
if (now - last < wait) return;
last = now;
fn.apply(this, args);
};
}
const save = throttle((n) => console.log("save at scroll", n), 250);
for (let n = 1; n <= 10; n++) {
setTimeout(() => save(n), (n - 1) * 100);
}
save at scroll 1
save at scroll 4
save at scroll 7
save at scroll 10
Date.now()is the current time in milliseconds.laststarts at-Infinity, so the first call always runs.- Ten events, 100 ms apart (0, 100, …, 900 ms). Runs at 0, 300, 600, 900 ms; the calls in between are dropped.
| Debounce | Throttle | |
|---|---|---|
| Runs | once, after the calls stop | at most once per window, during the calls |
| Good for | search boxes, auto-save, resize-end | scrolling, mouse moves, game controls, rate limits |
| Keeps in the closure | a timer id | the time of the last run |
Complexity: both are O(1) time per call and O(1) space.
Q2: Curry any function
Problem. curry(fn) returns a function you can call with the arguments one at a time, a few at a time, or all at once; when all of them have arrived, fn runs. Turning a function into that shape is currying.
order("rava")("masala")("coconut") === order("rava", "masala")("coconut") === order("rava", "masala", "coconut")
Real life: a dosa counter takes the base, then the filling, then the chutney, and you can keep a half-filled order like "mysore masala" and reuse it with different chutneys. Reusing a function with some arguments fixed in advance is called partial application.
Attempt: write the arrows by hand
const dosa = (base) => (filling) => (chutney) =>
`${base} dosa, ${filling}, ${chutney}`;
console.log(dosa("rava")("masala")("coconut"));
const rava = dosa("rava");
console.log(rava("plain")("tomato"));
console.log(dosa("rava", "masala", "coconut"));
rava dosa, masala, coconut
rava dosa, plain, tomato
[Function (anonymous)]
The first arrow has only one parameter, base; the extra arguments are ignored, and we got back the next arrow, still waiting. And this works for exactly three arguments; every function would need its own hand-written arrows.
A general curry, using fn.length
A function's length is the number of parameters it declares: ((a, b, c) => 0).length is 3. Like counting the blanks on the order slip.
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) return fn.apply(this, args);
return (...more) => curried.apply(this, [...args, ...more]);
};
}
const order = curry((base, filling, chutney) =>
`${base} dosa, ${filling}, ${chutney}`);
console.log(order("rava")("masala")("coconut"));
console.log(order("rava", "masala")("coconut"));
console.log(order("set", "plain", "tomato"));
const masalaFor = order("mysore")("masala");
console.log(masalaFor("mint"), "|", masalaFor("peanut"));
const total = curry((...prices) => prices.reduce((a, b) => a + b, 0));
console.log(total(10)(20));
rava dosa, masala, coconut
rava dosa, masala, coconut
set dosa, plain, tomato
mysore dosa, masala, mint | mysore dosa, masala, peanut
TypeError: total(...) is not a function
curriedis a named function expression: the name lets it call itself.- If enough arguments have arrived, call
fn; otherwise return a function that collects more and callscurriedagain with old + new arguments ([...args, ...more]builds a new array, somasalaForcan be reused). - The crash: a function with rest parameters
(...prices)haslength0 (no blanks to count). Sototal(10)already "had enough", ran, and returned the number10; then10(20)threw. Parameters with default values also stop the count:((a, b = 2, ...rest) => a).lengthis 1.
An "infinite" curry: stop on an empty call
function sum(...first) {
const all = [...first];
return function more(...next) {
if (next.length === 0) return all.reduce((a, b) => a + b, 0);
all.push(...next);
return more;
};
}
console.log(sum(10)(20)(30)());
console.log(sum(10, 20)(5, 5)());
console.log(sum()());
60
40
0
When the number of arguments is unknown, the caller must say "done": the usual signal is an empty call (). (Another common interview variant overrides valueOf/toString so the function converts to the total; the empty call is clearer.)
Complexity: curry copies the collected arguments on each call: O(n²) copying in the worst case for n arguments given one by one, which is tiny for real functions. sum keeps all n numbers: O(n) space and O(n) time to add them.
Q3: Compose and pipe
Problem. pipe(f, g, h) returns one function that runs the steps left to right: pipe(f, g, h)(x) = h(g(f(x))). compose(f, g, h) runs them right to left, like maths writes f(g(h(x))).
Real life: a restaurant bill: ₹50 off, then 18% GST, then round to the rupee.
Attempt: nested calls
const discount = (p) => p - 50;
const addGst = (p) => p * 1.18;
const round = (p) => Math.round(p);
const bill = round(addGst(discount(499)));
console.log(bill);
const bill2 = round(discount(addGst(499)));
console.log(bill2);
530
539
Nested calls run inside out, so you read them backwards, and with many steps nobody can see the order. A colleague swapped two calls: GST was charged before the discount, and the customer paid ₹9 more. We want the steps written in the order they happen.
pipe with reduce, compose with reduceRight
const discount = (p) => p - 50;
const addGst = (p) => p * 1.18;
const round = (p) => Math.round(p);
const pipe = (...fns) => (x) =>
fns.reduce((value, f) => f(value), x);
const compose = (...fns) => (x) =>
fns.reduceRight((value, f) => f(value), x);
const billOf = pipe(discount, addGst, round);
console.log(billOf(499), billOf(1000));
console.log(compose(round, addGst, discount)(499));
console.log(pipe()(499));
const steps = [discount, addGst, round];
console.log(pipe(...steps.toReversed())(499));
530 1121
530
499
538.8199999999999
reducestarts withxas the value and lets each function turn it into the next value.reduceRightdoes the same from the last function to the first.pipe()with no functions returnsxunchanged: the starting value is never touched (the identity function).toReversed()returns a reversed copy (it doesn't changesteps). Same three steps in a different order (round first, GST, then discount):538.82. Order matters, andpipelets you read it.
The map(parseInt) trap
const pipe = (...fns) => (x) => fns.reduce((value, f) => f(value), x);
const toNumbers = (list) => list.map(parseInt);
const total = (nums) => nums.reduce((a, b) => a + b, 0);
console.log(pipe(toNumbers, total)(["10", "20", "30"]));
console.log(["10", "20", "30"].map(parseInt));
console.log(["10", "20", "30"].map((s) => parseInt(s, 10)));
NaN
[ 10, NaN, NaN ]
[ 10, 20, 30 ]
mapcalls its callback with three arguments:(item, index, array).parseInt(string, radix)takes a second parameter, the radix (number base, 2 to 36; 0 or missing means "guess", usually 10). So we ranparseInt("10", 0)→ 10,parseInt("20", 1)→ NaN (base 1 doesn't exist),parseInt("30", 2)→ NaN (3 isn't a binary digit).- Fix: wrap it so exactly one argument goes in, and say the base:
(s) => parseInt(s, 10), or useNumber. In pipelines, use unary functions (exactly one parameter); that's one reason curry is useful.
Complexity: k functions run once each: O(k) calls plus whatever the functions cost, O(1) extra space.
Complexity summary
| Function | Time per call | Space |
|---|---|---|
debounce |
O(1) | O(1): one timer id |
throttle |
O(1) | O(1): one time stamp |
curry (n arguments, one by one) |
O(n) copy per call | O(n) |
Infinite sum |
O(1) per call, O(n) at the end | O(n) |
pipe / compose of k functions |
O(k) + the functions' own cost | O(1) |
Common mistakes (and the exact outputs)
| Mistake | Code | What you see | Why | Fix |
|---|---|---|---|---|
| Debounce without clearing | setTimeout(() => fn(...args), wait) |
still 6 requests, 300 ms late | old timers never cancelled | clearTimeout(timer) first |
| Debounce where throttle is needed | debounced scroll save | nothing saved while scrolling | debounce waits for the pause | throttle(fn, wait) |
Losing this |
setTimeout(function () { fn.apply(this, args) }) |
this is not your object |
a normal function gets its own this |
an arrow function inside, fn.apply(this, args) |
| Hand-written curried arrows | dosa("rava", "masala", "coconut") |
[Function (anonymous)] |
each arrow takes one argument | a general curry |
| Curry with rest parameters | curry((...prices) => ...) |
TypeError: total(...) is not a function |
length is 0 |
end with an empty call () |
Defaults shrink length |
(a, b = 2) => ... |
length is 1 |
counting stops at a default | pass the arity explicitly: curry(fn, 2) |
| Nested calls in the wrong order | round(discount(addGst(499))) |
539 instead of 530 |
inside-out reading | pipe(discount, addGst, round) |
map(parseInt) |
["10", "20", "30"].map(parseInt) |
[ 10, NaN, NaN ] |
the index is used as the radix | map((s) => parseInt(s, 10)) |
Mini project: a debounced menu search pipeline
Debounce + pipe together: clean the query, find matches, keep the top 3, and show them, but only after the user pauses.
function debounce(fn, wait) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), wait);
};
}
const pipe = (...fns) => (x) => fns.reduce((value, f) => f(value), x);
const menu = ["masala chai", "masala dosa", "mango lassi", "filter coffee", "chai latte"];
const clean = (q) => q.trim().toLowerCase();
const find = (q) => menu.filter((item) => item.includes(q));
const top3 = (list) => list.slice(0, 3);
const show = (list) => console.log(list.length ? list.join(", ") : "(no match)");
const runSearch = debounce(pipe(clean, find, top3, show), 200);
["m", "ma", "mas", "masa", "masala "].forEach((q, i) => setTimeout(() => runSearch(q), i * 50));
setTimeout(() => runSearch(" CHAI"), 800);
setTimeout(() => runSearch("pizza"), 1300);
masala chai, masala dosa
masala chai, chai latte
(no match)
Five fast keystrokes → one search. Each step is a small unary function you can test on its own.
Your turn: throttle with a trailing call (solution)
Problem. Our throttle drops every call inside the window, so the last scroll position can be lost. If calls were dropped, run once more at the end of the window with the latest arguments.
const t0 = Date.now();
const ms = () => Math.round((Date.now() - t0) / 50) * 50;
function throttle(fn, wait) {
let last = -Infinity, timer = null, lastArgs = null;
return function (...args) {
const now = Date.now();
const left = wait - (now - last);
if (left <= 0) {
last = now;
fn.apply(this, args);
} else {
lastArgs = args;
if (!timer) {
timer = setTimeout(() => {
last = Date.now();
timer = null;
fn.apply(this, lastArgs);
}, left);
}
}
};
}
const save = throttle((n) => console.log("save", n, "at", ms(), "ms"), 250);
[0, 100, 200].forEach((t, i) => setTimeout(() => save(i + 1), t));
save 1 at 0 ms
save 3 at 250 ms
Call 2 was replaced by call 3 (we keep only the latest arguments), and it ran exactly when the window ended. One timer at most, so still O(1) time and space.
Practice questions (with solutions)
1. debounce with a cancel() method (for example, when the user closes the page).
Solution
function debounce(fn, wait) {
let timer;
const debounced = function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), wait);
};
debounced.cancel = () => clearTimeout(timer);
return debounced;
}
const autosave = debounce((text) => console.log("saved:", text), 200);
autosave("draft 1");
setTimeout(() => autosave("draft 2"), 50);
setTimeout(() => { autosave.cancel(); console.log("user closed the page"); }, 100);
setTimeout(() => console.log("done"), 400);
user closed the page
done
Nothing is saved: the pending timer was cancelled. (A flush() that runs it immediately is the other common method.)
2. curry with a placeholder, so you can fill later arguments first.
Solution
const _ = Symbol("placeholder");
function curry(fn) {
return function curried(...args) {
const filled = args.slice(0, fn.length);
const ready = filled.length >= fn.length && !filled.includes(_);
if (ready) return fn.apply(this, filled);
return (...more) => {
const merged = args.map((a) => (a === _ && more.length ? more.shift() : a));
return curried.apply(this, [...merged, ...more]);
};
};
}
const order = curry((base, filling, chutney) => `${base} dosa, ${filling}, ${chutney}`);
const withCoconut = order(_, _, "coconut");
console.log(withCoconut("rava", "masala"));
console.log(withCoconut("set")("plain"));
console.log(order(_, "paneer")("mysore", "mint"));
rava dosa, masala, coconut
set dosa, plain, coconut
mysore dosa, paneer, mint
A Symbol is a unique value that can't be confused with any real argument. New arguments fill the placeholders first, left to right; the rest are appended.
3. pipe for async functions.
Solution
const pipeAsync = (...fns) => (x) => fns.reduce((p, f) => p.then(f), Promise.resolve(x));
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const fetchPrice = async (item) => { await sleep(50); return { chai: 20, dosa: 80 }[item]; };
const addGst = (p) => p * 1.18;
const round = (p) => Math.round(p);
const priceOf = pipeAsync(fetchPrice, addGst, round);
priceOf("dosa").then((v) => console.log("dosa:", v));
priceOf("chai").then((v) => console.log("chai:", v));
dosa: 94
chai: 24
Start from a resolved promise and chain .then(f): each step can be sync or async. (Promises are episodes 21 and 22.)
4. Which one: debounce or throttle? (a) validate a username after typing, (b) update a progress bar while scrolling, (c) a "Save" button hammered by the user, (d) send the window size to analytics after resizing.
Answer
(a) debounce, (b) throttle, (c) throttle (or once until the save finishes), (d) debounce.
Quick quiz
const f = (a, b = 2, ...rest) => a;
console.log(f.length, ["1", "1", "1"].map(parseInt));
A) 3 [1, 1, 1] B) 1 [1, NaN, 1] C) 2 [1, NaN, NaN] D) 1 [1, 1, 1]
Answer
B, output 1 [ 1, NaN, 1 ]. length counts only the parameters before the first default value or rest parameter, so 1. map passes the index as the radix: parseInt("1", 0) → 1 (0 means guess, base 10), parseInt("1", 1) → NaN (no base 1), parseInt("1", 2) → 1 (1 is a binary digit).
Interview questions
- Debounce vs throttle? Debounce runs once after the calls stop; throttle runs at most once per window while they continue.
- Leading vs trailing? A leading debounce/throttle runs on the first call; trailing runs at the end of the window. Libraries offer both options.
- Why
fn.apply(this, args)and notfn(...args)? To keep the caller'sthis, so debounced or throttled methods still work. - What is currying vs partial application? Currying turns
f(a, b, c)intof(a)(b)(c); partial application fixes some arguments now and returns a function for the rest. Ourcurrysupports both. - What is
fn.length? The number of declared parameters before the first default or rest parameter. - Compose vs pipe? Same idea, opposite order: compose is right to left (maths style), pipe is left to right (reading order).
- Why does
map(parseInt)fail?mappasses(item, index, array)andparseIntreads the index as the radix. - What is a higher-order function? A function that takes a function as an argument or returns one:
map,debounce,curry,pipe.
Glossary
| Term | Meaning |
|---|---|
| Higher-order function | A function that takes or returns a function |
| Debounce | Run once, after the calls have stopped for wait ms |
| Throttle | Run at most once per wait ms while calls keep coming |
setTimeout(fn, ms) |
Run fn later; returns a timer id |
clearTimeout(id) |
Cancel a timer that hasn't run yet |
| Timer id | The value setTimeout returns, used to cancel it |
Date.now() |
The current time in milliseconds |
| Closure | A function plus the variables it remembers (episode 17) |
fn.apply(this, args) |
Call fn with a chosen this and an array of arguments |
| Rest parameter | ...args in a parameter list: collects arguments into an array |
| Currying | Turning f(a, b, c) into f(a)(b)(c) |
| Partial application | Fixing some arguments now, the rest later |
fn.length |
Number of declared parameters before the first default or rest |
| Arity | The number of arguments a function takes; unary = one |
| Named function expression | function curried() {} used as a value; the name works inside it |
| Infinite curry | A curry with unknown argument count, ended by an empty call |
| Compose | Combine functions right to left: f(g(h(x))) |
| Pipe | Combine functions left to right: h(g(f(x))) |
reduce / reduceRight |
Fold an array into one value, from the left / from the right |
| Identity | A function that returns its input unchanged |
toReversed() |
A reversed copy of an array (the original is unchanged) |
| Radix | The number base for parseInt: 2 (binary) to 36 |
Symbol |
A unique value, used here as a placeholder |
| Big-O | How the work grows with the input size |
Summary
- Debounce keeps one timer in a closure and clears it on every call, so
fnruns once after the calls stop. Throttle keeps the time of the last run and drops calls inside the window. - Curry collects arguments until it has
fn.lengthof them; rest parameters and defaults shrinklength, so an infinite curry ends with an empty call(). pipeisreduceover functions (left to right);composeisreduceRight. The order of steps matters.mappasses the index as a second argument, so wrapparseInt:(s) => parseInt(s, 10).- Next episode:
thisand prototypes: write your ownbind,callandapply.