Snippets
Snippets
Short code snippets and runnable notes, organized for quick reuse.
Snippet Tags- SHA256 Synchronous Implementation (Without WebCrypto API)
A pure JavaScript SHA256 implementation without using the WebCrypto API. For environments where the crypto object is unavailable, such as some Web Workers implementations.
- Splitting Text with TransformStream
A TypeScript example using ReadableStream and TransformStream to split long text into chunks of specified size.
- Merging Uint8Arrays
A TypeScript function to merge multiple Uint8Arrays into one. Useful for combining binary data.
- How to Use CSS href Attribute Selectors
A CSS snippet using attribute selectors on the href attribute of anchor elements, including prefix match, suffix match, and substring match.
- File System API Permission Check
Function to check and request permissions for browser File System API. Supports both read-only and read-write modes.
- TypeScript Array Utilities
Collection of type-safe utility functions for common array operations in TypeScript development. Empty array generation, chunking, null filtering, and shuffling.
- React useSelection Hook
Custom React hook for managing multi-item selection state. Type-safe handling of select all, partial selection, and individual selection.
- Batch Convert Images to AVIF with avifenc
A Bash snippet that recursively scans jpg/jpeg/png files and converts them to .avif using avifenc.
- Dynamic Import Caching
Lightweight TypeScript implementation for caching dynamic imports. Handle multiple imports to the same path with a single Promise.
- Display Storage Capacity in Finder
Toggle storage capacity display in macOS Finder with a keyboard shortcut.
- Node.js File Check
Promise-based function to check if a path is a file in Node.js. Returns false on error.
- TypeScript p-limit Implementation
TypeScript reimplementation of p-limit for controlling Promise concurrency. Achieve concurrency control without adding dependencies.
- TypeScript yocto-queue Implementation
TypeScript reimplementation of lightweight queue yocto-queue. Provides basic operations: enqueue, dequeue, iterator.
- Build-time Message ID Hash Store
A TypeScript function that hashes and shortens message IDs and contexts at build time. Useful when a target platform restricts allowed translation keys.
- Bulk Import with Fallback from Pairwise COPY to Individual Inserts
First attempt bulk import for large relational data, then fall back to individual inserts for rows that violate schema constraints. Balances speed and success rate.
- Cache-First, Live-Fetch Orchestration Pattern
Orchestration combining a fast path from cache and a slow path from remote. Measures cache hit/miss, fetch latency, and final outcome as metrics, delegating side effects outward.
- Clone a Native UI Element to Inherit Styles
A lightweight pattern that maintains visual consistency by cloning existing host app buttons with cloneNode, then replacing only the icon and text. No need to fight obfuscated CSS.
- Idempotent DOM Observer Setup via dataset
A simple pattern using data attributes to prevent duplicate MutationObserver registrations. No global registry needed, highly portable.
- Entity-Embedded Cooldown Warning Suppression
A pattern that embeds repeated warning suppression logic within the quota entity itself. Properly controls frequent warnings like rate limit notices and billing alerts.
- Memory Size of Go Data Types
A comprehensive list of memory sizes for each Go data type and practical tips for memory-efficient coding.
- Layered DOM Observation Strategy
A pattern for progressively switching to narrower observers once the app is ready. Broadly reusable in SPA content scripts and third-party DOM integrations.
- Property Extractor Helper Function
Generate a function that extracts only specified properties from an object. Consolidate type-safe property extraction into one line for nested mapBy and array transformations.
- Two-Phase Repository Walk with Byte Budget
Split processing into path/size scan → structure analysis → read only needed chunks → parse to make memory limits controllable even for large repositories.
- Worker Pool with Sub-batches and Per-sub-batch Timeout
A pattern that splits large datasets into small sub-batches sent to workers, reducing memory pressure while setting timeouts per batch for early anomaly detection.
- Biome npm-scripts Configuration
Common patterns for npm-scripts when setting up Biome. Run lint and format using the check command.
- Image Extension Regex
JavaScript/TypeScript regex pattern to detect image formats from filenames. Supports png, webp, jpg, jpeg, avif, gif.
- Lazy-Initialized Object
A TypeScript pattern using getters to generate values only on first access. Lightweight lazy evaluation compared to memory caching.
- Saving man Pages to Text Files
How to save man command output to a file on macOS/Linux. Use col -b to remove control characters and create readable text.
- Download tarball from npm
How to download npm package tarballs (.tgz) using npm pack and pnpm info. Methods for npm, yarn, and pnpm.
- Time-Based Semantic Version Generation
A TypeScript function that automatically generates version numbers from build timestamps. Useful when version limits exist, such as in Chrome extensions.
- TypeScript Non-null Assertion
TypeScript type guard functions to eliminate undefined and null. Ensures both runtime errors and type safety.
- Implementing a Lightweight Result Type in TypeScript
An error handling pattern without try-catch. Type-safe error handling with a Result type that separates data and error.
- Uint32Array Helper Functions
A concise TypeScript wrapper for `new Uint32Array` calls. Supports all constructor overloads with type-safe overload definitions.
- Uint8Array Helper Functions
A TypeScript wrapper to simplify new Uint8Array calls. Supports arrays, ArrayBuffers, and length-based initialization patterns.
- Polyfill for crypto.randomUUID
A polyfill implementation of the crypto.randomUUID function. While all browsers now support this, it serves as a useful reference for understanding how UUID v4 works.
- Generate parameter.json from a CloudFormation Template
A snippet that combines aws cloudformation validate-template and jq to automatically generate a parameters.json with environment variable overrides.
- gzip Command Cheat Sheet
A snippet covering the basic usage of the gzip command, including file compression, decompression, and option flags.
hsb.horse