cf.completefrontend
JAVASCRIPT CODING

JavaScript problems

160 problems for the JavaScript coding round: write debounce, Promise.all, deep clone, an event emitter, polyfills, and real DOM widgets in the editor, and run tests that say exactly what works and what doesn't. 47 easy, 82 medium, and 31 hard.

Not algorithm puzzles (the DSA section has those): these test the language and the browser. Everything runs on this page, your code is saved as you go, and hints are free. Sign in with Google to see the solutions.

160 of 160 problems

Timing

  1. DebounceWait until calls stop for wait ms, then call the function once with the latest arguments.Easy
  2. ThrottleRun a function right away, then at most once every wait ms, dropping the calls in between.Easy
  3. setInterval with setTimeoutRebuild setInterval and clearInterval from chained setTimeout calls.Easy
  4. Clear all timeoutsMake timeouts through an object that remembers them, so one call can cancel every timeout it started.Easy
  5. Stopwatch with lapsBuild a stopwatch that starts, stops, records laps, and resets, and stays exact to the millisecond.Easy
  6. Throttle with a trailing callRun a function at most once every wait ms, and once more at the end with the latest arguments.Medium
  7. Idle timerTell when the user has been inactive for timeout ms, and when they come back, from events on a target.Medium
  8. Countdown timer with pause and resumeCount down in whole seconds, and pause and resume without losing the part of a second already counted.Medium
  9. Poll until a condition holdsCall a check every interval ms until it returns something truthy, and give up with an error after timeout ms.Medium
  10. Task scheduler with delaysRun tasks one at a time, in order, each a given delay after the previous one has finished.Medium
  11. Rate limiterStart at most limit calls in any interval ms, queue the rest, and return a promise of each result.Medium
  12. Batch callsCollect items for wait ms, or until there are maxSize of them, then pass them all to one call of a function.Medium
  13. Interval that corrects its own driftRun a function on a fixed schedule that late timers can't push back, skipping ticks that are already overdue.Hard
  14. Debounce with leading, trailing, and maxWaitA debounce that can run at the start of a burst, at the end, or both, and at least every maxWait ms.Hard
  15. Debounce async calls, latest winsDebounce an async function so every call gets a promise, and only the latest call ever gets a result.Hard

Functions

  1. OnceWrap a function so it runs only on the first call, and every later call returns that first result.Easy
  2. Counter with private stateBuild a counter whose count lives in a closure, so only its methods can read or change it.Easy
  3. Chainable calculatorReturn an object whose methods each return it, so calls chain: calculator(2).add(3).multiply(4).value() is 20.Easy
  4. ComposeCombine functions right to left into one, so compose(f, g)(x) is f(g(x)).Easy
  5. PipeCombine functions left to right into one, so pipe(f, g)(x) is g(f(x)).Easy
  6. Before and afterLimit a function by call count: before runs it only for the first calls, after only from the nth call on.Medium
  7. Partial applicationFix some of a function's arguments now, with placeholders for gaps, and pass the rest later.Medium
  8. CurryCollect a function's arguments over several calls and call it once it has as many as it declares.Medium
  9. Infinite curry sumWrite sum so sum(1)(2)(3)() is 6: each call adds its numbers, and a call with no arguments returns the total.Medium
  10. MemoizeCache a function's results by all of its arguments, compared the way a Map compares keys.Medium
  11. Memoize with a key resolver and size limitCache results under a key you choose, and drop the least recently used entry when the cache is full.Medium
  12. Memoize object arguments with a WeakMapCache results by every argument, but hold object arguments only as WeakMap keys, so the cache never keeps them in memory.Medium
  13. Build a spyWrite createSpy: a function that records its calls, their this, results, and errors, like jest.fn().Medium
  14. TrampolineRun a recursive function that returns thunks in a loop, so it can go 100,000 steps deep without overflowing the stack.Medium
  15. Curry with placeholdersCurry a function, with a placeholder that reserves a position to fill in a later call.Hard
  16. Memoize an async functionCache an async function's promises by key: share calls in flight, keep results, and forget failures so the next call tries again.Hard
  17. Compose middleware like KoaRun Koa-style middleware: each gets the context and a next() that runs the rest of the chain and returns a promise.Hard

Promises & async

  1. SleepReturn a promise that fulfills after ms milliseconds, so await can pause an async function.Easy
  2. PromisifyTurn a Node-style callback function into one that returns a promise.Easy
  3. Run async tasks in seriesRun async tasks one after another, each starting when the previous one finishes, and collect their results.Easy
  4. Promise.raceSettle the same way as the first input to settle, as Promise.race does.Easy
  5. promisifyAllGive every callback method of an object a promise-returning nameAsync twin, including the methods it inherits from its class.Medium
  6. Promise.allFulfill with every input's value in order, or reject as soon as one input rejects, as Promise.all does.Medium
  7. Promise.allSettledWait for every input to settle and report each outcome, in order, as Promise.allSettled does.Medium
  8. Promise.anyFulfill with the first input to fulfill, or reject with an AggregateError once they've all failed, as Promise.any does.Medium
  9. Promise with a timeoutReject with a TimeoutError if a promise takes longer than ms to settle, and leave no timer behind.Medium
  10. Wait for an event, with a timeoutTurn an emitter's next event into a promise that rejects on an "error" event or a timeout, and leaves no listener or timer behind.Medium
  11. Race that aborts the losersStart async tasks together, settle like the first one to finish, and abort every other task through its own AbortSignal.Medium
  12. Async pipeChain sync and async functions left to right, awaiting each step before passing its result on.Medium
  13. Retry with exponential backoffCall an async function again when it fails, waiting longer before each new attempt.Medium
  14. Dedupe in-flight requestsShare one in-flight promise between callers asking for the same key, and start fresh once it settles.Medium
  15. Stale-while-revalidate cacheServe cached values at once, refresh stale ones in the background, and keep at most one fetch per key in flight.Medium
  16. DataLoader-style batch loaderCollect the load(key) calls made in one tick into a single batchFn(keys) call, and give each caller its own result.Hard
  17. Map with a concurrency limitRun an async function over a list with at most limit calls at a time, and keep the results in input order.Hard
  18. Async task queue with pause and resumeBuild a queue that runs async tasks with a concurrency limit, hands each caller its task's result, and can pause and resume.Hard
  19. Cancellable task with AbortControllerRun an async task with an AbortSignal, and cancel it so its promise rejects at once, even if the task ignores the signal.Hard

Iterators & generators

  1. Fibonacci generator with takeWrite an endless Fibonacci generator, and a lazy take(iterable, n) that yields the first n values of any iterable.Easy
  2. Make a linked list iterableGive a linked list class a [Symbol.iterator] so it works with for...of and spread, and a LinkedList.from(iterable) to build one.Easy
  3. Zip iterablesPair up the values of several iterables, position by position, stop at the shortest, and close the others.Medium
  4. Interleave iterables round-robinTake one value from each iterable in turn, skip the ones that run out, and carry on until all of them are done.Medium
  5. Flatten nested iterablesLazily yield the values inside nested arrays, Sets, and generators, keeping strings whole, down to an optional depth.Medium
  6. Lazy iterator helpersBuild lazy(iterable) with chainable map, filter, and take that do no work until toArray() or a loop asks for values.Medium
  7. Async iterator over a paginated APITurn a page-by-page fetcher into an async iterable of items that fetches each page only when it's needed.Medium
  8. Run a generator as a coroutineWrite run(genFn, ...args): drive a generator that yields promises, resuming it with each result, the way async and await work.Medium
  9. Merge async iterablesCombine several async iterables into one that yields each value as soon as any source produces it, and closes the sources when it stops.Hard
  10. Turn events into an async iteratorWrite on(target, type): an async iterator over events that buffers the ones nobody is waiting for and removes its listener on return().Hard

Polyfills

  1. Array.prototype.mapWrite myMap, a polyfill for map: a new array of callback results, with thisArg, holes kept as holes.Easy
  2. Array.prototype.filterWrite myFilter, a polyfill for filter: keep the elements whose callback result is truthy, skipping holes.Easy
  3. Array.prototype.some and everyWrite mySome and myEvery, polyfills for some and every: stop at the element that settles the answer, and return a boolean.Easy
  4. Array.prototype.includesWrite myIncludes, a polyfill for includes: compare like === but find NaN, read holes as undefined, and start at fromIndex.Easy
  5. Object.createWrite Object.myCreate, a polyfill for Object.create: a new object with a chosen prototype, even null.Easy
  6. The instanceof operatorWrite myInstanceOf(value, Constructor): walk the prototype chain to answer what instanceof would.Easy
  7. Function.prototype.callWrite myCall, a polyfill for call: run a function with a chosen this, without call, apply, or bind.Medium
  8. The new operatorWrite myNew(Constructor, ...args): create the object, link its prototype, run the constructor, pick the result.Medium
  9. Array.prototype.reduceWrite myReduce, a polyfill for reduce, with its rules for a missing initial value, holes, and empty arrays.Medium
  10. Array.prototype.flatWrite myFlat(depth), a polyfill for flat: spread nested arrays into one, down to a depth, dropping holes.Medium
  11. Array.prototype.sortWrite mySort, a polyfill for sort: a stable sort in place, comparing as strings by default, with undefined and holes moved to the end.Medium
  12. Array.fromWrite Array.myFrom, a polyfill for Array.from: turn iterables and array-likes into arrays, with an optional mapFn.Medium
  13. Object.groupBy and Map.groupByWrite Object.myGroupBy and Map.myGroupBy: put the items of any iterable into groups by key, in an object with no prototype or in a Map.Medium
  14. Object.assignWrite Object.myAssign, a polyfill for Object.assign: copy own enumerable keys, symbols included, with get and set.Medium
  15. Promise.prototype.finallyWrite myFinally, a polyfill for finally: run cleanup on either outcome and pass the original result through.Medium
  16. Function.prototype.bindWrite myBind, a polyfill for bind: a fixed this, preset arguments, and correct behaviour with new.Hard
  17. A promise from scratchBuild MyPromise with then, catch, resolve, and reject: microtask callbacks, chaining, and thenables.Hard
  18. JSON.stringifyWrite JSON.myStringify for plain data: escaped strings, skipped values, toJSON, and a TypeError on cycles.Hard
  19. JSON.parseWrite JSON.myParse: turn JSON text into the value it describes, and throw a SyntaxError that says where for anything JSON doesn't allow.Hard

Objects & data

  1. Get by pathRead a nested value by a path like a.b[0].c, and fall back to a default when anything on the way is missing.Easy
  2. pick and omitMake a new object with only some of an object's keys, or with all of them but some.Easy
  3. isEmptyTell whether any value holds nothing: empty strings, arrays, Maps, Sets, and objects, but never numbers or functions.Easy
  4. shallowEqualCompare two objects one level deep, key by key with Object.is, the way React decides whether props changed.Easy
  5. Camelize keysTurn every snake_case key of an API response into camelCase, at every depth, without touching the values.Easy
  6. Deep freezeFreeze an object and everything reachable from it, including symbol keys, functions, and cycles.Easy
  7. Set by pathWrite a nested value by a path like a.b[0].c, creating objects and arrays on the way, without allowing prototype pollution.Medium
  8. Immutable setInReturn a copy with one nested value changed, copying only the objects on the path and sharing every other branch.Medium
  9. Flatten an objectTurn a nested object into a single level whose keys are dotted paths, like user.tags.0.Medium
  10. Unflatten an objectRebuild a nested object, with arrays where keys are indexes, from an object whose keys are dotted paths.Medium
  11. Compact an objectDrop null, undefined, and empty objects and arrays at every depth, including ones that only become empty on the way.Medium
  12. Deep mergeMerge objects into a new one, recursively for nested objects, with later values winning and no prototype pollution.Medium
  13. Object diffCompare two objects and list the dotted paths that were added, removed, and changed.Medium
  14. Normalize nested dataTurn nested API data into tables of items by id, with every nested item replaced by its id, following a schema.Medium
  15. Deep equalCompare two values by structure and contents, including Map, Set, Date, RegExp, prototypes, and cycles.Hard
  16. Deep cloneCopy any value all the way down, including Map, Set, Date, class instances, shared references, and cycles.Hard
  17. Apply a JSON PatchApply add, remove, and replace operations at JSON Pointer paths, returning a new document and failing cleanly on bad paths.Hard

Arrays & collections

  1. Chunk an arraySplit an array into groups of size items, with whatever is left over in a shorter last group.Easy
  2. Partition an arraySplit an array in two in one pass: the items that pass a test, and the items that don't.Easy
  3. uniqueByRemove duplicates by a key, a property name or a function, keeping the first item for each key, in order.Easy
  4. zip and unzipPair up the items of several arrays by index, padding short arrays with undefined, and split the pairs back apart.Medium
  5. Move an item in a listReturn a copy of a list with one item moved to a new index, the way a list reorders after drag and drop.Medium
  6. sortedIndex with binary searchFind where a value belongs in a sorted array, before or after equal items, reading only O(log n) items.Medium
  7. Set operations by keyIntersect, subtract, and merge two arrays of objects by a key such as id, keeping one item per key.Medium
  8. Fisher–Yates shuffleShuffle a copy of an array so every order is equally likely, using a random function that tests can replace.Medium
  9. sortBy with several keysSort a copy of an array by several keys, each ascending or descending, stably, with missing values last.Hard
  10. Build a tree from a flat listTurn a flat list of items with id and parentId into a nested tree in O(n), keeping order and catching cycles.Hard

Classes & state

  1. Undo/redo historyA class that holds a value and its history, so you can step back with undo and forward again with redo.Easy
  2. Iterable Range classMake a Range class work with for...of and spread by writing its iterator by hand.Easy
  3. TTL cacheA cache whose entries expire a set number of milliseconds after they're stored.Easy
  4. combineReducersCombine reducers that each own one key of the state into a single reducer for the whole state.Easy
  5. Form validatorA class that checks a form's values against rules and returns, for each failing field, the message of its first failing rule.Easy
  6. Event emitterAn EventEmitter class with on, off, once, and emit that stays correct when listeners change during an emit.Medium
  7. LRU cacheA fixed-size cache with O(1) get and put that drops the least recently used entry when it's full.Medium
  8. Redux-style storecreateStore(reducer, initialState) with getState, dispatch, and subscribe, the core of Redux.Medium
  9. Redux applyMiddlewareapplyMiddleware(...middlewares) wraps a Redux store's dispatch in a chain of middleware that can log, change, or stop actions.Medium
  10. PubSub with wildcard topicsA publish/subscribe hub whose subscriptions can use * and ** to match whole groups of dot-separated topics.Medium
  11. Client-side routercreateRouter(routes) with resolve(url): match paths like /users/:id, capture and decode params, and support a final * wildcard.Medium
  12. Finite state machinecreateMachine(config): a machine that moves between named states on events, with guarded transitions.Medium
  13. Toast queueA class that shows at most N toasts at once, queues the rest, and dismisses each one a set time after it appears.Medium
  14. Async mutexA lock for async code: one holder at a time, and everyone else waits their turn in order.Medium
  15. Observable with map and filterA lazy Observable class with subscribe, unsubscribe, teardown, and chainable map and filter operators.Hard
  16. Reactivity with ProxyVue-style reactivity: reactive(object) returns a Proxy that tracks reads, and watchEffect(fn) reruns fn when what it read changes.Hard
  17. Signals with computed and effectReactive signals: signal, computed, and effect, with automatic dependency tracking and no glitches.Hard

Strings & formatting

  1. Escape HTMLTurn any value into text that's safe to put inside HTML, by replacing the five characters HTML treats specially.Easy
  2. classNamesBuild a class attribute from strings, numbers, objects of flags, and nested arrays, skipping everything falsy.Easy
  3. Format a listJoin names into a readable list like "Ada, Grace, and Alan", with "or" as an option and a limit that counts the rest.Easy
  4. Build a query stringTurn an object into a URL query string, encoding every part, repeating keys for arrays, and skipping null and undefined.Easy
  5. Format bytesTurn a size in bytes into a short label like 1.5 KB, picking the unit and rounding to a given number of decimals.Easy
  6. SlugifyTurn a title into a URL slug: lowercase ASCII letters and digits joined by hyphens, with accents removed.Easy
  7. Truncate at a word boundaryShorten text to a maximum length without cutting a word in half, ending with an ellipsis that counts toward the limit.Medium
  8. Template rendererFill {{ path }} placeholders in a template with values from an object, following dotted paths and inserting values as plain text.Medium
  9. camelCase, snake_case, and kebab-caseSplit text in any naming style into words, then join them again as camelCase, snake_case, or kebab-case.Medium
  10. Parse a query stringTurn a URL query string into an object: decode every part, collect repeated keys into arrays, and keep __proto__ harmless.Medium
  11. Format a numberFormat a number with a thousands separator and a fixed number of decimals, without Intl, rounding halves away from zero.Medium
  12. Relative timeDescribe how long ago, or how far ahead, a date is: "just now", "3 minutes ago", or "in 2 days", without Intl.Medium
  13. Compare versionsCompare two semver-style version strings, numbers first and then pre-release tags, for use as a sort comparator.Medium
  14. Glob matchingCheck whether a file path matches a glob pattern with ?, *, and ** wildcards, like src/**/*.test.js.Medium
  15. Highlight matchesWrap every case-insensitive match of a search query in <mark>, escaping the text so the result is safe HTML.Hard
  16. Parse a CSV lineSplit one line of CSV into fields, handling quoted fields with commas and doubled quotes, and rejecting malformed quotes.Hard
  17. Inline Markdown to HTMLConvert Markdown's code, bold, italic, and links into safe HTML: escape all text and allow only safe link URLs.Hard

DOM

  1. Render a list from dataFill an empty list with one item per entry, safely, and render again when the data changes.Easy
  2. Character counter for a textareaShow how many characters are left in a textarea as the user types, with a warning near the limit.Easy
  3. getElementsByClassName by walking the treeFind every element inside a root that has all the given classes, walking the DOM tree yourself.Easy
  4. Turn a DOM tree into JSONDescribe an element and everything inside it as plain { tag, attrs, children } data.Easy
  5. Show password toggleLet users show and hide a password with a toggle button that keeps its label and reports its state with aria-pressed.Easy
  6. Build DOM from a JSON specTurn nested { tag, attrs, children } data into real DOM nodes, with attributes, listeners, and safe text.Medium
  7. Closest common ancestor of two nodesFind the deepest node that contains two given nodes, or null when they're in different trees.Medium
  8. Next node in document orderFind the node that comes after a given one in a depth-first walk, without leaving a root.Medium
  9. Event delegation helperHandle events for every matching element inside a container with one listener, including elements added later.Medium
  10. Accordion with one open panelWire up accordion headers so one panel opens at a time, keeping aria-expanded and hidden in sync.Medium
  11. Todo listWire a form, a list, and a counter into a working todo list with add, complete, and delete.Medium
  12. Serialize a form to an objectRead a form's current values into a plain object, with booleans for lone checkboxes and arrays for multi-value fields.Medium
  13. Star ratingTurn five stars into an accessible radio group: rate by clicking or with the arrow keys, with aria-checked and a roving tabindex.Medium
  14. Sortable tableSort a table's rows when a column header is clicked, flipping the direction and keeping aria-sort on the sorted column.Medium
  15. Checkbox tree with indeterminate parentsKeep a nested list of checkboxes in sync: a parent checks everything below it, and shows checked, unchecked, or mixed from its children.Medium
  16. Tabs with arrow-key navigationBuild accessible tabs: aria-selected, a roving tabindex, panels shown by aria-controls, and arrow, Home, and End keys.Hard
  17. Modal dialog with focus managementOpen a dialog with focus inside, keep Tab inside it, close it on Escape, and return focus where it was.Hard
  18. Autocomplete comboboxBuild an accessible autocomplete: filter suggestions as the user types, move through them with aria-activedescendant, and pick one with Enter.Hard
  19. Keyed list update that reuses nodesUpdate a list to match new data by key, reusing, moving, adding, and removing only the nodes that need it.Hard