Code Explainers

Code explainers tagged #generics

rust
use axum::{
    async_trait,
    extract::{rejection::JsonRejection, FromRequest, Request},
    http::StatusCode,

A validated JSON extractor in Axum

extractors validation error-handling
Intermediate 8 steps
typescript
import { Pipe, PipeTransform } from '@angular/core';
 
@Pipe({
  name: 'chunk',

A memoized chunk pipe in Angular

memoization weakmap pure-pipes
Intermediate 7 steps
rust
use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};
use std::thread;

Polling a directory for new files in Rust

polling filesystem callbacks
Intermediate 6 steps
typescript
type CacheEntry<V> = {
  value: V;
  computedAt: number;
};

A TTL cache keyed by object identity

caching weakmap generics
Intermediate 8 steps
typescript
import { useCallback, useRef, useState } from "react";
 
interface VirtualListProps<T> {
  items: T[];

How a virtualized list renders in React

virtualization windowing performance
Advanced 7 steps
rust
use rand::Rng;
 
#[derive(Debug)]
pub struct WeightedChoice<T> {

Weighted random sampling in Rust

weighted-sampling generics binary-search
Intermediate 7 steps
typescript
type RetryableRequest<T> = () => Promise<T>;
 
interface RetryOptions {
  maxAttempts?: number;

Retrying HTTP requests with backoff

retry exponential-backoff error-handling
Intermediate 8 steps
rust
use itertools::Itertools;
use std::cmp::Ordering;
 
#[derive(Debug, Clone)]

Merging sorted event streams with itertools

iterators merge deduplication
Intermediate 7 steps
typescript
import { Type, applyDecorators } from '@nestjs/common';
import {
  ApiExtraModels,
  ApiOkResponse,

A reusable paginated Swagger decorator in NestJS

decorators generics openapi
Intermediate 6 steps
rust
use axum::body::Bytes;
use axum::http::{header, HeaderValue, StatusCode};
use axum::response::{IntoResponse, Response};
use serde::Serialize;

Custom Axum responses with per-user ETags

etag trait-implementation generics
Intermediate 7 steps
typescript
type Middleware<TIn, TOut> = (ctx: TIn) => Promise<TOut> | TOut;
 
class Pipeline<TIn, TOut> {
  private constructor(private readonly run: Middleware<TIn, TOut>) {}

A type-safe async middleware pipeline

generics type-safety middleware
Advanced 9 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
rust
#[derive(Debug, Default)]
pub struct RequestBuilder {
    url: String,
    method: String,

The builder pattern in Rust

builder-pattern method-chaining ergonomic-api
Intermediate 8 steps
java
package com.example.lb;
 
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

A thread-safe round-robin load balancer in Java

concurrency load-balancing round-robin
Intermediate 9 steps
typescript
type CsvColumn<T> = {
  header: string;
  value: (row: T) => string | number | boolean | null | undefined;
};

Building a type-safe CSV writer in TypeScript

generics serialization escaping
Intermediate 7 steps
typescript
import { useCallback, useEffect, useRef, useState } from "react";
 
interface Page<T> {
  items: T[];

A cursor-based infinite scroll hook in React

custom-hooks pagination intersection-observer
Intermediate 9 steps
go
package batch
 
import "fmt"
 

Splitting a slice into batches in Go

generics slices error-handling
Intermediate 6 steps
java
public final class DeepCopier {
 
    private static final ObjectMapper MAPPER = new ObjectMapper()
            .registerModule(new JavaTimeModule())

Deep-copying objects via Jackson serialization

serialization deep-copy generics
Intermediate 7 steps