CodeNFacts

explore-codenfacts

The Living CodeZ
of Production

16,482 battle-tested snippets. Copied 2.4 million times. Curated by engineers at Google, Stripe, and Vercel.

โŒ˜

Showing 16 of 16 premium snippets

PythonAdvancedโ˜… PRO
๐Ÿ‘ 38.9k

RAG Vector Search

Cosine similarity + FAISS-style top-k in pure NumPy - the core of modern AI apps.

python
def top_k_similar(query_emb, corpus_embs, k=5):
scores = np.dot(corpus_embs, query_emb) / (np.linalg.norm(corpus_embs, axis=1) * np.linalg.norm(query_emb))
return np.argsort(scores)[-k:][::-1]
#ai#rag#embeddings#numpy
JavaScriptIntermediateโ˜… PRO
๐Ÿ‘ 41.3k

60 LOC Reactive Store

Zustand-style store with signals, derived state & persistence - zero dependencies.

javascript
function createStore(init) {
let state = init;
const subs = new Set();
return {
get: () => state,
set: (fn) => { state = fn(state); subs.forEach(s => s(state)); },
subscribe: (fn) => { subs.add(fn); return () => subs.delete(fn); }
};
}
#state#reactive#vanilla
TypeScriptAdvancedโ˜… PRO
๐Ÿ‘ 36.2k

useDeferredValue + Transition

React 18+ concurrent rendering patterns for instant search UX.

typescript
const deferredQuery = useDeferredValue(query);
const isStale = deferredQuery !== query;
#react#concurrent#ux
TypeScriptIntermediateโ˜… PRO
๐Ÿ‘ 29.4k

React 19 useActionState

Server Actions + optimistic UI in 12 lines - the future of forms.

typescript
const [state, submit, isPending] = useActionState(
async (prev, form) => { /* server action */ },
{ error: null }
);
#react19#server-actions#optimistic
RustAdvancedโ˜… PRO
๐Ÿ‘ 31.8k

Lock-Free Ring Buffer

Zero-allocation, cache-friendly SPSC ring buffer in Rust using atomics.

rust
struct RingBuf<T, const N: usize> {
buf: [MaybeUninit<T>; N],
head: AtomicUsize,
tail: AtomicUsize,
}
impl<T, const N: usize> RingBuf<T, N> {
fn push(&self, val: T) -> bool { /* ... */ true }
}
#concurrency#rust#lock-free#performance
CSSBeginnerโ˜… PRO
๐Ÿ‘ 33.7k

Tailwind + CSS Variables Theme Engine

Dark/light/system + custom brand colors with zero runtime JS.

css
:root { --primary: 234 179 8; }
.dark { --primary: 250 204 21; }
.bg-primary { background-color: hsl(var(--primary)); }
#tailwind#theme#css-variables
CSSIntermediate
๐Ÿ‘ 26.1k

Scroll-Driven Animations

Pure CSS scroll progress animations - no JavaScript, buttery 60fps.

css
@keyframes reveal {
from { opacity: 0; translate: 0 60px; }
to { opacity: 1; translate: 0 0; }
}
.card { animation: reveal linear both; animation-timeline: view(); animation-range: entry 0% entry 50%; }
#animation#scroll#native#css
PythonIntermediate
๐Ÿ‘ 24.8k

Rate Limiter with Redis

Token bucket + sliding window in 18 lines - production ready.

python
async def is_allowed(user_id: str, redis):
key = f#86efac">"rate:{user_id}"
await redis.incr(key)
await redis.expire(key, 60)
#rate-limit#redis#backend
TypeScriptIntermediate
๐Ÿ‘ 28.4k

Debounce with Cleanup

TypeScript-safe debounce with proper cleanup - battle-tested for search, resize & real-time inputs.

typescript
function useDebounce<T>(value: T, delay: number): T {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const timer = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(timer);
}, [value, delay]);
return debounced;
}
#hooks#performance#typescript
PythonIntermediate
๐Ÿ‘ 22.9k

Trie Autocomplete

O(m) prefix search regardless of dictionary size - used in IDEs & search engines.

python
class Trie:
def __init__(self):
self.root = {}
def insert(self, word: str):
node = self.root
for ch in word:
node = node.setdefault(ch, {})
node[#86efac">'$'] = True
#trie#autocomplete#search
PythonIntermediate
๐Ÿ‘ 21.4k

Binary Search Tree Iterator

O(1) amortized next() using explicit stack - LeetCode 173.

python
class BSTIterator:
def __init__(self, root):
self.stack = []
self._leftmost_inorder(root)
#bst#iterator#leetcode
PythonAdvanced
๐Ÿ‘ 19.7k

Async Generator Pipeline

Memory-efficient lazy pagination using async generators - never load the entire dataset again.

python
async def paginate(url: str):
while url:
resp = await httpx.get(url)
data = resp.json()
yield data[#86efac">"results"]
url = data.get(#86efac">"next")
async for batch in paginate(#86efac">"/api/items?limit=500"):
process(batch)
#async#generators#memory#pagination
RustAdvanced
๐Ÿ‘ 18.2k

WebAssembly Memory Pool

Zero-copy Rust โ†’ JS memory sharing using linear memory pools.

rust
#[wasm_bindgen]
pub struct MemoryPool {
buffer: Vec<u8>,
}
#wasm#performance#rust
YAMLAdvanced
๐Ÿ‘ 17.6k

Zero-Downtime K8s Deploy

RollingUpdate + preStop hook + graceful shutdown - zero dropped requests.

yaml
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 2
maxUnavailable: 0
lifecycle:
preStop:
exec:
command: [#86efac">"sleep", "30"]
#k8s#deploy#production#zero-downtime
YAMLAdvanced
๐Ÿ‘ 15.9k

Kubernetes HPA + VPA Combo

Horizontal + Vertical Pod Autoscaler for true cost-optimized scaling.

yaml
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
spec:
updatePolicy:
updateMode: #86efac">"Auto"
#k8s#scaling#cost-optimization
CSSBeginner
๐Ÿ‘ 14.2k

CSS Logical Properties

Direction-agnostic layouts that instantly support RTL & 120+ languages.

css
.card {
margin-inline: auto;
padding-block: 1.5rem;
padding-inline: 2rem;
border-inline-start: 4px solid indigo;
inset-inline-end: 0;
}
#css#i18n#logical#rtl