Code Explainers

Browse the library

javascript
function initScrollSpy() {
  const links = Array.from(document.querySelectorAll('.nav a[href^="#"]'));
  const sections = links
    .map((link) => document.querySelector(link.getAttribute('href')))

Building a scroll spy with IntersectionObserver

intersectionobserver dom event-driven
Intermediate 7 steps
rust
#[derive(Debug, Default)]
pub struct RequestBuilder {
    url: String,
    method: String,

The builder pattern in Rust

builder-pattern method-chaining ergonomic-api
Intermediate 8 steps
java
package com.example.lb;
 
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

A thread-safe round-robin load balancer in Java

concurrency load-balancing round-robin
Intermediate 9 steps
python
from typing import Callable, Dict, Type
 
 
class PluginRegistry:

A decorator-based plugin registry in Python

decorators registry pattern factory
Intermediate 9 steps
typescript
import { Component, inject, effect } from '@angular/core';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { toSignal } from '@angular/core/rxjs-interop';

Debounced search that syncs to the URL in Angular

signals reactive-forms debouncing
Advanced 8 steps
ruby
namespace :counter_cache do
  desc "Recalculate comments_count for posts after a backfill"
  task warm_post_comments: :environment do
    scope = Post.where(comments_count: nil).or(Post.where("comments_count < 0"))

Backfilling counter caches in a Rake task in Rails

counter-cache batching rake-tasks
Intermediate 6 steps
go
package humanize
 
import (
	"fmt"

Parsing human-readable byte sizes in Go

parsing regex lookup-table
Intermediate 8 steps
ruby
class ToastBroadcaster
  include ActionView::RecordIdentifier
 
  def self.broadcast_to(user, message:, type: :notice)

How Turbo Stream toasts broadcast in Rails

turbo-streams service-object real-time
Intermediate 6 steps
typescript
import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { ValidationPipe } from '@nestjs/common';
import { ApiProperty } from '@nestjs/swagger';

Wiring validation and Swagger docs in NestJS

validation openapi decorators
Intermediate 8 steps
python
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, status
from pydantic import BaseModel, EmailStr
from sqlalchemy.orm import Session
 

Building a signup endpoint in FastAPI

dependency-injection request-validation background-tasks
Intermediate 8 steps
javascript
const ROLE_PERMISSIONS = {
  admin: ['users:read', 'users:write', 'billing:read', 'billing:write'],
  manager: ['users:read', 'billing:read'],
  member: ['users:read'],

Role-based permissions middleware in Express

authorization middleware rbac
Intermediate 9 steps
rust
use axum::{extract::{Path, State}, http::StatusCode, Json};
use dashmap::DashMap;
use serde::Serialize;
use std::sync::Arc;

Request coalescing in an Axum handler

caching concurrency request-coalescing
Advanced 8 steps
java
public interface GitHubClient {
 
    @GetExchange("/users/{username}")
    GitHubUser getUser(@PathVariable String username);

Declarative HTTP clients in Spring

http-client declarative-api proxy
Intermediate 8 steps
php
<?php
 
namespace App\Console\Commands;
 

Releasing stale document locks in Laravel

artisan-command transactions row-locking
Intermediate 6 steps
ruby
class TemplateInterpolator
  PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/
 
  def initialize(strict: false)

Interpolating templates with dotted keys in Ruby

regex string-interpolation hash-traversal
Intermediate 6 steps
typescript
import { Component, Input } from '@angular/core';
 
interface Order {
  id: string;

How Angular ICU plurals localize an order summary

i18n pluralization standalone-component
Intermediate 8 steps
python
from django import forms
from django.utils import timezone
 
from .models import Reservation

Multi-field validation in a Django ModelForm

form validation cross-field validation modelform
Intermediate 7 steps
javascript
function attachThousandSeparators(input, { locale = 'en-US' } = {}) {
  const formatter = new Intl.NumberFormat(locale);
  const groupSep = formatter.format(11111).replace(/\d/g, '')[0] || ',';
  const decimalSep = formatter.format(1.1).replace(/\d/g, '')[0] || '.';

Live thousand separators without losing the caret

dom intl caret-preservation
Advanced 8 steps