Code Snippet Library

Free copy-paste code snippets for Python, JavaScript, TypeScript, Go, and Bash. Searchable library organized by language and category — strings, arrays, HTTP, file I/O, and more.

20 snippets found

Reverse a String

PythonStrings
text = "hello"
reversed_text = text[::-1]
print(reversed_text)  # "olleh"

Read a File

PythonFile I/O
with open("data.txt", "r") as f:
    content = f.read()
    print(content)

HTTP GET Request

PythonHTTP
import requests

response = requests.get("https://api.example.com/data")
data = response.json()
print(data)

Sort a List of Dicts

PythonSorting
users = [{"name": "Bob", "age": 30}, {"name": "Alice", "age": 25}]
sorted_users = sorted(users, key=lambda u: u["age"])
print(sorted_users)

List Comprehension with Filter

PythonArrays
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = [n for n in numbers if n % 2 == 0]
print(evens)  # [2, 4, 6, 8, 10]

Flatten Nested Array

JavaScriptArrays
const nested = [[1, 2], [3, [4, 5]]];
const flat = nested.flat(Infinity);
console.log(flat); // [1, 2, 3, 4, 5]

Debounce Function

JavaScriptPatterns
function debounce(fn, ms) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), ms);
  };
}

Fetch with Timeout

JavaScriptHTTP
async function fetchWithTimeout(url, ms = 5000) {
  const controller = new AbortController();
  const id = setTimeout(() => controller.abort(), ms);
  const res = await fetch(url, { signal: controller.signal });
  clearTimeout(id);
  return res.json();
}

Remove Duplicates

JavaScriptArrays
const arr = [1, 2, 2, 3, 3, 4];
const unique = [...new Set(arr)];
console.log(unique); // [1, 2, 3, 4]

Template Literal Tag

JavaScriptStrings
function highlight(strings, ...values) {
  return strings.reduce((result, str, i) =>
    result + str + (values[i] ? `<mark>${values[i]}</mark>` : ""), "");
}
const name = "World";
highlight`Hello ${name}!`; // "Hello <mark>World</mark>!"

Type Guard Function

TypeScriptPatterns
interface Dog { bark(): void; }
interface Cat { meow(): void; }

function isDog(pet: Dog | Cat): pet is Dog {
  return (pet as Dog).bark !== undefined;
}

Generic API Fetcher

TypeScriptHTTP
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>;
}

interface User { id: number; name: string; }
const user = await fetchData<User>("/api/user/1");

Zod Schema Validation

TypeScriptPatterns
import { z } from "zod";

const UserSchema = z.object({
  name: z.string().min(1),
  email: z.string().email(),
  age: z.number().int().positive(),
});

type User = z.infer<typeof UserSchema>;
const user = UserSchema.parse(input);

Read File Line by Line

GoFile I/O
file, _ := os.Open("data.txt")
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
    fmt.Println(scanner.Text())
}

HTTP Server

GoHTTP
package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, World!")
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

Sort a Slice

GoSorting
import "slices"

nums := []int{5, 2, 8, 1, 9}
slices.Sort(nums)
fmt.Println(nums) // [1 2 5 8 9]

Variable & Loop

BashBasics
#!/bin/bash
fruits=("apple" "banana" "cherry")
for fruit in "${fruits[@]}"; do
  echo "I like $fruit"
done

Find and Replace in Files

BashFile I/O
# Replace "foo" with "bar" in all .txt files
find . -name "*.txt" -exec sed -i 's/foo/bar/g' {} +

Check Command Exists

BashBasics
if command -v git &> /dev/null; then
  echo "git is installed"
else
  echo "git is NOT installed"
fi

Parallel Async Tasks

JavaScriptPatterns
const urls = ["/api/a", "/api/b", "/api/c"];
const results = await Promise.allSettled(
  urls.map(url => fetch(url).then(r => r.json()))
);
results.forEach((r, i) => {
  if (r.status === "fulfilled") console.log(urls[i], r.value);
  else console.error(urls[i], r.reason);
});

Free Code Snippet Library — Copy & Paste Ready

Search and copy production-ready code snippets for Python, JavaScript, TypeScript, Go, and Bash. Every snippet is organized by language and category — strings, arrays, HTTP requests, file I/O, sorting, and common patterns — so you can find what you need in seconds.

How to Use the Code Snippet Library

  1. Browse all snippets or filter by language and category
  2. Use the search bar to find snippets by keyword
  3. Click "Copy Code" to copy any snippet to your clipboard

Why Use a Snippet Library?

Reusable code snippets save time on repetitive tasks like reading files, making HTTP requests, sorting data, and string manipulation. Instead of searching StackOverflow each time, bookmark this page for instant access to tested, copy-ready code in your favorite language.