Code Explainers

Intermediate code explainers

rust
use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
 
#[derive(Debug)]

Parsing an HTTP Range header in Rust

http-range parsing file-io
Intermediate 10 steps
java
import java.util.HashSet;
import java.util.Set;
 
public final class CollectionDiff<T> {

Diffing two collections with set operations

set-operations immutability generics
Intermediate 8 steps
ruby
class Order < ApplicationRecord
  belongs_to :customer
  has_many :line_items
  has_many :products, through: :line_items

How scopes compose in a Rails model

scopes activerecord subqueries
Intermediate 7 steps
go
package handlers
 
import (
	"encoding/base64"

Cursor pagination in a Gin handler

pagination cursor rest-api
Intermediate 8 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
python
from django.core.cache import cache
from django.core.cache.utils import make_template_fragment_key
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver

Busting template fragment caches in Django

caching signals cache-invalidation
Intermediate 4 steps
go
package metrics
 
import (
	"sync"

A thread-safe sliding-window average in Go

concurrency sliding-window running-average
Intermediate 8 steps
java
public record AppConfig(
        String host,
        int port,
        String databaseUrl,

Loading typed config from env vars in Java

records configuration environment-variables
Intermediate 6 steps
ruby
require "charlock_holmes"
 
class TextFileNormalizer
  DEFAULT_CONFIDENCE = 60

Normalizing text files to clean UTF-8 in Ruby

encoding text-processing file-io
Intermediate 8 steps
rust
use rand::distributions::{Alphanumeric, DistString};
use rand::rngs::OsRng;
 
#[derive(Debug, Clone, PartialEq, Eq)]

A newtype wrapper for API tokens in Rust

newtype-pattern randomness encapsulation
Intermediate 6 steps
python
from datetime import datetime, timezone
 
_INTERVALS = (
    ("year", 60 * 60 * 24 * 365),

Building a human-friendly time_ago helper

datetime timezones formatting
Intermediate 5 steps
php
<?php
 
namespace App\Validation;
 

Building a reusable address form validator in PHP

validation error-accumulation regex
Intermediate 9 steps
typescript
export function isValidCardNumber(input: string): boolean {
  const digits = input.replace(/[\s-]/g, "");
 
  if (!/^\d{12,19}$/.test(digits)) {

Validating card numbers with the Luhn check

luhn-algorithm checksum input-validation
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
java
public class RequestThrottler {
 
    private final Semaphore permits;
    private final long acquireTimeoutMillis;

Bounding concurrency with a Semaphore in Java

concurrency semaphore rate-limiting
Intermediate 6 steps
ruby
require 'date'
require 'set'
 
class BusinessDayCalculator

Counting business days in Ruby

dates sets ranges
Intermediate 8 steps
rust
pub fn normalize_path(input: &str) -> String {
    let is_absolute = input.starts_with('/');
    let has_trailing_slash = input.len() > 1 && input.ends_with('/');
    let mut stack: Vec<&str> = Vec::new();

Normalizing filesystem paths in Rust

string-processing stack path-manipulation
Intermediate 8 steps
python
import time
import threading
from flask import Flask, request, jsonify, g
 

A token-bucket rate limiter in Flask

rate-limiting token-bucket middleware
Intermediate 7 steps