Debounce Function JS
function debounce(fn, delay = 300) { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), delay); }; } // Usage const search = debounce((q) => fetchResults(q), 500);
Delays execution until after a pause in calls. Great for search inputs, resize handlers.
Deep Clone Object JS
const deepClone = (obj) => structuredClone(obj); // Fallback for older browsers const deepCloneFallback = (obj) => JSON.parse(JSON.stringify(obj));
Creates a true deep copy. structuredClone handles Date, Map, Set, ArrayBuffer.
Array Deduplication JS
const unique = (arr) => [...new Set(arr)]; // Dedupe objects by key const uniqueBy = (arr, key) => [...new Map(arr.map(item => [item[key], item])).values()];
Remove duplicate values from arrays, including object arrays by key.
Fetch with Timeout JS
async function fetchWithTimeout(url, options = {}, timeout = 5000) { const controller = new AbortController(); const id = setTimeout(() => controller.abort(), timeout); try { const res = await fetch(url, { ...options, signal: controller.signal }); clearTimeout(id); return res; } catch (err) { clearTimeout(id); throw err; } }
Wraps fetch with an AbortController-based timeout.
Group Array by Key JS
const groupBy = (arr, key) => arr.reduce((acc, item) => { (acc[item[key]] ||= []).push(item); return acc; }, {}); // Usage groupBy(users, 'role'); // { admin: [...], user: [...] }
Groups an array of objects by a given key. Uses Object.groupBy in modern JS.
Throttle Function JS
function throttle(fn, limit = 300) { let inThrottle = false; return (...args) => { if (!inThrottle) { fn(...args); inThrottle = true; setTimeout(() => (inThrottle = false), limit); } }; }
Ensures function runs at most once per interval. Good for scroll/resize handlers.
LocalStorage Wrapper JS
const store = { get: (key) => JSON.parse(localStorage.getItem(key)), set: (key, val) => localStorage.setItem(key, JSON.stringify(val)), remove: (key) => localStorage.removeItem(key), };
Type-safe localStorage with automatic JSON serialization.
Date Formatting JS
const formatDate = (date, locale = 'en-US') => new Intl.DateTimeFormat(locale, { year: 'numeric', month: 'short', day: 'numeric' }).format(new Date(date)); // "Feb 27, 2026" const relativeTime = (date) => new Intl.RelativeTimeFormat('en', { numeric: 'auto' }) .format(Math.round((date - Date.now()) / 86400000), 'day');
Format dates using Intl API. No library needed.
Promise.allSettled Pattern JS
const results = await Promise.allSettled([ fetchUser(1), fetchUser(2), fetchUser(3), ]); const successes = results .filter(r => r.status === 'fulfilled') .map(r => r.value); const failures = results .filter(r => r.status === 'rejected') .map(r => r.reason);
Run promises in parallel, handle successes and failures independently.
Flatten Nested Array JS
const flatten = (arr) => arr.flat(Infinity); // Manual recursive const flattenDeep = (arr) => arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
Flatten arrays of any depth.
Read/Write JSON File PY
import json from pathlib import Path def read_json(path): return json.loads(Path(path).read_text()) def write_json(path, data, indent=2): Path(path).write_text(json.dumps(data, indent=indent))
Simple JSON file I/O using pathlib.
List Comprehension with Filter PY
evens = [x for x in range(20) if x % 2 == 0] names = [u["name"] for u in users if u["active"]] flat = [x for row in matrix for x in row] # flatten 2D list
Concise filtering and transformation in one expression.
Decorator with Arguments PY
import functools, time def retry(max_retries=3, delay=1): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): for attempt in range(max_retries): try: return func(*args, **kwargs) except Exception as e: if attempt == max_retries - 1: raise time.sleep(delay) return wrapper return decorator @retry(max_retries=5, delay=2) def fetch_data(url): ...
A retry decorator with configurable attempts and delay.
Dataclass Example PY
from dataclasses import dataclass, field @dataclass class User: name: str email: str roles: list[str] = field(default_factory=list) active: bool = True @property def is_admin(self): return "admin" in self.roles
Clean data containers with auto __init__, __repr__, __eq__.
Context Manager PY
from contextlib import contextmanager import time @contextmanager def timer(label="Block"): start = time.perf_counter() yield elapsed = time.perf_counter() - start print(f"{label}: {elapsed:.4f}s") with timer("DB query"): results = db.execute(query)
Custom context manager for timing code blocks.
Sort List of Dicts by Key PY
from operator import itemgetter users = [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}] by_age = sorted(users, key=itemgetter("age")) by_name_desc = sorted(users, key=lambda u: u["name"], reverse=True)
Sort a list of dictionaries by any key, ascending or descending.
Generator Function PY
def fibonacci(limit): a, b = 0, 1 while a < limit: yield a a, b = b, a + b # Lazy evaluation — memory efficient for n in fibonacci(1000): print(n)
Lazy sequence generation with yield. Memory-efficient for large datasets.
Dictionary Merge PY
# Python 3.9+ merged = defaults | overrides # Python 3.5+ merged = {**defaults, **overrides} # In-place defaults.update(overrides)
Three ways to merge dictionaries. Later keys override earlier ones.
File Path Handling (pathlib) PY
from pathlib import Path p = Path("data/reports") p.mkdir(parents=True, exist_ok=True) for f in p.glob("*.csv"): print(f.stem, f.suffix, f.stat().st_size) text = (p / "report.txt").read_text() (p / "output.txt").write_text("Hello")
Modern file/path operations with pathlib. Replaces os.path.
HTTP Request (requests) PY
import requests resp = requests.get("https://api.example.com/users", timeout=10) resp.raise_for_status() users = resp.json() # POST with JSON body resp = requests.post( "https://api.example.com/users", json={"name": "Alice"}, headers={"Authorization": "Bearer TOKEN"} )
Simple HTTP requests with the requests library.
HTTP Server GO
package main import ( "encoding/json" "net/http" ) func main() { http.HandleFunc("/api/health", func(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(map[string]string{"status": "ok"}) }) http.ListenAndServe(":8080", nil) }
Minimal HTTP server with JSON response using only the standard library.
Goroutine with WaitGroup GO
var wg sync.WaitGroup urls := []string{"url1", "url2", "url3"} for _, url := range urls { wg.Add(1) go func(u string) { defer wg.Done() resp, err := http.Get(u) if err != nil { return } defer resp.Body.Close() // process response }(url) } wg.Wait()
Run concurrent goroutines and wait for all to finish.
Error Handling Pattern GO
import "fmt" type AppError struct { Code int Message string Err error } func (e *AppError) Error() string { return fmt.Sprintf("%s: %v", e.Message, e.Err) } func (e *AppError) Unwrap() error { return e.Err } func getUser(id int) (*User, error) { user, err := db.Find(id) if err != nil { return nil, &AppError{404, "user not found", err} } return user, nil }
Custom error types with wrapping for idiomatic Go error handling.
Struct with Methods & Interface GO
type Shape interface { Area() float64 } type Circle struct { Radius float64 } func (c Circle) Area() float64 { return math.Pi * c.Radius * c.Radius } // Circle implicitly satisfies Shape interface func printArea(s Shape) { fmt.Printf("Area: %.2f\n", s.Area()) }
Go interfaces are implicit — no "implements" keyword needed.
Channel Communication GO
ch := make(chan string, 10) // buffered channel go func() { ch <- "hello" close(ch) }() for msg := range ch { fmt.Println(msg) }
Goroutine communication via channels. Range over channel until closed.
Slice Operations GO
// Filter filtered := make([]int, 0) for _, v := range nums { if v > 10 { filtered = append(filtered, v) } } // Map (Go 1.21+ with slices package) import "slices" slices.Sort(nums) idx, found := slices.BinarySearch(nums, 42) // Contains slices.Contains(nums, 42)
Common slice operations: filter, sort, search, contains.
Stream API (filter/map/collect) JAVA
List<String> names = users.stream() .filter(u -> u.isActive()) .map(User::getName) .sorted() .collect(Collectors.toList()); Map<String, List<User>> byRole = users.stream() .collect(Collectors.groupingBy(User::getRole));
Functional-style collection processing with Java Streams.
Optional Handling JAVA
Optional<User> user = repository.findById(id); String name = user .map(User::getName) .orElse("Unknown"); user.ifPresent(u -> sendEmail(u.getEmail())); User u = user.orElseThrow(() -> new NotFoundException("User not found"));
Safe null handling with Optional. Avoid NullPointerException.
CompletableFuture JAVA
CompletableFuture<String> future = CompletableFuture .supplyAsync(() -> fetchUser(id)) .thenApply(user -> user.getName()) .thenApply(String::toUpperCase) .exceptionally(ex -> "UNKNOWN"); // Parallel execution CompletableFuture.allOf(future1, future2, future3).join();
Async programming with CompletableFuture. Chain, combine, handle errors.
Singleton Pattern JAVA
public class Config { private static volatile Config instance; private Config() {} // private constructor public static Config getInstance() { if (instance == null) { synchronized (Config.class) { if (instance == null) { instance = new Config(); } } } return instance; } }
Thread-safe Singleton using double-checked locking.
Builder Pattern JAVA
public class User { private final String name; private final String email; private final int age; private User(Builder b) { name = b.name; email = b.email; age = b.age; } public static class Builder { private String name, email; private int age; public Builder name(String n) { name = n; return this; } public Builder email(String e) { email = e; return this; } public Builder age(int a) { age = a; return this; } public User build() { return new User(this); } } } // Usage: new User.Builder().name("Alice").email("[email protected]").age(30).build();
Fluent builder for objects with many optional parameters.
HashMap Operations JAVA
Map<String, Integer> freq = new HashMap<>(); // Count frequency for (String word : words) { freq.merge(word, 1, Integer::sum); } // Get with default int count = freq.getOrDefault("hello", 0); // Compute if absent map.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
HashMap utilities: merge, getOrDefault, computeIfAbsent.
Error Handling (Strict Mode) BASH
#!/usr/bin/env bash set -euo pipefail IFS=$'\n\t' # -e: exit on error # -u: error on undefined variable # -o pipefail: catch errors in piped commands
Always start scripts with strict mode to catch errors early.
Loop Through Files BASH
for file in *.log; do [ -f "$file" ] || continue echo "Processing: $file" wc -l "$file" done # Find + loop (handles spaces in names) find . -name "*.txt" -print0 | while IFS= read -r -d '' f; do echo "$f" done
Safe file iteration patterns. Always quote variables for space handling.
Function with Arguments BASH
greet() { local name="${1:?Error: name required}" local greeting="${2:-Hello}" echo "$greeting, $name!" } greet "Alice" # Hello, Alice! greet "Bob" "Hey" # Hey, Bob!
Functions with required args, default values, and local variables.
Check if File/Dir Exists BASH
[ -f "config.yml" ] && echo "File exists" || echo "Not found" [ -d "/var/log" ] && echo "Dir exists" [ -z "$VAR" ] && echo "VAR is empty" [ -n "$VAR" ] && echo "VAR is set" [ -r "$file" ] && echo "File is readable"
Common test expressions for files, dirs, and variables.
Parse Command-Line Args BASH
while [[ $# -gt 0 ]]; do case "$1" in -n|--name) NAME="$2"; shift 2 ;; -v|--verbose) VERBOSE=true; shift ;; -h|--help) usage; exit 0 ;; *) echo "Unknown: $1"; exit 1 ;; esac done echo "Name: ${NAME:-default}"
Simple argument parsing with case/shift. No getopt needed.
Read File Line by Line BASH
while IFS= read -r line; do echo "Line: $line" done < input.txt # Skip comments and empty lines while IFS= read -r line; do [[ "$line" =~ ^#|^$ ]] && continue process "$line" done < config.txt
Safe line-by-line reading with IFS= and -r to preserve whitespace.
Common Table Expression (CTE) SQL
WITH active_users AS ( SELECT id, name, email FROM users WHERE active = true AND created_at > NOW() - INTERVAL '30 days' ) SELECT au.name, COUNT(o.id) AS order_count FROM active_users au LEFT JOIN orders o ON o.user_id = au.id GROUP BY au.name ORDER BY order_count DESC;
CTEs make complex queries readable by defining named subqueries.
Window Functions SQL
SELECT name, department, salary, ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn, RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rnk, DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS dense_rnk, LAG(salary) OVER (PARTITION BY department ORDER BY salary DESC) AS prev_salary, SUM(salary) OVER (PARTITION BY department) AS dept_total FROM employees;
ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, and running aggregates.
UPSERT (INSERT ON CONFLICT) SQL
-- PostgreSQL INSERT INTO users (email, name, updated_at) VALUES ('[email protected]', 'Alice', NOW()) ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name, updated_at = EXCLUDED.updated_at; -- MySQL INSERT INTO users (email, name) VALUES ('[email protected]', 'Alice') ON DUPLICATE KEY UPDATE name = VALUES(name);
Insert or update if a unique constraint is violated.
Recursive CTE SQL
WITH RECURSIVE org_tree AS ( -- Base case: top-level managers SELECT id, name, manager_id, 1 AS level FROM employees WHERE manager_id IS NULL UNION ALL -- Recursive case SELECT e.id, e.name, e.manager_id, t.level + 1 FROM employees e JOIN org_tree t ON e.manager_id = t.id ) SELECT * FROM org_tree ORDER BY level, name;
Traverse hierarchical data (org charts, categories, file trees).
Conditional Aggregation (Pivot) SQL
SELECT product, SUM(CASE WHEN month = 'Jan' THEN revenue ELSE 0 END) AS jan, SUM(CASE WHEN month = 'Feb' THEN revenue ELSE 0 END) AS feb, SUM(CASE WHEN month = 'Mar' THEN revenue ELSE 0 END) AS mar, SUM(revenue) AS total FROM sales GROUP BY product;
Pivot rows to columns using CASE inside aggregate functions.
JSON Operations (PostgreSQL) SQL
-- Extract value SELECT data->>'name' AS name FROM users; -- Query inside JSON SELECT * FROM users WHERE data->'address'->>'city' = 'NYC'; -- Build JSON from rows SELECT json_agg(json_build_object('id', id, 'name', name)) FROM users;
Query and manipulate JSONB columns in PostgreSQL.