Code Recipes

Small, reusable recipes for common programming tasks. Search by problem, language, or code.

JavaScriptBeginner

Remove duplicates from an array

Keep the first occurrence of each value with a Set.

Purpose: Clean data before display or processing.

Real-life example: Remove repeated emails from a newsletter signup list.

const unique = [...new Set(items)];
JavaScriptBeginner

Group objects by a property

Build a lookup of items grouped by one of their fields.

Purpose: Organize records for quick lookup.

Real-life example: Group orders by status for a dashboard.

const grouped = items.reduce((groups, item) => {
  (groups[item.type] ??= []).push(item);
  return groups;
}, {});
JavaScriptBeginner

Safely read a nested value

Use optional chaining and nullish coalescing for missing data.

Purpose: Avoid crashes when data is incomplete.

Real-life example: Show a city from an API profile that may lack an address.

const city = user?.address?.city ?? "Unknown";
JavaScriptBeginner

Run requests concurrently

Start independent requests together and wait for all results.

Purpose: Reduce total wait time for independent calls.

Real-life example: Load a user and their posts together on a profile page.

const [user, posts] = await Promise.all([
  fetchUser(id),
  fetchPosts(id),
]);
JavaScriptBeginner

Debounce a function

Wait until calls pause before running an expensive action.

Purpose: Prevent excessive calls during rapid input.

Real-life example: Search as the user types without spamming the API.

function debounce(fn, delay = 250) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}
JavaScriptBeginner

Fetch JSON with error handling

Check the HTTP status before parsing the response body.

Purpose: Fail gracefully and inform the user.

Real-life example: Show a friendly error if a weather API request fails.

async function getJson(url) {
  const response = await fetch(url);
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  return response.json();
}
PythonBeginner

Count values

Use Counter to tally repeated values in an iterable.

Purpose: Understand frequency and popularity.

Real-life example: Count the most common words in survey responses.

from collections import Counter

counts = Counter(words)
print(counts.most_common(3))
PythonBeginner

Read a large file line by line

Stream a file without loading all of it into memory.

Purpose: Process big files without memory issues.

Real-life example: Parse a 2GB log file on a server.

with open("data.txt", encoding="utf-8") as file:
    for line in file:
        process(line.rstrip("\n"))
PythonBeginner

Create a dictionary with defaults

Group values without checking whether each key exists.

Purpose: Simplify grouping logic.

Real-life example: Group students by class without key checks.

from collections import defaultdict

groups = defaultdict(list)
for item in items:
    groups[item.category].append(item)
PythonBeginner

Retry a temporary operation

Retry a failing operation a limited number of times.

Purpose: Recover from transient failures.

Real-life example: Retry a payment API during a brief network blip.

import time

for attempt in range(3):
    try:
        result = operation()
        break
    except TemporaryError:
        if attempt == 2:
            raise
        time.sleep(2 ** attempt)
PythonBeginner

Merge dictionaries

Combine mappings with the dictionary union operator.

Purpose: Combine defaults with user overrides.

Real-life example: Apply default settings then user preferences.

defaults = {"theme": "light", "page_size": 20}
settings = {**defaults, **user_settings}
# user settings override defaults
PythonBeginner

Sort records by multiple fields

Sort by name, then by score descending.

Purpose: Produce stable, meaningful ordering.

Real-life example: Sort a leaderboard by name then score.

records.sort(key=lambda row: (row["name"], -row["score"]))
SQLBeginner

Find duplicate rows

Group by a key and keep values that occur more than once.

Purpose: Detect data quality issues.

Real-life example: Find duplicate customer emails.

SELECT email, COUNT(*) AS occurrences
FROM users
GROUP BY email
HAVING COUNT(*) > 1;
SQLBeginner

Return the latest row per user

Use ROW_NUMBER to select the newest record in each group.

Purpose: Get current state from history.

Real-life example: Show each user's latest order.

WITH ranked AS (
  SELECT orders.*,
         ROW_NUMBER() OVER (
           PARTITION BY user_id ORDER BY created_at DESC
         ) AS rn
  FROM orders
)
SELECT * FROM ranked WHERE rn = 1;
SQLBeginner

Paginate query results

Limit a result set and skip rows for basic offset pagination.

Purpose: Limit response size for the UI.

Real-life example: Load 20 products per page.

SELECT id, name
FROM products
ORDER BY id
LIMIT 20 OFFSET 40;
SQLBeginner

Upsert a row

Insert a record or update it when its unique key already exists (PostgreSQL).

Purpose: Insert or update in one operation.

Real-life example: Save a user profile whether it is new or existing.

INSERT INTO users (email, name)
VALUES ('ada@example.com', 'Ada')
ON CONFLICT (email)
DO UPDATE SET name = EXCLUDED.name;
SQLBeginner

Find rows with no related record

Use NOT EXISTS to find parent rows without a matching child.

Purpose: Find orphaned or unused records.

Real-life example: Customers without orders.

SELECT c.id, c.name
FROM customers c
WHERE NOT EXISTS (
  SELECT 1 FROM orders o WHERE o.customer_id = c.id
);
ShellBeginner

Check whether a port is listening

Use netcat to test a TCP connection to a host and port.

Purpose: Verify service availability.

Real-life example: Check if a web server is running on port 443.

nc -vz example.com 443
ShellBeginner

Search logs around an error

Find matching lines with line numbers, then inspect nearby context.

Purpose: Investigate failures quickly.

Real-life example: Find error context in app.log.

grep -n -C 3 "ERROR" app.log
ShellBeginner

Watch a command output

Repeat a command every two seconds to monitor changing output.

Purpose: Monitor changing system state.

Real-life example: Watch disk usage during a job.

watch -n 2 'df -h'
ShellBeginner

Pretty-print JSON

Format JSON output and select a field with jq.

Purpose: Inspect API responses.

Real-life example: Format curl output for debugging.

curl -s https://api.example.com/users | jq '.[] | {name, email}'
GitBeginner

Create and switch to a branch

Create a feature branch from the current commit and switch to it.

Purpose: Start isolated work safely.

Real-life example: Create a feature branch for a bug fix.

git switch -c feature/my-change
GitBeginner

Find a commit that introduced a bug

Bisect the commit history between a known-good and bad revision.

Purpose: Locate a regression efficiently.

Real-life example: Bisect to find the broken commit.

git bisect start
git bisect bad HEAD
git bisect good v1.0
# Test each revision Git checks out
git bisect reset
GitBeginner

Save work before switching tasks

Stash tracked changes with a label and restore them later.

Purpose: Preserve unfinished changes.

Real-life example: Stash work to review a pull request.

git stash push -m "unfinished feature"
# switch branches and work
git stash pop
TypeScriptBeginner

Type a readonly tuple

Use as const to keep literal values in tuples and objects.

Purpose: Prevent accidental mutation of constants.

Real-life example: Define allowed roles for RBAC.

const roles = ["admin", "editor", "viewer"] as const;
type Role = typeof roles[number];
TypeScriptBeginner

Narrow a union with a type guard

Check a property to refine a union type safely.

Purpose: Safely handle unknown input.

Real-life example: Validate an API payload before use.

function isUser(value: unknown): value is User {
  return typeof value === "object" && value !== null && "id" in value;
}
GoBeginner

Run a goroutine

Start concurrent work with the go keyword.

Purpose: Perform concurrent tasks.

Real-life example: Fetch multiple APIs in parallel.

go func() {
    fmt.Println("running in background")
}()
GoBeginner

Handle an error explicitly

Check errors immediately instead of ignoring them.

Purpose: Avoid silent failures.

Real-life example: Return an error from a file read.

result, err := doWork()
if err != nil {
    return err
}
RustBeginner

Borrow a value immutably

Pass a reference without giving up ownership.

Purpose: Share data without ownership transfer.

Real-life example: Print a string without moving it.

fn print_name(name: &str) {
    println!("{name}");
}
RustBeginner

Match an enum

Use match to handle every variant exhaustively.

Purpose: Handle all cases explicitly.

Real-life example: Process order status variants.

match status {
    Status::Ok => println!("ok"),
    Status::Error(msg) => println!("{msg}"),
}
JavaBeginner

Create a list with generics

Use generics to keep collections type-safe.

Purpose: Type-safe collections.

Real-life example: Store user names in a list.

List<String> names = new ArrayList<>();
names.add("Ada");
JavaBeginner

Use a record

Model immutable data with minimal boilerplate.

Purpose: Concise immutable data.

Real-life example: Represent a point or user.

public record User(String name, int age) {}
C#Beginner

Use a primary constructor

Initialize properties directly in the class declaration.

Purpose: Reduce boilerplate.

Real-life example: Define a user model quickly.

public class User(string name, int age);
C#Beginner

Filter a collection with LINQ

Query in-memory data with a readable expression.

Purpose: Query collections fluently.

Real-life example: Filter adults from a list.

var adults = people.Where(p => p.Age >= 18).ToList();
PHPBeginner

Read request input safely

Validate and sanitize user input before using it.

Purpose: Prevent injection and invalid data.

Real-life example: Validate an email from a form.

$email = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);
PHPBeginner

Use an associative array

Store named values in a simple key-value map.

Purpose: Store named values.

Real-life example: Represent a user profile.

$user = ["name" => "Ada", "role" => "admin"];
RubyBeginner

Iterate with each

Run a block for every element in a collection.

Purpose: Process collections cleanly.

Real-life example: Print all names.

names.each do |name|
  puts name
end
RubyBeginner

Use a hash with a default

Avoid nil checks when a key is missing.

Purpose: Simplify counting.

Real-life example: Count page views.

counts = Hash.new(0)
counts[:visits] += 1