Code Explainers

Browse the library

typescript
type RequestState<T, E = string> =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; data: T; fetchedAt: number }

Modeling request state with discriminated unions

discriminated-unions exhaustiveness-checking state-machine
Intermediate 8 steps
java
public Map<Long, List<Order>> ordersByCustomer(List<Order> orders) {
    return orders.stream()
            .collect(Collectors.groupingBy(Order::getCustomerId));
}

Grouping streams with Java Collectors

streams grouping collectors
Intermediate 5 steps
php
<?php
 
namespace App\Http\Controllers;
 

Building a filtered product index in Laravel

query-builder validation conditional-queries
Intermediate 9 steps
ruby
class MetricSeries
  def initialize(readings, window: 5)
    @readings = readings
    @window = window

Rolling averages with each_cons in Ruby

sliding-window enumerable data-smoothing
Intermediate 7 steps
javascript
async function mapWithConcurrency(items, limit, worker) {
  const results = new Array(items.length);
  let nextIndex = 0;
 

Bounded-concurrency async map in JavaScript

concurrency async-await promises
Intermediate 7 steps
go
package config
 
import (
	"encoding/json"

Parsing untyped JSON config in Go

json parsing type assertions error handling
Intermediate 7 steps
rust
use axum::{
    body::Bytes,
    extract::State,
    http::StatusCode,

Handling raw byte uploads in Axum

extractors shared-state request-limits
Intermediate 7 steps
typescript
import {
  Directive,
  Input,
  TemplateRef,

Building a structural *appUnless directive in Angular

structural-directive template-rendering dependency-injection
Intermediate 8 steps
java
@Service
public class PaymentGatewayClient {
 
    private static final Logger log = LoggerFactory.getLogger(PaymentGatewayClient.class);

Resilient payment calls with Spring Retry

retry backoff fault-tolerance
Intermediate 7 steps
php
<?php
 
namespace App\Models\Scopes;
 

How a tenant global scope works in Laravel

multi-tenancy global-scope query-builder
Intermediate 5 steps
javascript
const RETRIABLE_STATUS = new Set([408, 429, 500, 502, 503, 504]);
 
function sleep(ms, signal) {
  return new Promise((resolve, reject) => {

Retrying fetch with exponential backoff

retry exponential-backoff abort-signal
Advanced 8 steps
go
package main
 
import (
	"net/http"

How route groups nest in Gin

routing middleware api versioning
Intermediate 6 steps
rust
use axum::{
    extract::{Query, State},
    http::StatusCode,
    Json,

Paginated, filtered product listing in Axum

pagination query-parameters sql-filtering
Intermediate 8 steps
python
from operator import itemgetter
 
 
def sort_employees(employees):

Multi-key sorting patterns in Python

sorting tuple-keys itemgetter
Intermediate 5 steps
typescript
type EventMap = Record<string, unknown[]>;
 
type Listener<Args extends unknown[]> = (...args: Args) => void;
 

A type-safe event emitter in TypeScript

generics mapped-types event-emitter
Advanced 8 steps
java
public final class Debouncer<T> {
 
    private final ScheduledExecutorService scheduler =
            Executors.newSingleThreadScheduledExecutor(runnable -> {

How a debouncer collapses bursts in Java

debounce concurrency scheduling
Intermediate 9 steps
javascript
const express = require('express');
const Stripe = require('stripe');
 
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);

Verifying Stripe webhooks in Express

webhooks signature-verification raw-body
Intermediate 7 steps
ruby
class Api::V1::ArticlesController < Api::V1::BaseController
  def index
    articles = Article
      .published

Building a JSON:API endpoint in Rails

serialization eager-loading pagination
Intermediate 7 steps