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)];Small, reusable recipes for common programming tasks. Search by problem, language, or code.
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)];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;
}, {});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";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),
]);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);
};
}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();
}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))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"))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)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)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 defaultsSort 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"]))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;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;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;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;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
);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 443Find 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.logRepeat 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'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}'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-changeBisect 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 resetStash 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 popUse 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];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;
}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")
}()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
}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}");
}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}"),
}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");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) {}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);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();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);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"];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
endAvoid nil checks when a key is missing.
Purpose: Simplify counting.
Real-life example: Count page views.
counts = Hash.new(0)
counts[:visits] += 1