Gists
export function splitmix32(seed: number):
() => number /* [0, 1) */ {
let state = seed | 0;
return () => {
state |= 0;
state = state + 0x9e3779b9 | 0;
let t = state ^ state >>> 16;
t = Math.imul(t, 0x21f0aaad); Splitmix32: A Fast Seeded PRNG
A 32-bit seeded pseudorandom number generator derived from MurmurHash3's finalizer. Deterministic, fast, and good enough for simulations that need reproducibility — not cryptography.
type UnionToIntersection<U> =
(U extends unknown ? (arg: U) => void : never) extends (arg: infer I) => void
? I
: never
type Handlers =
| { onClick: () => void }
| { onKey: (key: string) => void } Union to Intersection
Merge a union of object types into a single composite type.
type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never }
type XOR<T, U> = (T & Without<U, T>) | (U & Without<T, U>)
type ById = { id: string }
type ByEmail = { email: string }
type Lookup = XOR<ById, ByEmail> XOR Types for Mutually Exclusive Options
Enforce exactly one of two shapes at compile time.
SPEED=1.15
INPUT="input.mp4"
OUTPUT="output.mp4"
ffmpeg -i "$INPUT" \
-filter_complex "[0:v]setpts=PTS/${SPEED}[v];[0:a]atempo=${SPEED}[a]" \
-map "[v]" -map "[a]" \
-c:v libx264 -preset fast -crf 22 \ Speed Up Video with ffmpeg
Speed up or slow down video and audio tracks together using ffmpeg, with configurable speed multiplier and high-quality H.264 re-encoding.
# Kill all running Docker containers, by sending
# them a SIGKILL signal.
docker ps -q \
| xargs docker kill Kill All Running Docker Containers
Stop every running container in one shot with docker kill and xargs.
function assertNever(value: never): never {
throw new Error('Unhandled case: ' + value)
}
type Event =
| { type: 'created'; id: string }
| { type: 'deleted'; id: string } assertNever for Exhaustive Switches
Fail fast when a union gains a new member.
declare const __brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [__brand]: B };
type UserId = Brand<string, "UserId">;
type PostId = Brand<string, "PostId">;
type Email = Brand<string, "Email">;
type PositiveInt = Brand<number, "PositiveInt">; Branded Types in TypeScript
Prevent accidental type aliasing and enforce domain constraints at compile time using branded types, factory functions, and assertion functions.
type DeepPartial<T> = T extends Function
? T
: T extends object
? { [K in keyof T]?: DeepPartial<T[K]> }
: T
type User = {
id: string DeepPartial for Patch Objects
Make every nested field optional for update payloads.
type DeepReadonly<T> = T extends Function
? T
: T extends object
? { readonly [K in keyof T]: DeepReadonly<T[K]> }
: T
type Config = {
api: { DeepReadonly for Configuration
Freeze nested objects at the type level.
type Exact<T, Shape extends T> = T & Record<Exclude<keyof Shape, keyof T>, never>
type User = {
id: string
email: string
}
function acceptUser<T extends User>(user: Exact<User, T>) { Exact Object Types
Reject excess properties in object literals without runtime checks.
type NonEmptyArray<T> = [T, ...T[]]
function assertNonEmpty<T>(value: T[]): asserts value is NonEmptyArray<T> {
if (value.length === 0) {
throw new Error('Expected at least one item')
}
} Non-Empty Arrays with Runtime Guard
Guarantee at least one element after a check.
type PickByValue<T, V> = {
[K in keyof T as T[K] extends V ? K : never]: T[K]
}
type Model = {
id: string
name: string
createdAt: Date PickByValue Utilities
Select keys by value type to build focused subsets.
import { defineConfig } from 'tsdown'
export default defineConfig({
entry: 'src/index.ts',
dts: true,
}) tsdown Basic Config
Minimal tsdown config for a library build.
import { defineConfig } from 'tsdown'
export default defineConfig([
{
entry: 'src/index.ts',
},
{
entry: 'src/cli.ts', tsdown Multi-Config Builds
Build multiple entry points with different settings.
pnpm dlx wrangler@latest init my-worker
# Non-interactive defaults
pnpm dlx wrangler@latest init my-worker -y Scaffold a New Cloudflare Worker
Initialize a Worker project with Wrangler.
pnpm dlx wrangler@latest secret put MY_SECRET Set Worker Secrets with Wrangler
Add encrypted secrets for a deployed Worker.
pnpm dlx wrangler@latest types Generate Worker Types
Create TypeScript types from your Wrangler configuration.
import { pipe } from "effect"
const result = pipe(
" Hello, World! ",
(s) => s.trim(),
(s) => s.toLowerCase(),
(s) => s.replace(/\s+/g, "-"),
(s) => s.replace(/[^a-z0-9-]/g, ""), Pipe and Flow Composition with Effect
Composing operations left-to-right using Effect's pipe and flow utilities for readable data transformations.
#[derive(Debug)]
enum ConnectionState {
Disconnected,
Connecting { attempt: u32 },
Connected { latency_ms: u64 },
Error { message: String },
} Exhaustive Pattern Matching in Rust
Using Rust's match expressions and enums to handle every variant at compile time — no missing cases allowed.
from pydantic import BaseModel, Field, field_validator
from datetime import datetime
class UserCreate(BaseModel):
name: str = Field(min_length=1, max_length=100)
email: str
age: int = Field(ge=0, le=150)
bio: str | None = None Dataclass Validation with Pydantic
Defining validated data models in Python using Pydantic — automatic parsing, coercion, and clear error messages.