0 day streak
Code library

Code worth reading.

Hand-picked snippets across TypeScript, Python, Rust, Go, and more — each one comes with a line-by-line breakdown so you can read it like the people who wrote it.

3495 snippets · 10 languages
▶ Start learning
JavaScript · ExpertSnippet

Thread-Safe Synchronization with Atomics

Atomics provides static methods for performing atomic operations on SharedArrayBuffer data. This is crucial for multi-threaded JavaScript (Web Workers) to prevent race conditions and synchronize memory access between threads.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
const buffer = new SharedArrayBuffer(1024);
const i32 = new Int32Array(buffer);
// In Worker A
Atomics.store(i32, 0, 123);
Atomics.notify(i32, 0, 1);
// In Worker B
const result = Atomics.wait(i32, 0, 0);
if (result === 'ok') {
console.log(Atomics.load(i32, 0));
}
Async & ConcurrencyPerformance
JavaScript · ExpertSnippet

Memory-Efficient Caching with WeakRef

WeakRef allows you to hold a weak reference to an object, meaning it doesn't prevent the object from being garbage collected. Combined with FinalizationRegistry, you can create caches that automatically clean up when memory is low without keeping objects alive indefinitely.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const cache = new Map();
const registry = new FinalizationRegistry(key => {
const ref = cache.get(key);
if (ref && !ref.deref()) cache.delete(key);
});
function getCachedData(key, factory) {
const ref = cache.get(key);
let data = ref?.deref();
if (!data) {
data = factory();
cache.set(key, new WeakRef(data));
registry.register(data, key);
}
return data;
}
PerformanceBest Practices
JavaScript · ExpertSnippet

Contextual Escaping via Tagged Templates

Tagged template literals allow you to parse template literals with a function. This is an expert pattern for implementing Domain Specific Languages (DSLs) or, as shown here, automatic security escaping to prevent XSS attacks.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
function safeHTML(strings, ...values) {
return strings.reduce((acc, str, i) => {
const value = String(values[i] || '');
const escaped = value.replace(/[&<>"']/g, m => ({
'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
}[m]));
return acc + str + escaped;
}, '');
}
const userSupplied = '<img src=x onerror=alert(1)>';
const html = safeHTML`<div>${userSupplied}</div>`;
SyntaxSecurity
JavaScript · ExpertSnippet

Structural Validation with Proxy Traps

The Proxy object allows you to create a wrapper for another object, intercepting fundamental operations like property assignment. By using the 'set' trap and 'Reflect' API, you can implement robust runtime type checking.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
const schema = { name: 'string', age: 'number' };
const handler = {
set(target, prop, value) {
if (schema[prop] && typeof value !== schema[prop]) {
throw new TypeError(`Invalid type for ${prop}`);
}
return Reflect.set(...arguments);
}
};
const user = new Proxy({}, handler);
user.name = 'Alice'; // Works
user.age = 'none'; // Throws TypeError
Design PatternsOOP
JavaScript · ExpertSnippet

Low-Level Binary Manipulation with DataView

DataView provides a low-level interface for reading and writing multiple number types in an ArrayBuffer, regardless of the platform's endianness. This is critical for implementing binary protocols, file parsers, or high-performance networking where byte-perfect alignment is required.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
const buffer = new ArrayBuffer(8);
const view = new DataView(buffer);
// Write a 32-bit integer at byte 0 in Big-Endian
view.setUint32(0, 0x12345678, false);
// Read the first byte
const firstByte = view.getUint8(0);
console.log(firstByte.toString(16)); // '12'
// Read as Little-Endian to see the difference
const leValue = view.getUint32(0, true);
console.log(leValue.toString(16)); // '78563412'
PerformanceData Types
JavaScript · ExpertSnippet

Backpressure Handling in Async Generators

Async generators provide a natural way to implement backpressure. By awaiting a promise inside the generator before yielding, you can signal to the producer that the consumer is not ready for more data, effectively managing flow control in asynchronous streams.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
async function* streamProcessor(source) {
for await (const chunk of source) {
if (needsThrottling()) {
await new Promise(r => setTimeout(r, 100)); // Simulate backpressure
}
yield transform(chunk);
}
}
const consumer = async () => {
for await (const data of streamProcessor(dataSource)) {
console.log(data);
}
};
Async & ConcurrencyDesign Patterns
JavaScript · ExpertSnippet

Explicit Resource Management with Symbol.dispose

The 'using' keyword, combined with Symbol.dispose, introduces deterministic resource management. It ensures that cleanup logic is executed immediately when the variable goes out of scope, preventing memory leaks or hanging file handles without relying on manual try-finally blocks.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class TempFile {
constructor(path) {
this.path = path;
console.log(`File ${path} opened.`);
}
[Symbol.dispose]() {
console.log(`File ${this.path} closed and deleted.`);
}
}
{
using file = new TempFile('test.txt');
// Resource is bound to this block scope
}
// Automatically disposed here
SyntaxBest Practices
JavaScript · ExpertSnippet

Function Composition via Pipe Combinators

Pipe is a functional programming pattern that composes multiple functions into a single transformation pipeline. It improves readability by allowing data to flow from left to right, avoiding deeply nested function calls and reducing imperative boilerplate.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
const pipe = (...fns) => (initialValue) =>
fns.reduce((acc, fn) => fn(acc), initialValue);
const normalize = s => s.trim().toLowerCase();
const slugify = s => s.replace(/\s+/g, '-');
const label = s => `id:${s}`;
const createSlug = pipe(normalize, slugify, label);
console.log(createSlug(' Expert JS Snippet ')); // 'id:expert-js-snippet'
FunctionsDesign Patterns