Code Explainers

Browse the library

java
import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;

A safe recurring heartbeat scheduler in Java

concurrency scheduling thread-safety
Intermediate 6 steps
javascript
function initLazyLoad(root = document) {
  const images = root.querySelectorAll('img[data-src]');
 
  if (!('IntersectionObserver' in window)) {

How lazy image loading works

lazy-loading intersectionobserver progressive-enhancement
Intermediate 8 steps
go
package main
 
import (
	"bufio"

Counting matching lines in Go with bufio

file-io buffered-scanning error-handling
Intermediate 4 steps
ruby
class EventEmitter
  def initialize
    @listeners = Hash.new { |hash, key| hash[key] = [] }
  end

Building an EventEmitter in Ruby

pub-sub closures callbacks
Intermediate 7 steps
python
from flask import Blueprint, render_template, request, abort
from sqlalchemy import select
 
from .models import Article

Paginating articles in a Flask Blueprint

pagination blueprints input-validation
Intermediate 6 steps
javascript
import { notFound } from 'next/navigation';
 
const PER_PAGE = 24;
const SORT_OPTIONS = ['relevance', 'price-asc', 'price-desc', 'newest'];

Parsing search params in a Next.js page

input-validation query-params pagination
Intermediate 10 steps
go
package collection
 
func Deduplicate[T comparable](items []T) []T {
	seen := make(map[T]struct{}, len(items))

Generic deduplication in Go

generics deduplication maps
Intermediate 5 steps
ruby
require 'optparse'
require 'ostruct'
 
def parse_options(argv)

Parsing CLI options with OptionParser

cli argument-parsing validation
Intermediate 8 steps
rust
use axum::{extract::Form, http::StatusCode, response::{IntoResponse, Response}, Json};
use serde::Deserialize;
use serde_json::json;
use std::collections::HashMap;

Validating a signup form in Axum

form-validation deserialization error-handling
Intermediate 8 steps
java
package com.example.monitoring;
 
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;

A custom replica health check in Spring

health-check actuator monitoring
Intermediate 7 steps
javascript
import { NextResponse } from 'next/server';
import Stripe from 'stripe';
import { headers } from 'next/headers';
 

Handling Stripe webhooks in Next.js

webhooks signature verification payment processing
Intermediate 7 steps
go
func StreamMetrics(c *gin.Context) {
	clientGone := c.Request.Context().Done()
	ticker := time.NewTicker(time.Second)
	defer ticker.Stop()

Streaming server-sent events in Gin

server-sent-events streaming channels
Intermediate 7 steps
php
<?php
 
namespace App\Http\Middleware;
 

Enforcing a JSON Accept header in Laravel

middleware content-negotiation http-headers
Beginner 5 steps
python
from fastapi import APIRouter, Depends, Query
from pydantic import BaseModel
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession

How a paginated list endpoint works in FastAPI

pagination dependency-injection async-orm
Intermediate 8 steps
javascript
const fs = require('fs');
const path = require('path');
 
router.get('/downloads/:name', (req, res, next) => {

Streaming file downloads in Express

streaming backpressure file-download
Advanced 9 steps
ruby
module Retryable
  class RetriesExhausted < StandardError; end
 
  RETRYABLE_ERRORS = [

Exponential backoff retries in Ruby

retry-logic exponential-backoff error-handling
Intermediate 7 steps
typescript
import { IsEmail, IsEnum, IsInt, IsOptional, IsString, Length, Max, Min } from 'class-validator';
import { Type } from 'class-transformer';
import { Body, Controller, Post } from '@nestjs/common';
 

How DTO validation works in NestJS

validation data-transfer-objects decorators
Intermediate 8 steps
go
package worker
 
import (
	"fmt"

A graceful worker pool in Go

concurrency goroutines channels
Intermediate 7 steps