Code prompts: a ready task for every language

Sixteen briefs you can hand to an AI code generator as they are. Each one already names the language and version, says whether a framework is involved and how thoroughly errors should be handled. Put in your own field names and read the code.

Functions and utilities

The small utility functions you end up writing again in every project: generate a URL slug from a headline, format an amount as currency, validate a form field, and count working days between two dates.

URL slug from a headline

Turns an article title into a clean address: lowercase, hyphens, nothing a browser has to escape.

Prompt

Write a JavaScript function that turns an article headline into a URL slug: lowercase, spaces become hyphens, accents are stripped, punctuation is dropped, and a hyphen never sits at either end. No dependencies.

Result

export function slugify(title) { // normalisation splits an accented letter in two, and the accent is dropped — in a URL it would only become %C3 noise const base = title.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase() return base.replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "")}

Format an amount as money

Thousands separator, two decimals and the currency — with the rounding done before the formatting, not after.

Prompt

Write a Python function that renders a Decimal as money in US format: 1234.5 becomes 1,234.50 USD. Round to cents first and never on a float, and let the caller pass a different currency code.

Result

def format_money(amount: Decimal, currency: str = "USD") -> str: # quantise to cents before formatting — on a float the last cent goes missing value = amount.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) return locale.format_string("%.2f", value, grouping=True) + " " + currency

Validate a form field

A regular expression for the email and the phone, plus the one-line check that actually uses it.

Prompt

Write regular expressions that validate an email address and a US phone number in a sign-up form, with a short check function for each. Walk me through what every part of the pattern matches so I can adjust it.

Result

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[a-z]+$/i// the browser only checks the shape; whether the address exists is what the confirmation email is forexport const isEmail = (value) => EMAIL_RE.test(value.trim().toLowerCase())

Working days between two dates

Weekends and public holidays taken out, and an exception for dates handed over the wrong way round.

Prompt

Write a PHP 8.3 function that counts working days between two dates: skip Saturdays, Sundays and any date in a holidays array. Throw if the end date is earlier than the start date.

Result

function workingDays(DateTimeImmutable $from, DateTimeImmutable $to, array $holidays = []): int{ $period = new DatePeriod($from, new DateInterval("P1D"), $to); $isWork = fn (DateTimeImmutable $d) => (int) $d->format("N") < 6 && !in_array($d->format("Y-m-d"), $holidays, true); return count(array_filter(iterator_to_array($period), $isWork));}

Data and APIs

Talking to someone else's service and to your own database: call an API so a timeout is retried rather than lost, parse a messy CSV import, write a report query that groups and sorts, and page an endpoint.

API call with retries

A timeout, a retry on 5xx and a hard stop — so one slow service cannot hang the whole request.

Prompt

Write a TypeScript function that calls an HTTP API with a four-second timeout and up to three attempts. Retry only on 5xx and network errors, never on 4xx, pause between attempts, and throw a typed error once the attempts run out.

Result

export async function fetchWithRetry(url: string, tries = 3): Promise<Response> { const res = await fetch(url, { signal: AbortSignal.timeout(4000) }) if (res.ok || res.status < 500 || tries === 1) return res await new Promise((r) => setTimeout(r, 400)) return fetchWithRetry(url, tries - 1)}

Import a messy CSV

Reads a supplier price list and puts the broken rows in a file of their own instead of failing.

Prompt

Write a Python script with pandas that imports a supplier price list from CSV: prices arrive as text and some rows have none at all. Put the bad rows in rejected.csv, drop duplicates by order_id and keep the rest.

Result

orders = pd.read_csv("orders.csv", sep=",", decimal=".", on_bad_lines="warn")orders["total"] = pd.to_numeric(orders["total"], errors="coerce")bad = orders["total"].isna()orders.loc[bad].to_csv("rejected.csv", index=False)clean = orders.loc[~bad].drop_duplicates(subset="order_id")

A report query

Revenue by customer and by month, written against the schema you paste into the data field.

Prompt

Write a PostgreSQL query for the schema above: revenue by customer by month for the last year, largest first, with customers who never ordered left out.

Result

SELECT c.name, date_trunc('month', o.created_at) AS month, sum(o.total) AS revenueFROM orders oJOIN customers c ON c.id = o.customer_idWHERE o.created_at >= now() - interval '1 year'GROUP BY 1, 2ORDER BY revenue DESC

A paginated endpoint

Cursor pagination — the kind that does not repeat rows when new ones arrive mid-scroll.

Prompt

Write a TypeScript function on Prisma that returns a page of published posts with cursor pagination: twenty at a time, newest first, plus a nextCursor the client sends back for the following page.

Result

const page = await prisma.post.findMany({ where: { published: true }, orderBy: { createdAt: "desc" }, cursor: cursorId ? { id: cursorId } : undefined, take: 20,})

Interface

The parts of a screen that are really code: a React component built around a custom hook, a responsive card grid that still holds together on a phone, and a list screen for a mobile app with real data.

A React hook

Holds the search input back so the list is not refetched on every keystroke.

Prompt

Write a typed React hook that debounces a value by 300 ms and clears its timer on unmount, plus two lines showing how a search field uses it.

Result

export function useDebounced(value: string, delay = 300) { const [out, setOut] = useState(value) useEffect(() => { const id = setTimeout(() => setOut(value), delay) return () => clearTimeout(id) }, [value, delay]) return out}

A responsive card grid

Catalogue cards that go from four columns to one without a single media query.

Prompt

Write the CSS for a catalogue card grid: cards no narrower than 260px, the row filled edge to edge, 16px gaps, no media queries. BEM class names.

Result

.catalog__grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 16px;}

A mobile list screen

A scrolling list of orders in Jetpack Compose, with a tap on a row and an empty state.

Prompt

Write a Jetpack Compose screen with a scrollable list of orders: each row shows the number, the date and the total, a tap opens the order, and an empty state shows when there is nothing to list.

Result

@Composablefun OrderList(orders: List<Order>) { LazyColumn { items(orders) { order -> OrderRow(order, onClick = { openOrder(order.id) }) } }}

Scripts and automation

Code that runs while you sleep. A Python automation script you can leave alone, a shell script for a nightly database backup, a command-line tool for one job, and a cron entry that reports when it fails.

Nightly database backup

Dumps the database, names the file by date and deletes anything older than a month.

Prompt

Write a Bash script that dumps a PostgreSQL database into /backup with the date in the filename, deletes dumps older than 30 days and stops on the first error. ShellCheck-clean.

Result

#!/usr/bin/env bashset -euo pipefailstamp=$(date +%F)pg_dump --format=custom "$DATABASE_URL" > "/backup/db-$stamp.dump"find /backup -name "db-*.dump" -mtime +30 -delete

A command-line tool

A one-off utility that walks a folder and renames the files in it by rule.

Prompt

Write a Go command-line tool that walks a folder and renames photos to the date they were taken. Take the folder as a flag, print what would change unless --apply is given, and use the standard library only.

Result

func main() { dir := flag.String("dir", ".", "folder with the photos") flag.Parse() if err := filepath.WalkDir(*dir, renameByShootDate); err != nil { log.Fatal(err) }}

A job on a schedule

Wakes up at seven on weekdays, pulls yesterday's numbers and mails them out.

Prompt

Write a Node.js job that runs at 07:00 on weekdays, pulls yesterday's sales out of PostgreSQL, renders them as an HTML table and emails it to the sales team. Log failures and never crash the process.

Result

// 07:00 on weekdays — the numbers have to be on the desk before standupcron.schedule("0 7 * * 1-5", async () => { const rows = await db.query(DAILY_SALES_SQL) await mailer.send({ to: "sales@acme.com", subject: "Yesterday in sales", html: render(rows) })})

Tests

Coverage for code that already exists: write unit tests for a function with the edge cases people quietly skip when they do it by hand, and cover an API endpoint including the responses nobody returns on purpose.

Tests for a function

pytest with parametrised cases: zero, a negative amount and None.

Prompt

Write pytest tests for a format_money(amount, currency) function: zero, a large amount, a negative one, two decimal places, and a TypeError when None comes in. Use parametrize.

Result

@pytest.mark.parametrize("amount,expected", [("0", "0.00"), ("1234.5", "1,234.50")])def test_format_money(amount, expected): assert format_money(Decimal(amount)) == expecteddef test_format_money_rejects_none(): with pytest.raises(TypeError): format_money(None)

Tests for an endpoint

JUnit tests for GET and POST, the 404 and the validation error included.

Prompt

Write JUnit 5 tests for the REST endpoint /api/orders: 200 with a body for an existing order, 404 for an unknown id, 400 for a malformed payload. Assert on the JSON fields, not only on the status.

Result

@Testvoid returnsNotFoundForUnknownOrder() throws Exception { mockMvc.perform(get("/api/orders/0")) .andExpect(status().isNotFound()) .andExpect(jsonPath("$.error").value("order_not_found"));}

AI code generator prompts: 16 ready-made tasks | iBro