Code Explainers

Code explainers tagged #generics

typescript
type Operator = "=" | "!=" | ">" | "<" | ">=" | "<=" | "LIKE";
 
type Row = Record<string, unknown>;
 

A type-safe SQL query builder in TypeScript

builder pattern generics method chaining
Intermediate 8 steps
rust
use std::env;
use std::time::Duration;
 
#[derive(Debug, Clone)]

Loading typed config from environment variables in Rust

configuration error-handling generics
Intermediate 7 steps
typescript
type AsyncFn<A extends unknown[], R> = (...args: A) => Promise<R>;
 
interface MemoizeOptions<A extends unknown[]> {
  keyFn?: (...args: A) => string;

Memoizing async functions with TTL in TypeScript

memoization generics promises
Advanced 8 steps
rust
use std::time::Duration;
use tokio::time::sleep;
 
#[derive(Debug)]

Async retry with exponential backoff in Rust

retry exponential-backoff async
Intermediate 8 steps
typescript
interface PollOptions<T> {
  intervalMs?: number;
  timeoutMs?: number;
  signal?: AbortSignal;

A cancellable polling helper in TypeScript

polling async-await abortsignal
Intermediate 9 steps
rust
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
 

Recursive file search by extension in Rust

recursion filesystem error-handling
Intermediate 8 steps
typescript
type Ok<T> = { ok: true; value: T };
type Err<E> = { ok: false; error: E };
export type Result<T, E> = Ok<T> | Err<E>;
 

A Result type for typed error handling

discriminated-union error-handling type-guards
Intermediate 8 steps
java
public final class RetryExecutor {
 
    private final int maxAttempts;
    private final Duration initialDelay;

Exponential backoff retry in Java

retry exponential-backoff jitter
Intermediate 8 steps
rust
use std::collections::BinaryHeap;
use std::cmp::Reverse;
 
pub fn top_k<T: Ord + Clone>(items: &[T], k: usize) -> Vec<T> {

Top-K selection with a bounded min-heap in Rust

heap top-k generics
Intermediate 8 steps
typescript
interface Page<T> {
  items: T[];
  nextCursor: string | null;
}

Streaming cursor pagination with async generators

async-generators pagination generics
Intermediate 8 steps
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
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
typescript
interface Order {
  id: number;
  customerId: string;
  total: number;

A type-safe groupBy in TypeScript

generics reduce type-inference
Intermediate 6 steps
go
package cache
 
import (
	"container/list"

Building a generic LRU cache in Go

lru-cache generics linked-list
Intermediate 8 steps
rust
use std::collections::HashMap;
 
pub struct Memoizer<K, V, F> {
    cache: HashMap<K, V>,

A generic memoizer in Rust

memoization generics caching
Intermediate 6 steps
typescript
function throttle<T extends (...args: any[]) => void>(
  fn: T,
  limit: number
): (...args: Parameters<T>) => void {

Building a trailing-edge throttle in TypeScript

throttling closures generics
Intermediate 7 steps
typescript
interface TokenBucketOptions {
  capacity: number;
  refillPerSecond: number;
}

How a token bucket rate limiter works

rate-limiting token-bucket lazy-evaluation
Intermediate 7 steps