Implement utility functions, polyfills and async helpers in JavaScript.
Progress
0 / 119 completed
Showing 119 questions
Array.prototype.at
Implement Array.prototype.at, including negative indices and the spec's integer coercion rules.
Array.prototype.concat
Implement Array.prototype.concat, including sparse arrays and Symbol.isConcatSpreadable.
Array.prototype.filter
Implement Array.prototype.filter with thisArg support and correct handling of sparse arrays.
Array.prototype.flat
Implement Array.prototype.flat with a depth argument, hole removal and an iterative variant.
Array.prototype.map
Implement Array.prototype.map, keeping holes in sparse arrays and supporting thisArg.
Array.prototype.reduce
Implement Array.prototype.reduce, including the no-initial-value rules and sparse arrays.
Array.prototype.square
Add a square() method to every array that returns a new array of squared values.
Async Queue with Priority
Run async tasks with a concurrency limit, starting higher-priority tasks first and keeping FIFO order within a priority.
Backbone Model
Build an observable Model class with defaults, get/set/unset, per-attribute change events, previous values and silent updates.
Cache Async (Deduplicate Requests)
Memoize an async function so concurrent calls share one in-flight promise, results expire after a TTL and failures are not cached.
Camel Case Keys
Deeply convert snake_case object keys from an API response into camelCase.
Cancellable Interval
Wrap setInterval so it returns a cancel function that stops future ticks.
Cancellable Timeout
Wrap setTimeout so it returns a cancel function instead of a timer id.
Chunk
Split an array into consecutive groups of a fixed size, with a shorter final group if needed.
Clamp
Restrict a number to an inclusive range between a lower and an upper bound.
classnames
Build a CSS class string from strings, numbers, nested arrays and conditional objects.
Compact
Return a new array with every falsy value removed.
Compose
Combine functions right to left into a single function, where each output feeds the next input.
Count By
Count how many elements of an array map to each key produced by an iteratee.
Curry
Turn a function of n arguments into one that can be called with those arguments one or several at a time.
Curry II (with placeholders)
Curry a function so that arguments can be supplied in any order using a placeholder value.
Data Merging
Merge workout session records by user: sum durations and combine equipment lists without duplicates.
Data Selection
Implement a small query function over an array of records: filtering, multi-key stable sorting, pagination and field projection.
Debounce
Delay invoking a function until a burst of calls has stopped for a given wait time.
Debounce II
Debounce with leading, trailing and maxWait options, plus cancel and flush.
Deep Clone
Make a deep copy of a JSON-like value so that no nested object or array is shared with the original.
Deep Clone II
Deep clone values with circular references, shared references, Date, RegExp, Map, Set, symbols and prototypes.
Deep Equal
Decide whether two JSON-like values are structurally equal, comparing nested objects and arrays by content.
Deep Map
Transform every leaf value in a nested object/array structure while preserving its shape.
Deep Merge
Recursively merge configuration objects without mutating the inputs, with clear rules for arrays and undefined.
Deep Omit
Remove the given keys from an object at every level of nesting, including inside arrays.
Dependency Injection Container
Build an IoC container with transient, singleton and scoped lifetimes, child scopes, overrides and circular-dependency detection.
Difference
Return the elements of an array that do not appear in any of the other given arrays.
Identical DOM Trees
Decide whether two DOM nodes are structurally identical: same tags, attributes, text and children, without using isEqualNode.
Drop Right While
Drop trailing elements of an array for as long as a predicate holds, scanning from the end.
Drop While
Drop leading elements of an array for as long as a predicate holds, then keep the rest.
Event Emitter
Implement an EventEmitter class with on, off and emit, the observer pattern behind Node's events module and DOM events.
Event Emitter II
Extend an event emitter with once, unsubscribe handles, bulk off and listener counts, with well-defined behaviour during emit.
Feature Flag Evaluator
Evaluate feature flags with a kill switch, targeting rules and a percentage rollout that uses stable hashing so users keep their bucket.
Fill
Overwrite a range of an array with a value, supporting negative start and end indices.
Find Index
Return the index of the first element that satisfies a predicate, starting from an optional index.
Find Last Index
Return the index of the last element that satisfies a predicate, searching backwards from an optional index.
Flatten
Flatten a nested array to a given depth, recursively or with an explicit stack.
From Pairs
Build an object from an array of [key, value] pairs, the inverse of Object.entries.
Function.prototype.apply
Implement Function.prototype.apply, including array-like argument lists and argument validation.
Function.prototype.bind
Implement Function.prototype.bind with partial application and correct behaviour under new.
Function.prototype.call
Implement Function.prototype.call without using call, apply or bind.
Get
Safely read a nested value from an object by a dot/bracket path, falling back to a default.
getElementsByClassName
Find every descendant element that has all of the given class names by walking the DOM tree yourself.
getElementsByStyle
Find descendant elements whose computed value for a CSS property equals a given value, normalising values like red vs #f00.
getElementsByTagName
Return every descendant element with a given tag name (or all of them for "*") by traversing the DOM tree.
Group By
Group the elements of an array into arrays keyed by the result of an iteratee.
Has
Check whether an object has an own property at a nested path, even when the value is undefined.
HTML Serializer
Turn a plain-object element tree into pretty-printed, correctly escaped HTML with indentation and void elements.
In Range
Check whether a number lies in a half-open range, with an optional start and swapped bounds.
instanceof
Re-implement the instanceof operator by walking the prototype chain.
Intersection
Return the unique values that appear in every one of the given arrays.
Is Empty
Decide whether a value is empty: no length, no size, or no own enumerable keys depending on its type.
jQuery Class Manipulation
Build a tiny $ wrapper with chainable addClass, removeClass, toggleClass and hasClass that work on every matched element.
jQuery CSS
Implement a $(selector).css() getter/setter that handles camelCase names, objects, automatic px units and removal.
JSON.parse (Lite)
Write a recursive-descent parser for JSON text that matches JSON.parse and throws SyntaxError on invalid input.
JSON.stringify
Reimplement JSON.stringify: escaping, undefined and function handling, toJSON, wrapper objects, cycles and BigInt errors.
List Format
Format a list of names into a readable sentence with options for sorting, de-duplication and an "and N others" cutoff.
LRU Cache
Implement a fixed-capacity cache that evicts the least recently used entry, with O(1) get and set.
Make Counter
Use a closure to build independent counters that remember their own state between calls.
Map Async
Map over a list with an async callback, running every call in parallel and keeping the results in input order.
Map Async with Limit
Map over a list with an async callback while never running more than a given number of calls at once.
Max By
Return the element whose iteratee value is largest, skipping elements that produce no comparable value.
Mean
Compute the arithmetic mean of an array of numbers, returning NaN for an empty array.
Memoize
Cache a function's results by argument so repeated calls with the same input skip the work.
Memoize II (multiple arguments)
Memoize a function of any number of arguments with a collision-free cache keyed on every argument.
Middlewares
Compose async middleware functions into one onion-style pipeline where each step can run code before and after next().
Min By
Return the element whose iteratee value is smallest, skipping elements that produce no comparable value.
new Operator
Re-implement the new operator: create the object, link the prototype, run the constructor.
Number of Arguments
Return how many arguments a function was called with, and explain arguments vs rest vs Function.length.
Object.create
Implement Object.create, including null prototypes and property descriptors.
Observable
Build a minimal Observable with subscribe, unsubscribe, teardown, of/from creators and pipeable map and filter operators.
Omit
Create a shallow copy of an object without the listed keys.
Once
Wrap a function so that it runs at most once and later calls return the first result.
Partial
Pre-fill some of a function's arguments, with placeholders for positions supplied later.
Pick
Create a new object containing only the listed keys of a source object.
Pipe
Chain functions left to right so data flows through them in reading order.
Promise.all
Implement Promise.all: resolve with every result in order, or reject on the first failure.
Promise.allSettled
Implement Promise.allSettled: wait for every input and report each outcome in order.
Promise.any
Implement Promise.any: fulfill with the first success, or reject with an AggregateError.
Promise Implementation
Build a Promises/A+-style MyPromise with then, catch, finally, chaining and thenable adoption.
Promise Pool
Build a concurrency-limited task queue: tasks can be added at any time and at most N run at once.
Promise.race
Implement Promise.race: settle the same way as the first input to settle.
Promise.reject
Implement Promise.reject and explain why it never unwraps promises or thenables.
Promise.resolve
Implement Promise.resolve, including promise pass-through and thenable adoption.
Promise Timeout
Wrap a promise so it rejects with a TimeoutError if it doesn't settle in time, without leaking timers.
Promise.withResolvers
Implement Promise.withResolvers to create a promise you can settle from outside its executor.
Promisify
Convert a Node-style callback function into one that returns a promise.
Promisify II
Extend promisify with a custom-implementation symbol, like Node's util.promisify.custom.
Pub/Sub Store (Mini Redux)
Implement createStore with getState, dispatch and subscribe: the core of Redux in about 50 lines.
Range
Generate an array of numbers from start up to, but not including, end with an optional step.
Range Right
Generate the same numbers as range(start, end, step) but in descending order of generation.
Retry with Backoff
Retry a failing async operation with exponential backoff and a predicate that decides which errors are worth retrying.
Run Async Tasks in Series
Run a list of async functions one after another, passing each result to the next and stopping at the first failure.
Set
Write a value at a nested path, creating missing objects and arrays along the way.
setInterval with setTimeout
Re-implement setInterval and clearInterval using only chained setTimeout calls.
Signals (Fine-Grained Reactivity)
Implement createSignal, createEffect, createMemo, batch and untrack with automatic dependency tracking and glitch-free updates.
Size
Return the size of a collection: length for arrays and strings, size for Map and Set, key count for objects.
Sleep
Write a promise-based sleep(ms) and explain why it pauses an async function but not the thread.
Spreadsheet Evaluator
Build a spreadsheet engine: parse cell formulas, evaluate references and ranges, recompute dependents on change and detect cycles.
Squash Object
Flatten a nested object into a single level whose keys are dot-separated paths.
String Repeat and Pad
Implement repeat, padStart and padEnd without the built-in string methods, matching their edge-case behaviour.
Table of Contents
Build a nested table of contents from the h1–h6 headings in a document, generating unique anchor ids and rendering it as nested lists.
Template Engine
Build a {{ }} interpolation engine with dotted paths, HTML escaping, raw {{{ }}} output, filters and a compile step.
Text Search Highlight
Wrap every case-insensitive match of the query words in <b> tags, merging overlapping and adjacent matches.
Throttle
Limit a function to at most one call per wait window, with leading and trailing calls.
Type Utilities
Write reliable checks for JavaScript's primitive types, including the null and boxed-value traps.
Type Utilities II
Write type checks for non-primitive values: arrays, functions, objects and plain objects.
Undo/Redo History
Implement an undoable value with past and future stacks, redo invalidation, no-op detection and a bounded history size.
Union By
Merge several arrays into one list of unique elements, where uniqueness is decided by an iteratee.
Unique Array
Remove duplicate values from an array while keeping the first occurrence of each, in order.
Query String Parse and Stringify
Parse a URL query string into an object (with repeated keys as arrays) and serialise it back, handling encoding, + as space and malformed input.