Code Snippet Library

Ready-to-use snippets � copy, paste, ship.

31 snippets

31 snippets

JavaScriptDebounce Function
performanceevents
function debounce(fn, delay) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}
JavaScriptDeep Clone Object
objectsutility
const deepClone = (obj) => JSON.parse(JSON.stringify(obj));
JavaScriptShuffle Array
arrayrandom
const shuffle = (arr) => [...arr].sort(() => Math.random() - 0.5);
JavaScriptSleep / Delay
asyncutility
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
// Usage: await sleep(1000);
JavaScriptGroup By Key
arrayobjects
const groupBy = (arr, key) =>
  arr.reduce((acc, item) => {
    (acc[item[key]] = acc[item[key]] || []).push(item);
    return acc;
  }, {});
JavaScriptThrottle Function
performanceevents
function throttle(fn, limit) {
  let inThrottle;
  return (...args) => {
    if (!inThrottle) {
      fn(...args);
      inThrottle = true;
      setTimeout(() => (inThrottle = false), limit);
    }
  };
}
JavaScriptFlatten Nested Array
array
const flatten = (arr) => arr.flat(Infinity);
// Or recursively:
const flattenDeep = (arr) =>
  arr.reduce((acc, val) =>
    Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
JavaScriptCopy to Clipboard
browserutility
async function copyToClipboard(text) {
  await navigator.clipboard.writeText(text);
}
TypeScriptGeneric Fetch Wrapper
fetchasync
async function fetchData<T>(url: string): Promise<T> {
  const res = await fetch(url);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json() as Promise<T>;
}
TypeScriptOptional Chaining Type
typesutility
type DeepPartial<T> = {
  [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
};
TypeScriptEnum to Array
enumutility
enum Direction { Up, Down, Left, Right }
const directions = Object.values(Direction).filter(v => typeof v === 'string');
PythonRead JSON File
filejson
import json

with open('data.json', 'r') as f:
    data = json.load(f)
PythonFlatten List
listutility
from itertools import chain
flat = list(chain.from_iterable([[1,2],[3,4],[5]]))
PythonTimer Decorator
performancedecorator
import time

def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        print(f"{func.__name__} took {time.time()-start:.4f}s")
        return result
    return wrapper
PythonRetry Decorator
error handlingdecorator
import time, functools

def retry(times=3, delay=1):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for i in range(times):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    if i == times - 1:
                        raise
                    time.sleep(delay)
        return wrapper
    return decorator
CSSCenter with Flexbox
layoutflexbox
.center {
  display: flex;
  align-items: center;
  justify-content: center;
}
CSSResponsive Font Size
typographyresponsive
/* Scales from 16px at 320px screen to 24px at 1280px */
font-size: clamp(1rem, 0.5rem + 2vw, 1.5rem);
CSSCSS Custom Scrollbar
scrollbarui
::-webkit-scrollbar { width: 8px; }
::-webkit-scrollbar-track { background: #1a1a2e; }
::-webkit-scrollbar-thumb { background: #3b82f6; border-radius: 4px; }
::-webkit-scrollbar-thumb:hover { background: #2563eb; }
CSSText Gradient
typographygradient
.gradient-text {
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}
BashFind Large Files
filesystemdisk
find . -type f -size +100M -exec ls -lh {} \; | sort -k5 -rh | head -20
BashBatch Rename Files
filesrename
# Add prefix to all .jpg files
for f in *.jpg; do mv "$f" "prefix_$f"; done
BashMonitor Port
networkdebug
# Check what's running on port 3000
lsof -i :3000
# Kill it
kill -9 $(lsof -t -i:3000)
SQLPagination Query
databasepagination
SELECT * FROM users
ORDER BY created_at DESC
LIMIT 10 OFFSET 20; -- page 3 (0-indexed)
SQLRunning Total
window functions
SELECT
  date,
  amount,
  SUM(amount) OVER (ORDER BY date) AS running_total
FROM transactions;
SQLFind Duplicates
data quality
SELECT email, COUNT(*) as cnt
FROM users
GROUP BY email
HAVING COUNT(*) > 1;
ReactuseLocalStorage Hook
hooksstorage
import { useState, useEffect } from 'react';

function useLocalStorage(key, defaultValue) {
  const [value, setValue] = useState(() => {
    try {
      return JSON.parse(localStorage.getItem(key)) ?? defaultValue;
    } catch { return defaultValue; }
  });
  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);
  return [value, setValue];
}
ReactuseDebounce Hook
hooksperformance
import { useState, useEffect } from 'react';

function useDebounce(value, delay = 300) {
  const [debounced, setDebounced] = useState(value);
  useEffect(() => {
    const t = setTimeout(() => setDebounced(value), delay);
    return () => clearTimeout(t);
  }, [value, delay]);
  return debounced;
}
ReactuseFetch Hook
hooksdata fetching
import { useState, useEffect } from 'react';

function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  useEffect(() => {
    setLoading(true);
    fetch(url)
      .then(r => r.json())
      .then(setData)
      .catch(setError)
      .finally(() => setLoading(false));
  }, [url]);
  return { data, loading, error };
}
GitUndo Last Commit
undohistory
# Undo commit but keep changes staged
git reset --soft HEAD~1

# Undo commit and unstage changes
git reset HEAD~1

# Completely discard last commit
git reset --hard HEAD~1
GitStash with Message
stash
git stash push -m "WIP: feature login"
git stash list
git stash pop stash@{0}
GitSquash Last N Commits
historyrebase
# Squash last 3 commits into one
git rebase -i HEAD~3
# In editor: change 'pick' to 'squash' on 2nd and 3rd
👋 Need help with code?