Code Explainers

Javascript code explainers

javascript
function parseHexColor(hex) {
  const cleaned = hex.trim().replace(/^#/, '');
 
  const expand = (short) =>

Parsing hex colors into RGBA channels

parsing bitwise regex
Intermediate 7 steps
javascript
import { useReducer, useCallback } from 'react';
 
function historyReducer(state, action) {
  const { past, present, future } = state;

Undo/redo form state with a React reducer

undo-redo reducer immutability
Intermediate 10 steps
javascript
import { NextResponse } from 'next/server';
import { db } from '@/lib/db';
 
function csvCell(value) {

Streaming a CSV export in a Next.js route

streaming csv readablestream
Advanced 9 steps
javascript
class MovingAverage {
  constructor(windowSize) {
    if (!Number.isInteger(windowSize) || windowSize <= 0) {
      throw new RangeError('windowSize must be a positive integer');

A rolling average over a fixed window

circular-buffer streaming async-generators
Intermediate 7 steps
javascript
const { Pool } = require('pg');
 
const pool = new Pool({
  connectionString: process.env.DATABASE_URL,

Per-request Postgres connections in Express

connection-pooling middleware transactions
Intermediate 8 steps
javascript
const express = require('express');
const router = express.Router();
const db = require('../db');
 

Building a paginated orders page in Express

pagination routing sql-queries
Intermediate 7 steps
javascript
import { Suspense } from 'react';
import { searchProducts } from '@/lib/products';
import SearchInput from './search-input';
 

Streaming search results in a Next.js Server Component

server-components suspense streaming
Intermediate 8 steps
javascript
import { useState } from 'react';
 
function StarRating({ value = 0, max = 5, onChange, size = 24 }) {
  const [hovered, setHovered] = useState(null);

Building an accessible star rating in React

controlled-component accessibility state-management
Intermediate 8 steps
javascript
import { notFound } from 'next/navigation'
import { Suspense } from 'react'
import { getPostBySlug, getRelatedPosts } from '@/lib/posts'
import { RelatedPosts } from '@/components/related-posts'

Building a dynamic blog post page in Next.js

server-components dynamic-routing metadata
Intermediate 8 steps
javascript
const express = require('express');
const { createProxyMiddleware, fixRequestBody } = require('http-proxy-middleware');
 
const router = express.Router();

Building an API gateway proxy in Express

reverse-proxy middleware api-gateway
Intermediate 6 steps
javascript
import { useCallback, useRef, useState } from 'react';
 
export function ColorPicker({ initialColor = '#3b82f6', onCommit }) {
  const [committed, setCommitted] = useState(initialColor);

A validated color picker in React

uncontrolled-inputs refs validation
Intermediate 7 steps
javascript
import { useEffect, useRef } from 'react';
 
export function useRefetchOnFocus(refetch, { staleTime = 30_000 } = {}) {
  const lastFetchedAt = useRef(Date.now());

A React hook that refetches on tab focus

custom-hooks refs event-listeners
Intermediate 6 steps
javascript
import { NextResponse } from 'next/server';
import { Redis } from '@upstash/redis';
 
const redis = Redis.fromEnv();

Sliding-window rate limiting in a Next.js route

rate-limiting redis sorted-set
Advanced 8 steps
javascript
const MAX_FILE_SIZE = 5 * 1024 * 1024;
 
const ALLOWED_TYPES = {
  'image/jpeg': ['jpg', 'jpeg'],

Validating file uploads by content, not just claims

input-validation security magic-bytes
Intermediate 7 steps
javascript
function zip(keys, values) {
  if (keys.length !== values.length) {
    throw new RangeError('zip expects arrays of equal length');
  }

Three ways to zip arrays in JavaScript

arrays higher-order-functions pairing
Intermediate 6 steps
javascript
import { useCallback, useEffect, useState } from 'react';
 
export function useLocalStorage(key, initialValue) {
  const readValue = useCallback(() => {

How a useLocalStorage hook syncs state in React

custom hooks localstorage state persistence
Intermediate 8 steps
javascript
import { useState } from 'react';
 
export function ReorderableList({ initialItems }) {
  const [items, setItems] = useState(initialItems);

Drag-to-reorder lists in React

drag-and-drop state-management immutable-updates
Intermediate 8 steps
javascript
import { unstable_cache, revalidateTag } from 'next/cache'
import { db } from '@/lib/db'
 
export const getDashboardStats = unstable_cache(

Caching dashboard stats in Next.js

caching cache-invalidation tag-based-revalidation
Intermediate 8 steps