Code Explainers

Code explainers tagged #generics

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
typescript
export function chunk<T>(items: readonly T[], size: number): T[][] {
  if (size <= 0 || !Number.isInteger(size)) {
    throw new RangeError(`chunk size must be a positive integer, got ${size}`);
  }

Splitting work into sequential batches in TypeScript

generics async-await batching
Intermediate 5 steps
rust
use std::fs::File;
use std::io::{self, BufRead, BufReader};
use std::path::Path;
 

Buffered log scanning in Rust

buffered-io error-handling streaming
Intermediate 9 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
java
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;

Three ways to deduplicate a list by key in Java

streams deduplication collectors
Intermediate 6 steps
typescript
// A module-scoped Singleton: the single instance lives in this module's
// closure and is never exposed directly.
 
interface AppConfig {

A module-scoped Singleton in TypeScript

singleton generics encapsulation
Intermediate 7 steps
typescript
interface RetryOptions {
  retries?: number;
  baseDelayMs?: number;
  maxDelayMs?: number;

Retrying async tasks with exponential backoff

retry exponential-backoff async
Intermediate 8 steps
rust
use std::thread;
 
pub fn parallel_map_reduce<T, M, R, F, G, H>(
    data: &[T],

A parallel map-reduce with scoped threads

concurrency scoped-threads map-reduce
Advanced 8 steps
typescript
type NestedArray<T> = Array<T | NestedArray<T>>;
 
function flatten<T>(input: NestedArray<T>): T[] {
  const result: T[] = [];

Recursively flattening nested arrays in TypeScript

recursion recursive-types generics
Intermediate 7 steps
typescript
class LRUCache<K, V> {
  private readonly capacity: number;
  private readonly map: Map<K, V>;
 

Building an LRU cache on a JS Map

caching data-structures generics
Intermediate 8 steps