Code Explainers

Browse the library

javascript
function getCityName(user) {
  return user?.address?.city ?? "Unknown city";
}
 

Optional chaining and nullish coalescing in JS

optional-chaining nullish-coalescing defensive-coding
Intermediate 5 steps
typescript
class LRUCache<K, V> {
  private readonly capacity: number;
  private readonly map: Map<K, V>;
 

Building an LRU cache on a JS Map

caching data-structures generics
Intermediate 8 steps
ruby
module FileResource
  # Opens a file, yields it to the caller, and guarantees the
  # handle is closed even if the block raises an exception.
  def self.open(path, mode = "r")

Guaranteeing cleanup with begin/ensure in Ruby

resource-management exception-safety blocks
Intermediate 8 steps
rust
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
 

A worker thread driven by Rust channels

concurrency message-passing channels
Intermediate 8 steps
java
public final class Quicksort {
 
    private Quicksort() {
    }

Quicksort with Lomuto partitioning in Java

recursion divide-and-conquer in-place
Intermediate 7 steps
go
package geometry
 
import "fmt"
 

Implementing fmt.Stringer in Go

interfaces stringer composition
Beginner 5 steps
javascript
function throttle(fn, wait) {
  let lastCall = 0;
  let timeoutId = null;
  let lastArgs = null;

Building a leading-and-trailing throttle

closures rate-limiting timers
Advanced 6 steps
typescript
type Split<S extends string, D extends string> =
  S extends `${infer Head}${D}${infer Tail}`
    ? [Head, ...Split<Tail, D>]
    : [S];

Type-level string parsing in TypeScript

template literal types conditional types recursive types
Advanced 8 steps
javascript
async function* fetchPages(baseUrl, maxPages) {
  let page = 1;
  while (page <= maxPages) {
    const data = await mockFetch(`${baseUrl}?page=${page}`);

Paginated APIs with async generators

async-iterators generators pagination
Advanced 7 steps
javascript
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
 

Building a Promise from scratch

promises state-machine microtasks
Advanced 10 steps
javascript
function delegate(root, eventType, selector, handler) {
  const listener = (event) => {
    let node = event.target;
    while (node && node !== root) {

Event delegation with a clean teardown

event-delegation dom closures
Intermediate 8 steps