Skip to content

Machine Coding

Q (basic): Implement debounce.

Say this (30 sec): Debounce delays running fn until delay ms have passed without another call. Each call clears the previous timer and starts a new one. I keep this and the latest arguments, and I’ll add a cancel method.

Example:

function debounce(fn, delay) {
let timer = null;
function debounced(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
}
debounced.cancel = () => clearTimeout(timer);
return debounced;
}
// usage
const onSearch = debounce((q) => console.log("search", q), 300);
onSearch("r"); onSearch("re"); onSearch("rea"); // only "rea" logs, 300ms after last call

Follow-ups they ask: Leading-edge debounce (fire immediately, then ignore until quiet)? → run fn when timer is null, and let the timeout just reset timer = null.

function debounceLeading(fn, delay) {
let timer = null;
return function (...args) {
if (timer === null) fn.apply(this, args);
clearTimeout(timer);
timer = setTimeout(() => { timer = null; }, delay);
};
}
Q (basic): Implement throttle.

Say this (30 sec): Throttle runs fn at most once per interval. The simplest version stores the last run time and ignores calls inside the window. A better version also schedules a trailing call so the final event isn’t lost (important for scroll position).

Example:

// simple (leading only)
function throttle(fn, interval) {
let last = 0;
return function (...args) {
const now = Date.now();
if (now - last >= interval) {
last = now;
fn.apply(this, args);
}
};
}
// leading + trailing
function throttleTrailing(fn, interval) {
let last = 0;
let timer = null;
let lastArgs, lastThis;
return function (...args) {
const now = Date.now();
const remaining = interval - (now - last);
lastArgs = args; lastThis = this;
if (remaining <= 0) {
clearTimeout(timer);
timer = null;
last = now;
fn.apply(lastThis, lastArgs);
} else if (!timer) {
timer = setTimeout(() => {
last = Date.now();
timer = null;
fn.apply(lastThis, lastArgs);
}, remaining);
}
};
}
Q (mid): Implement Promise.all.

Say this (30 sec): Return a new promise. Track results by index (not push order, since promises finish out of order) and a counter. Resolve when the counter hits the length; reject on the first rejection. Wrap each item in Promise.resolve so plain values work. Empty input resolves immediately with [].

Example:

function promiseAll(iterable) {
return new Promise((resolve, reject) => {
const items = Array.from(iterable);
const results = new Array(items.length);
let completed = 0;
if (items.length === 0) return resolve(results);
items.forEach((item, i) => {
Promise.resolve(item).then((value) => {
results[i] = value;
completed++;
if (completed === items.length) resolve(results);
}, reject);
});
});
}
promiseAll([1, Promise.resolve(2), new Promise(r => setTimeout(() => r(3), 100))])
.then(console.log); // [1, 2, 3]

Common wrong answer: Using results.push(value) — the order would follow completion time, not input order.

Q (mid): Implement Promise.race, Promise.allSettled and Promise.any.

Example:

function promiseRace(iterable) {
return new Promise((resolve, reject) => {
for (const item of iterable) Promise.resolve(item).then(resolve, reject);
}); // first settle wins; later resolve/reject calls are ignored
}
function promiseAllSettled(iterable) {
const items = Array.from(iterable);
return Promise.all(
items.map((item) =>
Promise.resolve(item).then(
(value) => ({ status: "fulfilled", value }),
(reason) => ({ status: "rejected", reason })
)
)
);
}
function promiseAny(iterable) {
return new Promise((resolve, reject) => {
const items = Array.from(iterable);
const errors = new Array(items.length);
let rejected = 0;
if (items.length === 0) return reject(new AggregateError([], "All promises were rejected"));
items.forEach((item, i) => {
Promise.resolve(item).then(resolve, (err) => {
errors[i] = err;
if (++rejected === items.length) reject(new AggregateError(errors, "All promises were rejected"));
});
});
});
}

Follow-ups they ask: Why does race “just work” with multiple resolve calls? → a promise can only settle once; extra resolve/reject calls are no-ops. What does race([]) do? → stays pending forever.

Q (mid): Implement deep clone.

Say this (30 sec): Recursively copy objects and arrays. Handle primitives and null (return as is), special objects like Date, RegExp, Map, Set, and circular references using a WeakMap of already-cloned objects. In real code I’d just use structuredClone.

Example:

function deepClone(value, seen = new WeakMap()) {
if (value === null || typeof value !== "object") return value;
if (seen.has(value)) return seen.get(value); // circular ref
if (value instanceof Date) return new Date(value);
if (value instanceof RegExp) return new RegExp(value.source, value.flags);
if (value instanceof Map) {
const copy = new Map();
seen.set(value, copy);
value.forEach((v, k) => copy.set(deepClone(k, seen), deepClone(v, seen)));
return copy;
}
if (value instanceof Set) {
const copy = new Set();
seen.set(value, copy);
value.forEach((v) => copy.add(deepClone(v, seen)));
return copy;
}
const copy = Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value));
seen.set(value, copy);
for (const key of Reflect.ownKeys(value)) { // includes symbol keys
copy[key] = deepClone(value[key], seen);
}
return copy;
}
const a = { d: new Date(), list: [1, { x: 2 }] };
a.self = a;
const b = deepClone(a);
b.self === b; // true
b.list[1] !== a.list[1]; // true
Q (basic): Flatten a nested array (with optional depth).

Say this (30 sec): Recursively walk the array; if an element is an array and depth remains, flatten it with depth − 1, otherwise push it. Built-in equivalent: arr.flat(depth), and arr.flat(Infinity) for full flattening.

Example:

function flatten(arr, depth = Infinity) {
const result = [];
for (const item of arr) {
if (Array.isArray(item) && depth > 0) {
result.push(...flatten(item, depth - 1));
} else {
result.push(item);
}
}
return result;
}
flatten([1, [2, [3, [4]]]]); // [1, 2, 3, 4]
flatten([1, [2, [3, [4]]]], 1); // [1, 2, [3, [4]]]
// reduce version (full depth)
const flat = (arr) => arr.reduce((acc, x) => acc.concat(Array.isArray(x) ? flat(x) : x), []);

Follow-ups they ask: Without recursion? → use a stack: pop items, push array contents back, then reverse the result.

Q (basic): Implement memoize.

Say this (30 sec): Cache results in a Map keyed by the arguments. If the key exists, return the cached value; otherwise compute and store it. JSON.stringify as a key works for primitive args; for object args, a custom resolver is better. Only memoize pure functions.

Example:

function memoize(fn, resolver = (...args) => JSON.stringify(args)) {
const cache = new Map();
return function (...args) {
const key = resolver(...args);
if (cache.has(key)) return cache.get(key);
const result = fn.apply(this, args);
cache.set(key, result);
return result;
};
}
const slowSquare = (n) => { for (let i = 0; i < 1e8; i++); return n * n; };
const fastSquare = memoize(slowSquare);
fastSquare(9); // slow
fastSquare(9); // instant

Follow-ups they ask: Problem with unlimited caches? → memory growth; add an LRU limit (a Map keeps insertion order, so delete the first key when over size).

Q (mid): Implement curry.

Say this (30 sec): Curry converts f(a, b, c) into f(a)(b)(c) (or any grouping). Collect args until we have at least fn.length of them, then call the original. Otherwise return a function that collects more.

Example:

function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) return fn.apply(this, args);
return (...next) => curried.apply(this, [...args, ...next]);
};
}
const add3 = (a, b, c) => a + b + c;
const cAdd = curry(add3);
cAdd(1)(2)(3); // 6
cAdd(1, 2)(3); // 6
cAdd(1)(2, 3); // 6

Follow-ups they ask: Infinite currying sum(1)(2)(3)()?

function sum(a) {
return function next(b) {
if (b === undefined) return a;
a += b;
return next;
};
}
sum(1)(2)(3)(); // 6
Q (mid): Implement an EventEmitter (on, off, emit, once).

Say this (30 sec): Store a Map from event name to a list of listeners. emit calls each listener with the args — iterate over a copy so listeners removing themselves during emit don’t break the loop. once wraps the listener so it removes itself after the first call, and keeps a reference to the original so off still works with it.

Example:

class EventEmitter {
#events = new Map();
on(event, listener) {
if (!this.#events.has(event)) this.#events.set(event, []);
this.#events.get(event).push(listener);
return () => this.off(event, listener); // unsubscribe function
}
off(event, listener) {
const list = this.#events.get(event);
if (!list) return;
this.#events.set(event, list.filter((l) => l !== listener && l.original !== listener));
}
once(event, listener) {
const wrapper = (...args) => {
this.off(event, wrapper);
listener.apply(this, args);
};
wrapper.original = listener;
return this.on(event, wrapper);
}
emit(event, ...args) {
const list = this.#events.get(event);
if (!list || list.length === 0) return false;
[...list].forEach((l) => l.apply(this, args));
return true;
}
}
const bus = new EventEmitter();
const unsub = bus.on("msg", (t) => console.log("got", t));
bus.once("msg", () => console.log("only once"));
bus.emit("msg", "hi"); // got hi, only once
bus.emit("msg", "again");// got again
unsub();
Q (basic): Polyfill Array.prototype.map, filter and reduce.

Say this (30 sec): Use a regular function so this is the array. Pass (element, index, array) to the callback, support thisArg for map/filter, and skip holes in sparse arrays with i in this. For reduce: if no initial value, use the first element and start from index 1; an empty array with no initial value throws a TypeError.

Example:

Array.prototype.myMap = function (cb, thisArg) {
if (typeof cb !== "function") throw new TypeError(cb + " is not a function");
const result = new Array(this.length);
for (let i = 0; i < this.length; i++) {
if (i in this) result[i] = cb.call(thisArg, this[i], i, this);
}
return result;
};
Array.prototype.myFilter = function (cb, thisArg) {
const result = [];
for (let i = 0; i < this.length; i++) {
if (i in this && cb.call(thisArg, this[i], i, this)) result.push(this[i]);
}
return result;
};
Array.prototype.myReduce = function (cb, initialValue) {
let i = 0;
let acc;
if (arguments.length >= 2) {
acc = initialValue;
} else {
while (i < this.length && !(i in this)) i++; // find first real element
if (i >= this.length) throw new TypeError("Reduce of empty array with no initial value");
acc = this[i++];
}
for (; i < this.length; i++) {
if (i in this) acc = cb(acc, this[i], i, this);
}
return acc;
};
[1, 2, 3].myMap((x) => x * 2); // [2, 4, 6]
[1, 2, 3, 4].myFilter((x) => x % 2 === 0); // [2, 4]
[1, 2, 3].myReduce((a, b) => a + b, 0); // 6

Common wrong answer: Checking initialValue === undefined to detect “no initial value” — reduce(fn, undefined) is a valid explicit initial value. Use arguments.length.

Q (mid): Polyfill Function.prototype.bind.

Say this (30 sec): Return a new function that calls the original with the fixed this and pre-filled args concatenated with new args. Bonus: if the bound function is called with new, this should be the new instance, not the bound context.

Example:

Function.prototype.myBind = function (context, ...boundArgs) {
if (typeof this !== "function") throw new TypeError("Bind must be called on a function");
const originalFn = this;
function bound(...args) {
const isNew = this instanceof bound;
return originalFn.apply(isNew ? this : context, [...boundArgs, ...args]);
}
if (originalFn.prototype) bound.prototype = Object.create(originalFn.prototype);
return bound;
};
function greet(greeting) { return `${greeting}, ${this.name}`; }
const hi = greet.myBind({ name: "Aman" }, "Hi");
hi(); // "Hi, Aman"

Follow-ups they ask: Implement call too?

Function.prototype.myCall = function (context = globalThis, ...args) {
const key = Symbol("fn"); // unique key avoids clobbering existing props
const ctx = Object(context); // box primitives
ctx[key] = this;
const result = ctx[key](...args);
delete ctx[key];
return result;
};
Q (mid): Implement retry with exponential backoff.

Say this (30 sec): Call the async function; on failure, wait and retry, doubling the delay each time (base * 2^attempt), plus random jitter so many clients don’t retry at the same moment. Stop after retries attempts and throw the last error. Don’t retry errors that won’t succeed (like 4xx validation errors).

Example:

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function retry(fn, { retries = 3, baseDelay = 500, shouldRetry = () => true } = {}) {
for (let attempt = 0; ; attempt++) {
try {
return await fn(attempt);
} catch (err) {
if (attempt >= retries || !shouldRetry(err)) throw err;
const delay = baseDelay * 2 ** attempt + Math.random() * 100; // 500, 1000, 2000 (+ jitter)
await sleep(delay);
}
}
}
// usage
const data = await retry(async () => {
const res = await fetch("/api/data");
if (!res.ok) throw Object.assign(new Error("HTTP " + res.status), { status: res.status });
return res.json();
}, { shouldRetry: (e) => !e.status || e.status >= 500 });
Q (mid): Run promises with a concurrency limit.

Say this (30 sec): Start limit workers; each worker takes the next task index from a shared counter until none are left. Results keep the original order by index. Common for “upload 100 files, max 3 at a time.”

Example:

async function runWithLimit(tasks, limit) {
const results = new Array(tasks.length);
let next = 0;
async function worker() {
while (next < tasks.length) {
const i = next++; // safe: JS is single-threaded between awaits
results[i] = await tasks[i]();
}
}
await Promise.all(Array.from({ length: Math.min(limit, tasks.length) }, worker));
return results;
}
Q (basic): Implement once and a sleep function.

Example:

function once(fn) {
let called = false;
let result;
return function (...args) {
if (!called) {
called = true;
result = fn.apply(this, args);
}
return result;
};
}
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
await sleep(1000);
Q (basic): Build a counter with increment, decrement and reset.

Say this (30 sec): Use useState with the functional updater since the next value depends on the previous. Add a guard if it shouldn’t go below zero.

Example:

function Counter({ initial = 0, step = 1 }) {
const [count, setCount] = useState(initial);
return (
<div>
<p aria-live="polite">{count}</p>
<button onClick={() => setCount((c) => Math.max(0, c - step))} disabled={count === 0}>-</button>
<button onClick={() => setCount((c) => c + step)}>+</button>
<button onClick={() => setCount(initial)}>Reset</button>
</div>
);
}
Q (basic): Build a todo list (add, toggle, delete).

Say this (30 sec): State is an array of { id, text, done }. Use crypto.randomUUID() for stable keys. All updates are immutable: spread to add, map to toggle, filter to delete. Trim and ignore empty input. Use a <form> so Enter submits.

Example:

function TodoApp() {
const [todos, setTodos] = useState([]);
const [text, setText] = useState("");
const addTodo = (e) => {
e.preventDefault();
const value = text.trim();
if (!value) return;
setTodos((prev) => [...prev, { id: crypto.randomUUID(), text: value, done: false }]);
setText("");
};
const toggle = (id) =>
setTodos((prev) => prev.map((t) => (t.id === id ? { ...t, done: !t.done } : t)));
const remove = (id) => setTodos((prev) => prev.filter((t) => t.id !== id));
return (
<div>
<form onSubmit={addTodo}>
<label htmlFor="todo">New todo</label>
<input id="todo" value={text} onChange={(e) => setText(e.target.value)} />
<button type="submit">Add</button>
</form>
{todos.length === 0 ? <p>No todos yet</p> : (
<ul>
{todos.map((t) => (
<li key={t.id}>
<label>
<input type="checkbox" checked={t.done} onChange={() => toggle(t.id)} />
<span style={{ textDecoration: t.done ? "line-through" : "none" }}>{t.text}</span>
</label>
<button onClick={() => remove(t.id)} aria-label={`Delete ${t.text}`}>x</button>
</li>
))}
</ul>
)}
</div>
);
}

Follow-ups they ask: Persist it? → lazy-init from localStorage and save in an effect (see useLocalStorage on the React page). Filters (all/active/done)? → keep a filter state and derive the visible list during render, don’t store it.

Q (mid): Build a debounced search that calls an API.

Say this (30 sec): Keep the input value in state, debounce it with a useDebounce hook, and fetch in an effect keyed on the debounced value. Use an AbortController in the cleanup so an older, slower response can’t overwrite a newer one (race condition). Handle loading, error and empty states.

Example:

function useDebounce(value, delay = 400) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(id);
}, [value, delay]);
return debounced;
}
function Search() {
const [query, setQuery] = useState("");
const [results, setResults] = useState([]);
const [status, setStatus] = useState("idle"); // idle | loading | error
const debouncedQuery = useDebounce(query.trim());
useEffect(() => {
if (!debouncedQuery) { setResults([]); setStatus("idle"); return; }
const controller = new AbortController();
setStatus("loading");
fetch(`/api/search?q=${encodeURIComponent(debouncedQuery)}`, { signal: controller.signal })
.then((res) => { if (!res.ok) throw new Error(res.statusText); return res.json(); })
.then((data) => { setResults(data); setStatus("idle"); })
.catch((err) => { if (err.name !== "AbortError") setStatus("error"); });
return () => controller.abort();
}, [debouncedQuery]);
return (
<div>
<input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search..." aria-label="Search" />
{status === "loading" && <p>Loading...</p>}
{status === "error" && <p>Something went wrong</p>}
{status === "idle" && debouncedQuery && results.length === 0 && <p>No results</p>}
<ul>{results.map((r) => <li key={r.id}>{r.name}</li>)}</ul>
</div>
);
}
Q (mid): Build a reusable fetch hook with loading and error states.

Say this (30 sec): Return { data, error, loading }. Abort on cleanup to avoid setting state after unmount or from a stale request. Check res.ok because fetch doesn’t reject on HTTP errors. In production I’d use TanStack Query for caching, retries and dedupe.

Example:

function useFetch(url) {
const [state, setState] = useState({ data: null, error: null, loading: true });
useEffect(() => {
const controller = new AbortController();
setState({ data: null, error: null, loading: true });
fetch(url, { signal: controller.signal })
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.then((data) => setState({ data, error: null, loading: false }))
.catch((error) => {
if (error.name !== "AbortError") setState({ data: null, error, loading: false });
});
return () => controller.abort();
}, [url]);
return state;
}
function Users() {
const { data, error, loading } = useFetch("/api/users");
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return <ul>{data.map((u) => <li key={u.id}>{u.name}</li>)}</ul>;
}
Q (mid): Build infinite scroll.

Say this (30 sec): Render a sentinel element at the end of the list and watch it with IntersectionObserver. When it becomes visible and we’re not already loading and there’s more data, fetch the next page and append. Guard against duplicate requests, disconnect the observer on cleanup, and stop when the API says there are no more items.

Example:

function InfiniteList() {
const [items, setItems] = useState([]);
const [page, setPage] = useState(1);
const [loading, setLoading] = useState(false);
const [hasMore, setHasMore] = useState(true);
const sentinelRef = useRef(null);
useEffect(() => {
let cancelled = false;
setLoading(true);
fetch(`/api/items?page=${page}`)
.then((r) => r.json())
.then((data) => {
if (cancelled) return;
setItems((prev) => [...prev, ...data.items]);
setHasMore(data.hasMore);
})
.finally(() => { if (!cancelled) setLoading(false); });
return () => { cancelled = true; };
}, [page]);
useEffect(() => {
const el = sentinelRef.current;
if (!el || loading || !hasMore) return;
const observer = new IntersectionObserver(
([entry]) => { if (entry.isIntersecting) setPage((p) => p + 1); },
{ rootMargin: "200px" } // start loading a bit before the bottom
);
observer.observe(el);
return () => observer.disconnect();
}, [loading, hasMore]);
return (
<div>
<ul>{items.map((item) => <li key={item.id}>{item.title}</li>)}</ul>
{loading && <p>Loading...</p>}
{!hasMore && <p>You're all caught up</p>}
<div ref={sentinelRef} />
</div>
);
}

Follow-ups they ask: Thousands of items? → virtualize the list (TanStack Virtual) so only visible rows are in the DOM.

Q (mid): Build a modal.

Say this (30 sec): Render through a portal to document.body to escape overflow and z-index issues. Close on Escape and on backdrop click (but not on clicks inside the content). Lock body scroll while open, move focus into the modal, and use role="dialog" with aria-modal. Clean up listeners in the effect. (The native <dialog> element with showModal() gives focus trapping and Escape for free — worth mentioning.)

Example:

import { createPortal } from "react-dom";
function Modal({ open, onClose, title, children }) {
const dialogRef = useRef(null);
useEffect(() => {
if (!open) return;
const onKey = (e) => { if (e.key === "Escape") onClose(); };
document.addEventListener("keydown", onKey);
const prevOverflow = document.body.style.overflow;
document.body.style.overflow = "hidden";
dialogRef.current?.focus();
return () => {
document.removeEventListener("keydown", onKey);
document.body.style.overflow = prevOverflow;
};
}, [open, onClose]);
if (!open) return null;
return createPortal(
<div className="backdrop" onClick={onClose}>
<div
ref={dialogRef}
role="dialog"
aria-modal="true"
aria-labelledby="modal-title"
tabIndex={-1}
className="modal"
onClick={(e) => e.stopPropagation()}
>
<h2 id="modal-title">{title}</h2>
{children}
<button onClick={onClose}>Close</button>
</div>
</div>,
document.body
);
}
Q (basic): Build a star rating component.

Say this (30 sec): Keep rating (selected) and hover (preview) state. A star is filled if its index is ≤ hover || rating. Use buttons for keyboard access and aria-labels. Make it controlled-friendly by accepting value/onChange.

Example:

function StarRating({ max = 5, value = 0, onChange }) {
const [hover, setHover] = useState(0);
const display = hover || value;
return (
<div role="radiogroup" aria-label="Rating" onMouseLeave={() => setHover(0)}>
{Array.from({ length: max }, (_, i) => {
const star = i + 1;
return (
<button
key={star}
type="button"
role="radio"
aria-checked={value === star}
aria-label={`${star} star${star > 1 ? "s" : ""}`}
onClick={() => onChange(star)}
onMouseEnter={() => setHover(star)}
style={{ color: star <= display ? "gold" : "gray", fontSize: 24, background: "none", border: "none" }}
>
★
</button>
);
})}
</div>
);
}
// usage
const [rating, setRating] = useState(0);
<StarRating value={rating} onChange={setRating} />
Q (basic): Build tabs.

Say this (30 sec): Store the active tab index or id. Render a tab list of buttons and only the active panel. Add ARIA roles (tablist, tab, tabpanel) and aria-selected. Bonus: arrow-key navigation.

Example:

function Tabs({ tabs }) {
const [active, setActive] = useState(0);
const onKeyDown = (e) => {
if (e.key === "ArrowRight") setActive((i) => (i + 1) % tabs.length);
if (e.key === "ArrowLeft") setActive((i) => (i - 1 + tabs.length) % tabs.length);
};
return (
<div>
<div role="tablist" onKeyDown={onKeyDown}>
{tabs.map((tab, i) => (
<button
key={tab.id}
role="tab"
id={`tab-${tab.id}`}
aria-selected={active === i}
aria-controls={`panel-${tab.id}`}
tabIndex={active === i ? 0 : -1}
onClick={() => setActive(i)}
>
{tab.label}
</button>
))}
</div>
<div role="tabpanel" id={`panel-${tabs[active].id}`} aria-labelledby={`tab-${tabs[active].id}`}>
{tabs[active].content}
</div>
</div>
);
}
<Tabs tabs={[
{ id: "profile", label: "Profile", content: <p>Profile info</p> },
{ id: "settings", label: "Settings", content: <p>Settings</p> },
]} />
Q (mid): Build a countdown/stopwatch timer.

Say this (30 sec): Store the interval ID in a useRef (not state). Use the functional updater inside setInterval to avoid stale closures. Clear the interval on pause and in the unmount cleanup. For accuracy over long durations, compute elapsed time from Date.now() instead of counting ticks.

Example:

function Stopwatch() {
const [ms, setMs] = useState(0);
const [running, setRunning] = useState(false);
const intervalRef = useRef(null);
const startRef = useRef(0);
useEffect(() => {
if (!running) return;
startRef.current = Date.now() - ms;
intervalRef.current = setInterval(() => setMs(Date.now() - startRef.current), 100);
return () => clearInterval(intervalRef.current);
// eslint-disable-next-line react-hooks/exhaustive-deps -- only restart on running change
}, [running]);
return (
<div>
<p>{(ms / 1000).toFixed(1)}s</p>
<button onClick={() => setRunning((r) => !r)}>{running ? "Pause" : "Start"}</button>
<button onClick={() => { setRunning(false); setMs(0); }}>Reset</button>
</div>
);
}
Q (mid): Build an accordion (only one section open at a time).

Example:

function Accordion({ items }) {
const [openId, setOpenId] = useState(null);
return (
<div>
{items.map((item) => {
const isOpen = openId === item.id;
return (
<div key={item.id}>
<button
aria-expanded={isOpen}
aria-controls={`section-${item.id}`}
onClick={() => setOpenId(isOpen ? null : item.id)}
>
{item.title}
</button>
{isOpen && <div id={`section-${item.id}`}>{item.content}</div>}
</div>
);
})}
</div>
);
}

Follow-ups they ask: Allow multiple open? → store a Set of open ids (create a new Set on each update for immutability).