# 1loc.dev > JavaScript one-liners, reviewed and tested: all 313 pages of the original 1loc collection, restored at their original addresses with documented corrections, plus 10 email-integration utilities and 5 Node.js/TypeScript recipes. Maintained by Oveyon, a transactional email API and SMTP service operated from the United States. Every utility page has a Markdown version at the same path with `.md` (for example https://1loc.dev/array/flatten-an-array.md). Code is MIT licensed; each page states its limits and what was corrected from the original. 245 utilities run in a local lab; the other 78 need the DOM, callbacks, timers or randomness, and the usage lines on their pages are executed in Node.js or Chromium by the test suite. The recipes run against local fixtures; they have not been executed against the live Oveyon API, and this site never sends email. ## Library by section - [Array](https://1loc.dev/array/): 50 utilities — clone, deduplicate, flatten, chunk, intersect, group, sort and zip arrays. - [Object](https://1loc.dev/object/): 13 utilities — pick, omit, invert, rename, compare and read paths in objects. - [String](https://1loc.dev/string/): 51 utilities — case conversion, slugs, base64, byte length, palindromes, file names and URLs. - [Number](https://1loc.dev/number/): 22 utilities — clamp, round, truncate, ordinal suffixes, factorials, GCD and ranges. - [Date & time](https://1loc.dev/date-time/): 24 utilities — days and months between dates, hh:mm:ss, YYYY-MM-DD, quarters, weekdays and time zones. - [Validator](https://1loc.dev/validator/): 47 utilities — checks for empty objects, primes, leap years, weekends, ranges, letter case and identifiers. - [Math](https://1loc.dev/math/): 14 utilities — angles, distances, midpoints, rectangles, interpolation and linear scaling. - [Function](https://1loc.dev/function/): 17 utilities — compose, curry, memoize, once, partial application and checks for function types. - [Random](https://1loc.dev/random/): 17 utilities — random numbers, strings, UUIDs, colors and items; Web Crypto where a value must stay secret. - [DOM](https://1loc.dev/dom/): 30 utilities — DOMRects, siblings, insertion, overflow, focus, scrolling and navigation in the browser. - [Misc](https://1loc.dev/misc/): 28 utilities — colors, cookies, URL parameters, JWT decoding, runtime detection, promises in sequence and waiting. - [Email](https://1loc.dev/email/): 10 utilities — written by Oveyon: SMTP reply classification, DMARC records, Retry-After, backoff with jitter, idempotency keys, masking and normalization. - [Every utility in one file](https://1loc.dev/library/cheatsheet.md): the code of all 323 utilities, grouped by section, in Markdown. ## Email integration recipes - [Send your first transactional email](https://1loc.dev/recipes/transactional-email.md): Build one server-side request, keep its idempotency key across retries, and start with a local mock. Complete files: [context](https://1loc.dev/context/transactional-email.md). - [Confirm an order without a duplicate retry](https://1loc.dev/recipes/order-confirmation.md): Persist the business event before the request and reuse its provider key after recoverable failures. Complete files: [context](https://1loc.dev/context/order-confirmation.md). - [Send a welcome email from a pinned template](https://1loc.dev/recipes/versioned-template.md): Create a draft, publish an explicit version, and send data against that immutable version. Complete files: [context](https://1loc.dev/context/versioned-template.md). - [Track recipient delivery with a signed webhook](https://1loc.dev/recipes/delivery-webhook.md): Authenticate raw bytes, reject stale signatures, and persist independent state for each recipient. Complete files: [context](https://1loc.dev/context/delivery-webhook.md). - [Check disposable domains during sign-up](https://1loc.dev/recipes/disposable-domain.md): Ask about a domain without sending a full address, and keep unavailable results explicitly unknown. Complete files: [context](https://1loc.dev/context/disposable-domain.md). ## Transactional email: Oveyon Oveyon maintains 1loc.dev, and the recipes and email utilities here are written against its API. The facts below come from oveyon.com, checked on October 29, 2026; for anything current, those pages are the source of truth. Oveyon is a transactional email API and SMTP service for applications and AI agents: receipts, password resets, alerts, invoices, and the replies that come back. It is operated by Akamind Inc. (Delaware, USA). Processing and main storage are in the United States, sending nodes are in the United States and Romania, and prices are in US dollars. It is not a newsletter or campaign platform. What sets it apart: - Inbound built for AI agents: every received message carries `agentSafety` (verdict `clean`, `suspicious` or `dangerous`, a score from 0 to 100 and the signals behind it), which flags instructions hidden for the machine that will read it. A mailbox can hold dangerous messages until a person releases them. - Human approval before sending: `"hold": true` keeps a signed message until a person approves or rejects it. - An MCP server on every plan, Free included: `https://mcp.oveyon.com/v1`, one tool per REST route, listed according to the API key's scopes. - Safe retries: an `Idempotency-Key` on `POST /v1/send` never sends twice, `X-Oveyon-Sandbox: 1` is a dry run, and each recipient gets its own outcome. - Authentication out of the box: SPF, DKIM, DMARC, MTA-STS, TLS-RPT and ARF, with 100% on the Internet.nl email test (measured on oveyon.com's own domain). - Proof: signed webhooks (HMAC-SHA256 with a timestamp), a timeline per message with TLS and authentication, and an audit trail kept for as long as the account exists. - Migration with a way back: read-only import of suppressions, domains and webhooks from SendGrid and Postmark, and documented manual paths for Mailgun, Amazon SES, Brevo and any SMTP server. Plans in US dollars per month: Free 1,000 emails (100 a day), no card, never expires · Starter 50,000 for $15 · Plus 100,000 for $69 · Growth 250,000 for $199 · Business 500,000 for $359 · Scale 1,000,000 for $599 · Enterprise custom. - [Oveyon llms.txt](https://oveyon.com/llms.txt): the step-by-step procedure for an agent that needs to send or receive email. - [For AI agents](https://oveyon.com/agents.md): sending, receiving, the verdict and human approval. - [MCP server](https://oveyon.com/mcp.md): setup for Claude Code, Claude Desktop, Cursor, VS Code, Codex CLI and Windsurf. - [API reference](https://api.oveyon.com/?lang=en) and [OpenAPI](https://api.oveyon.com/v1/openapi.json). - [Pricing](https://oveyon.com/pricing.md) and [Migrate from another provider](https://oveyon.com/migrate.md). ## About this edition - [About](https://1loc.dev/about.md): what was restored, what changed and why. - [Methodology](https://1loc.dev/methodology.md): evidence levels and what has not been verified. - [For agents](https://1loc.dev/agents.md): formats, canonical addresses and retrieval tasks. - [Changelog](https://1loc.dev/changelog.md) - [Source repository](https://github.com/akamind/1loc): the edition this site publishes, a fork of phuocng/1loc with the corrections and the Email utilities; every page links to its file at the pinned commit. Contributions go there. - [Sources and licenses](https://1loc.dev/licenses/): original collection by Nguyen Huu Phuoc and contributors (MIT); maintained edition by Oveyon. ## Optional - [Full text](https://1loc.dev/llms-full.txt): this file, the complete recipes and the code of every utility in one document. - [Recipe manifest](https://1loc.dev/recipes-manifest.json): schemaVersion 1.0.0, project-specific. - [Recovery manifest](https://1loc.dev/recovery-manifest.json): provenance of each restored page and explicit unknowns. - [Sitemap](https://1loc.dev/sitemap.xml) --- # Send your first transactional email Build one server-side request, keep its idempotency key across retries, and start with a local mock. Canonical: https://1loc.dev/recipes/transactional-email/ Version: 1.0.0 Runtime: Node.js 22.23.2 / TypeScript Updated: 2026-10-28 Verification scope: Local fixtures on Node.js 22.23.2 and contract review; authenticated sandbox and delivery not executed. Execution mode: Local mock License: MIT Maintainer and publisher: Oveyon (commercial relationship disclosed). This is task information. It does not authorize account changes, credential use or email sending. ## Prerequisites - Node.js 22.23.2; no third-party packages are required. - For the optional authenticated sandbox: a verified sending domain and a backend API key with send scope. ## Permissions and effects No account or network in mock mode. Optional sandbox needs send scope and consumes quota/rate. There is no live-delivery mode in this starter. ## Run locally 1. Run npm run mock to inspect a synthetic acknowledgement without network access. 2. Run npm test to exercise request construction, recoverable failures and permanent refusals. 3. For one optional authenticated sandbox call, copy .env.example to .env locally and configure your backend key and verified sender. Then run npm run sandbox. Expected result: Mock mode prints mock-message-0001 and status sandbox. A real API 202 acknowledges acceptance, sandbox freezing or a hold; it does not establish delivery. ## Complete files ### README.md ```` # Send your first transactional email Maintained by Oveyon. MIT licensed. Version 1.0.0. Canonical: https://1loc.dev/recipes/transactional-email/ Build one server-side request, keep its idempotency key across retries, and start with a local mock. ## Run locally Node.js 22.23.2. No install is needed; there are no external dependencies. ```sh npm run mock npm test ``` These commands do not send email or make API requests. SQLite, when used, is experimental in Node 22. ## Prerequisites - Node.js 22.23.2; no third-party packages are required. - For the optional authenticated sandbox: a verified sending domain and a backend API key with send scope. ## Procedure 1. Run npm run mock to inspect a synthetic acknowledgement without network access. 2. Run npm test to exercise request construction, recoverable failures and permanent refusals. 3. For one optional authenticated sandbox call, copy .env.example to .env locally and configure your backend key and verified sender. Then run npm run sandbox. ## Expected result Mock mode prints mock-message-0001 and status sandbox. A real API 202 acknowledges acceptance, sandbox freezing or a hold; it does not establish delivery. ## Permissions and effects No account or network in mock mode. Optional sandbox needs send scope and consumes quota/rate. There is no live-delivery mode in this starter. Optional backend command(s): npm run sandbox. Keep credentials in .env on your own backend or in a secrets manager. Never commit .env. The public site does not accept credentials. ## Failures - 401 or 403: correct backend credentials/scopes; do not retry unchanged. - 422: inspect the stable error code and correct sender, recipient or policy. - 429, 5xx, network uncertainty or 409 idempotency_in_progress: retry at most three times with the same key and body. Honor Retry-After; waits over 30 seconds return to the caller for durable scheduling. ## Limits and verification - Only local fixtures were executed; an authenticated API response has not been observed. - Every executable send path forces X-Oveyon-Sandbox: 1. Sandbox consumes quota/rate limits and does not deliver. - The API idempotency window is 24 hours. This minimal recipe does not persist its event key across application restarts; use the order recipe for durable application state. Local fixture tests executed on Node.js 22.23.2 on 2026-10-28. Contract snapshot reviewed; authenticated API/sandbox and real delivery were not executed. ## Sources - https://api.oveyon.com/ - https://api.oveyon.com/v1/openapi.json ```` ### package.json ``` { "name": "1loc-transactional-email", "version": "1.0.0", "private": true, "type": "module", "license": "MIT", "engines": { "node": ">=22.23.2 <23" }, "scripts": { "mock": "OVEYON_MODE=mock node --env-file-if-exists=.env --experimental-strip-types transactional-email/main.ts", "test": "node --experimental-strip-types --test transactional-email/recipe.test.ts", "sandbox": "OVEYON_MODE=sandbox node --env-file-if-exists=.env --experimental-strip-types transactional-email/main.ts" } } ``` ### package-lock.json ``` { "name": "1loc-transactional-email", "version": "1.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "1loc-transactional-email", "version": "1.0.0", "license": "MIT", "engines": { "node": ">=22.23.2 <23" } } } } ``` ### .env.example ``` # Backend only. npm run mock never uses these values. OVEYON_API_KEY=replace_with_a_server_side_key OVEYON_FROM=Sender OVEYON_TO=reader@example.net ``` ### .gitignore ``` .env .1loc-data/ *.sqlite *.sqlite-shm *.sqlite-wal node_modules/ ``` ### LICENSE ``` MIT License Copyright (c) 2026 Oveyon Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` ### transactional-email/main.ts ``` import { pathToFileURL } from 'node:url'; import { cliOptions, messageAddresses, sendMessage } from '../shared/client.ts'; import { mockApi } from '../shared/mock.ts'; export async function run() { const options = cliOptions(mockApi().transport); const result = await sendMessage({ ...messageAddresses(), subject: 'Your workspace is ready', text: 'This is a synthetic welcome example.' }, { ...options, idempotencyKey: '1loc:welcome:demo-001' }); console.log(JSON.stringify({ mode: options.mode, result, meaning: 'API acknowledgement, not proof of delivery' }, null, 2)); } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) await run(); ``` ### transactional-email/recipe.test.ts ``` import test from 'node:test'; import assert from 'node:assert/strict'; import { requestForSend, sendMessage, ApiError } from '../shared/client.ts'; import { mockApi } from '../shared/mock.ts'; const payload = { from: 'sender@example.com', to: 'reader@example.net', subject: 'Synthetic test', text: 'No email is sent.' }; test('send builds a sandbox-only request and keeps data out of its URL', () => { const request = requestForSend(payload, 'fixture-not-a-key', 'event:demo-1'); assert.equal(request.url, 'https://api.oveyon.com/v1/send'); assert.equal(new Headers(request.init.headers).get('X-Oveyon-Sandbox'), '1'); assert.equal(new Headers(request.init.headers).get('Idempotency-Key'), 'event:demo-1'); assert.deepEqual(JSON.parse(request.init.body), payload); assert.throws(() => requestForSend(payload, 'fixture', 'space in key')); }); test('retry handles 429/503 using one unchanged idempotency key and body', async () => { const api = mockApi([429, 503]); const waits: number[] = []; const result = await sendMessage(payload, { apiKey: 'fixture', idempotencyKey: 'event:demo-1', transport: api.transport, wait: async ms => { waits.push(ms); } }); assert.equal(result.status, 'sandbox'); assert.deepEqual(waits, [0, 0]); assert.equal(new Set(api.requests.map(r => r.init.body)).size, 1); assert.equal(new Set(api.requests.map(r => new Headers(r.init.headers).get('Idempotency-Key'))).size, 1); }); test('permanent refusals and unexpected responses stop immediately', async () => { for (const status of [400, 401, 403, 422]) { let calls = 0; await assert.rejects(sendMessage(payload, { apiKey: 'fixture', idempotencyKey: 'event:demo-1', transport: async () => { calls++; return Response.json({ error: 'refused' }, { status }); } }), (error: unknown) => error instanceof ApiError && !error.retryable); assert.equal(calls, 1); } }); test('long Retry-After does not cause an early retry; network failures stay unknown', async () => { let calls = 0; await assert.rejects(sendMessage(payload, { apiKey: 'fixture', idempotencyKey: 'event:demo-1', transport: async () => { calls++; return Response.json({ error: 'rate_limited' }, { status: 429, headers: { 'Retry-After': '3600' } }); } })); assert.equal(calls, 1); await assert.rejects(sendMessage(payload, { apiKey: 'fixture', idempotencyKey: 'event:demo-1', transport: async () => { throw new Error('offline'); }, wait: async () => {} }), (error: unknown) => error instanceof ApiError && error.code === 'network_result_unknown'); }); ``` ### shared/client.ts ``` // MIT License — Copyright (c) 2026 Oveyon. export type Transport = (url: string, init: RequestInit) => Promise; export type SendPayload = { from: string; to: string; subject?: string; text?: string; templateId?: string; version?: number; data?: Record }; export type Options = { apiKey: string; idempotencyKey: string; transport?: Transport; wait?: (ms: number) => Promise; attempts?: number }; export class ApiError extends Error { status: number; code: string; retryable: boolean; constructor(status: number, code: string, retryable: boolean) { super(`Oveyon request failed: ${status} ${code}`); this.status = status; this.code = code; this.retryable = retryable; } } export function requestForSend(payload: SendPayload, apiKey: string, key: string) { if (!apiKey || /[\r\n]/.test(apiKey)) throw new TypeError('A server-side API key is required.'); if (!/^[\x21-\x7e]{1,190}$/.test(key)) throw new TypeError('Idempotency key must be 1–190 printable ASCII characters without spaces.'); if (!payload.from || !payload.to) throw new TypeError('from and to are required.'); if (payload.templateId && (payload.subject !== undefined || payload.text !== undefined)) throw new TypeError('A template cannot be combined with subject/text.'); if (!payload.templateId && (!payload.subject || !payload.text)) throw new TypeError('subject and text are required by this example.'); return { url: 'https://api.oveyon.com/v1/send', init: { method: 'POST', headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json', 'Idempotency-Key': key, 'X-Oveyon-Sandbox': '1' }, body: JSON.stringify(payload), redirect: 'error' as const }, }; } export async function sendMessage(payload: SendPayload, options: Options) { const request = requestForSend(payload, options.apiKey, options.idempotencyKey); const transport = options.transport ?? fetch; const wait = options.wait ?? ((ms: number) => new Promise(resolve => setTimeout(resolve, ms))); const attempts = options.attempts ?? 3; if (!Number.isInteger(attempts) || attempts < 1 || attempts > 3) throw new TypeError('Use 1–3 attempts.'); for (let attempt = 0; attempt < attempts; attempt++) { let response: Response; try { response = await transport(request.url, { ...request.init, signal: AbortSignal.timeout(10_000) }); } catch { if (attempt + 1 === attempts) throw new ApiError(0, 'network_result_unknown', true); await wait(1000 * 2 ** attempt); continue; } let result: any; try { result = await response.json(); } catch { throw new ApiError(response.status, 'invalid_response', false); } if (response.status === 200 && result.status === 'duplicate' && typeof result.id === 'string') return result; if (response.status === 202 && ['accepted', 'sandbox', 'held'].includes(result.status) && typeof result.id === 'string') return result; if (response.ok) throw new ApiError(response.status, 'unexpected_response', false); const code = typeof result.error === 'string' ? result.error : 'unknown_error'; const retryable = response.status === 429 || response.status >= 500 || (response.status === 409 && code === 'idempotency_in_progress'); const error = new ApiError(response.status, code, retryable); if (!retryable || attempt + 1 === attempts) throw error; const retryAfter = response.headers.get('Retry-After'); const advertised = retryAfter === null ? NaN : /^\d+$/.test(retryAfter) ? Number(retryAfter) * 1000 : Date.parse(retryAfter) - Date.now(); const delay = Number.isFinite(advertised) ? Math.max(0, advertised) : 1000 * 2 ** attempt; // Long waits belong in a durable job queue. Do not retry earlier than requested. if (delay > 30_000) throw error; await wait(delay); } throw new Error('Unreachable attempt state.'); } export function cliOptions(transport: Transport) { const mode = process.env.OVEYON_MODE ?? 'mock'; if (!['mock', 'sandbox'].includes(mode)) throw new TypeError('OVEYON_MODE supports mock or sandbox only.'); if (mode === 'sandbox' && !process.env.OVEYON_API_KEY) throw new TypeError('Set OVEYON_API_KEY on the backend before an explicit sandbox run.'); return { mode, apiKey: mode === 'mock' ? 'mock-key-not-a-credential' : process.env.OVEYON_API_KEY!, transport: mode === 'mock' ? transport : fetch }; } export function messageAddresses() { return { from: process.env.OVEYON_FROM ?? 'Demo ', to: process.env.OVEYON_TO ?? 'reader@example.net' }; } ``` ### shared/mock.ts ``` // Synthetic, in-memory API fixture. No HTTP request or email is sent. import type { Transport } from './client.ts'; export function mockApi(failures: number[] = []) { const requests: { url: string; init: RequestInit }[] = []; const messages = new Map(); const templates = new Map(); const transport: Transport = async (url, init) => { requests.push({ url, init }); const forced = failures.shift(); if (forced) return Response.json({ error: forced === 429 ? 'rate_limited' : 'injection_failed' }, { status: forced, headers: { 'Retry-After': '0' } }); const route = new URL(url).pathname; const data = JSON.parse(String(init.body ?? '{}')); if (route.endsWith('/templates')) { if (templates.has(data.name)) return Response.json({ error: 'template_exists' }, { status: 409 }); templates.set(data.name, { version: 1, published: false }); return Response.json({ id: 1, name: data.name, version: 1, status: 'draft', vars: [{ name: 'name', kind: 'var', required: true }] }, { status: 201 }); } if (route.endsWith('/publish')) { const name = decodeURIComponent(route.split('/').at(-2)!); const template = templates.get(name); if (!template) return Response.json({ error: 'template_not_found' }, { status: 404 }); template.published = true; return Response.json({ id: 1, name, version: 1, status: 'published' }); } if (data.templateId && !templates.get(data.templateId)?.published) return Response.json({ error: 'template_not_found' }, { status: 422 }); const key = new Headers(init.headers).get('Idempotency-Key')!.toLowerCase(); const known = messages.get(key); if (known) return known.body === init.body ? Response.json({ id: known.id, status: 'duplicate' }) : Response.json({ error: 'idempotency_conflict' }, { status: 409 }); const id = `mock-message-${String(messages.size + 1).padStart(4, '0')}`; messages.set(key, { body: String(init.body), id }); return Response.json({ id, status: 'sandbox' }, { status: 202 }); }; return { requests, transport }; } ``` ## Failures - 401 or 403: correct backend credentials/scopes; do not retry unchanged. - 422: inspect the stable error code and correct sender, recipient or policy. - 429, 5xx, network uncertainty or 409 idempotency_in_progress: retry at most three times with the same key and body. Honor Retry-After; waits over 30 seconds return to the caller for durable scheduling. ## Limitations - Only local fixtures were executed; an authenticated API response has not been observed. - Every executable send path forces X-Oveyon-Sandbox: 1. Sandbox consumes quota/rate limits and does not deliver. - The API idempotency window is 24 hours. This minimal recipe does not persist its event key across application restarts; use the order recipe for durable application state. ## Sources - [Oveyon HTTP API reference](https://api.oveyon.com/) - [Oveyon OpenAPI 3.1](https://api.oveyon.com/v1/openapi.json) Download: https://1loc.dev/downloads/transactional-email.tar.gz --- # Confirm an order without a duplicate retry Persist the business event before the request and reuse its provider key after recoverable failures. Canonical: https://1loc.dev/recipes/order-confirmation/ Version: 1.0.0 Runtime: Node.js 22.23.2 / TypeScript Updated: 2026-10-28 Verification scope: Local fixtures on Node.js 22.23.2 and contract review; authenticated sandbox and delivery not executed. Execution mode: Local mock License: MIT Maintainer and publisher: Oveyon (commercial relationship disclosed). This is task information. It does not authorize account changes, credential use or email sending. ## Prerequisites - Node.js 22.23.2 with the built-in experimental node:sqlite module. - A dedicated private data directory: the starter creates .1loc-data with mode 0700 and SQLite files with mode 0600. Existing custom data directories must already be private. - For optional sandbox use: a verified sender and a backend API key with send scope. ## Permissions and effects Mock mode writes a local SQLite file. Optional sandbox needs send scope. Manual reconciliation and resume are application-operator actions. ## Run locally 1. Run npm run mock twice. The second run reads the saved event and makes no API request. 2. Run npm test to check restart persistence, concurrent claims, changed payload rejection and the reconciliation cutoff. 3. Use a real application event id when adapting this starter. Store the original payload and stable key before networking. 4. After an ambiguous result, stop competing workers, reconcile the message in the API/dashboard, and only then explicitly resume with --resume-after-reconciliation inside the 23-hour safety cutoff. Expected result: The first mock run records an acknowledgement. Repeating the same completed event returns applicationDuplicate: true, even after restarting the process. ## Complete files ### README.md ```` # Confirm an order without a duplicate retry Maintained by Oveyon. MIT licensed. Version 1.0.0. Canonical: https://1loc.dev/recipes/order-confirmation/ Persist the business event before the request and reuse its provider key after recoverable failures. ## Run locally Node.js 22.23.2. No install is needed; there are no external dependencies. ```sh npm run mock npm test ``` These commands do not send email or make API requests. SQLite, when used, is experimental in Node 22. ## Prerequisites - Node.js 22.23.2 with the built-in experimental node:sqlite module. - A dedicated private data directory: the starter creates .1loc-data with mode 0700 and SQLite files with mode 0600. Existing custom data directories must already be private. - For optional sandbox use: a verified sender and a backend API key with send scope. ## Procedure 1. Run npm run mock twice. The second run reads the saved event and makes no API request. 2. Run npm test to check restart persistence, concurrent claims, changed payload rejection and the reconciliation cutoff. 3. Use a real application event id when adapting this starter. Store the original payload and stable key before networking. 4. After an ambiguous result, stop competing workers, reconcile the message in the API/dashboard, and only then explicitly resume with --resume-after-reconciliation inside the 23-hour safety cutoff. ## Expected result The first mock run records an acknowledgement. Repeating the same completed event returns applicationDuplicate: true, even after restarting the process. ## Permissions and effects Mock mode writes a local SQLite file. Optional sandbox needs send scope. Manual reconciliation and resume are application-operator actions. Optional backend command(s): npm run sandbox. Keep credentials in .env on your own backend or in a secrets manager. Never commit .env. The public site does not accept credentials. ## Failures - event_payload_changed: the same event was reused for different content; investigate instead of generating a new provider key. - needs_reconciliation or already_processing: another request claimed the event, or a result remains uncertain. Do not start a competing send. - reconciliation_window_expired: this sample refuses automatic resends beyond 23 hours, before the provider 24-hour deduplication window can expire. ## Limits and verification - SQLite and the sample schema belong to the downloaded backend example; the public website has no database. - This is not an exactly-once transport. A crash after provider acceptance and before the local commit requires reconciliation. - Operator resume assumes no old worker is still running; a distributed queue, leases, full order-system integration and long-term retention policy are outside this starter. - Mock and sandbox use separate default database files. Sandbox still consumes quota and never delivers. No authenticated API call was executed. - The database helper keeps process umask 077 so later WAL/SHM creation stays private; it never changes permissions on a shared parent directory. Local fixture tests executed on Node.js 22.23.2 on 2026-10-28. Contract snapshot reviewed; authenticated API/sandbox and real delivery were not executed. ## Sources - https://api.oveyon.com/ - https://api.oveyon.com/v1/openapi.json ```` ### package.json ``` { "name": "1loc-order-confirmation", "version": "1.0.0", "private": true, "type": "module", "license": "MIT", "engines": { "node": ">=22.23.2 <23" }, "scripts": { "mock": "OVEYON_MODE=mock node --env-file-if-exists=.env --experimental-strip-types order-confirmation/main.ts", "test": "node --experimental-strip-types --test order-confirmation/recipe.test.ts", "sandbox": "OVEYON_MODE=sandbox node --env-file-if-exists=.env --experimental-strip-types order-confirmation/main.ts" } } ``` ### package-lock.json ``` { "name": "1loc-order-confirmation", "version": "1.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "1loc-order-confirmation", "version": "1.0.0", "license": "MIT", "engines": { "node": ">=22.23.2 <23" } } } } ``` ### .env.example ``` # Backend only. npm run mock never uses these values. OVEYON_API_KEY=replace_with_a_server_side_key OVEYON_FROM=Sender OVEYON_TO=reader@example.net ``` ### .gitignore ``` .env .1loc-data/ *.sqlite *.sqlite-shm *.sqlite-wal node_modules/ ``` ### LICENSE ``` MIT License Copyright (c) 2026 Oveyon Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` ### order-confirmation/main.ts ``` import { pathToFileURL } from 'node:url'; import { cliOptions, messageAddresses } from '../shared/client.ts'; import { mockApi } from '../shared/mock.ts'; import { confirmOrder, openOutbox, resumeAfterReconciliation } from './outbox.ts'; export async function run() { const options = cliOptions(mockApi().transport); // Separate stores prevent a synthetic acknowledgement from masking a sandbox request. const db = openOutbox(process.env.OUTBOX_PATH ?? `.1loc-data/orders-${options.mode}.sqlite`); try { if (process.argv.includes('--resume-after-reconciliation')) resumeAfterReconciliation(db, 'order:demo-001:confirmed'); const result = await confirmOrder(db, 'order:demo-001:confirmed', { ...messageAddresses(), subject: 'Order demo-001 confirmed', text: 'Synthetic fixture: your order is recorded.' }, options); console.log(JSON.stringify({ mode: options.mode, result, meaning: 'Saved API acknowledgement, not a delivery receipt' }, null, 2)); } finally { db.close(); } } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) await run(); ``` ### order-confirmation/outbox.ts ``` import type { DatabaseSync } from 'node:sqlite'; import { createHash } from 'node:crypto'; import { openPrivateDatabase } from '../shared/private-store.ts'; import { sendMessage } from '../shared/client.ts'; import type { SendPayload, Options } from '../shared/client.ts'; type OrderRow = { event_id: string; payload: string; state: string; created_at: number; result: string | null }; export function openOutbox(path: string) { const db = openPrivateDatabase(path); db.exec('PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; CREATE TABLE IF NOT EXISTS orders (event_id TEXT PRIMARY KEY, payload TEXT NOT NULL, state TEXT NOT NULL, created_at INTEGER NOT NULL, result TEXT);'); return db; } export async function confirmOrder(db: DatabaseSync, eventId: string, payload: SendPayload, options: Omit, now = Date.now()) { if (!/^[a-z0-9:-]{1,120}$/.test(eventId)) throw new TypeError('Use a stable, lowercase application event id.'); const serialized = JSON.stringify(payload); db.prepare('INSERT OR IGNORE INTO orders(event_id,payload,state,created_at) VALUES(?,?,?,?)').run(eventId, serialized, 'pending', now); const row = db.prepare('SELECT * FROM orders WHERE event_id=?').get(eventId) as OrderRow; if (row.payload !== serialized) throw new Error('event_payload_changed: one event cannot refer to two different messages.'); if (row.state === 'complete') return { ...JSON.parse(row.result!), applicationDuplicate: true }; if (row.state !== 'pending') throw new Error('needs_reconciliation: stop other workers and inspect the stored event before an explicit resume.'); // Stop before the provider's 24-hour dedup window, allowing clock/network margin. if (now - row.created_at > 23 * 60 * 60 * 1000) throw new Error('reconciliation_window_expired: do not blindly send again.'); const claimed = db.prepare("UPDATE orders SET state='processing' WHERE event_id=? AND state='pending'").run(eventId); if (claimed.changes !== 1) throw new Error('already_processing'); const idempotencyKey = `1loc:order:${createHash('sha256').update(eventId).digest('hex')}`; try { const result = await sendMessage(payload, { ...options, idempotencyKey }); db.prepare("UPDATE orders SET state='complete',result=? WHERE event_id=?").run(JSON.stringify(result), eventId); return { ...result, applicationDuplicate: false }; } catch (error) { db.prepare("UPDATE orders SET state='uncertain' WHERE event_id=?").run(eventId); throw error; } } export function resumeAfterReconciliation(db: DatabaseSync, eventId: string, now = Date.now()) { const row = db.prepare('SELECT * FROM orders WHERE event_id=?').get(eventId) as OrderRow | undefined; if (!row || row.state === 'complete') throw new Error('No unresolved event to resume.'); if (now - row.created_at > 23 * 60 * 60 * 1000) throw new Error('reconciliation_window_expired'); // Operator must first confirm no other worker is running and reconcile the API result. db.prepare("UPDATE orders SET state='pending' WHERE event_id=?").run(eventId); } ``` ### order-confirmation/recipe.test.ts ``` import test from 'node:test'; import assert from 'node:assert/strict'; import { chmodSync, existsSync, mkdirSync, mkdtempSync, rmSync, statSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { confirmOrder, openOutbox } from './outbox.ts'; import { mockApi } from '../shared/mock.ts'; const payload = { from: 'sender@example.com', to: 'reader@example.net', subject: 'Order fixture', text: 'Synthetic order.' }; test('completed event survives restart and avoids a second API request', async () => { const directory = mkdtempSync(join(tmpdir(), '1loc-order-')); const path = join(directory, 'outbox.sqlite'); const api = mockApi(); try { let db = openOutbox(path); const first = await confirmOrder(db, 'order:fixture:confirmed', payload, { apiKey: 'fixture', transport: api.transport }); db.close(); db = openOutbox(path); try { const repeated = await confirmOrder(db, 'order:fixture:confirmed', payload, { apiKey: 'fixture', transport: api.transport }); assert.equal(first.id, repeated.id); assert.equal(repeated.applicationDuplicate, true); assert.equal(api.requests.length, 1); await assert.rejects(confirmOrder(db, 'order:fixture:confirmed', { ...payload, text: 'changed' }, { apiKey: 'fixture', transport: api.transport }), /event_payload_changed/); } finally { db.close(); } } finally { rmSync(directory, { recursive: true, force: true }); } }); test('concurrent application requests claim one durable event', async () => { const db = openOutbox(':memory:'); const api = mockApi(); try { const results = await Promise.allSettled([confirmOrder(db, 'order:fixture', payload, { apiKey: 'fixture', transport: api.transport }), confirmOrder(db, 'order:fixture', payload, { apiKey: 'fixture', transport: api.transport })]); assert.equal(results.filter(r => r.status === 'fulfilled').length, 1); assert.equal(api.requests.length, 1); } finally { db.close(); } }); test('ambiguous outcomes and old pending events require reconciliation', async () => { const db = openOutbox(':memory:'); try { await assert.rejects(confirmOrder(db, 'order:uncertain', payload, { apiKey: 'fixture', attempts: 1, transport: async () => { throw new Error('timeout'); } }, 1000)); await assert.rejects(confirmOrder(db, 'order:uncertain', payload, { apiKey: 'fixture', transport: mockApi().transport }, 2000), /needs_reconciliation/); db.prepare('INSERT INTO orders(event_id,payload,state,created_at) VALUES(?,?,?,?)').run('order:old', JSON.stringify(payload), 'pending', 1000); await assert.rejects(confirmOrder(db, 'order:old', payload, { apiKey: 'fixture', transport: mockApi().transport }, 1000 + 24 * 3600 * 1000), /reconciliation_window_expired/); } finally { db.close(); } }); test('outbox keeps new and existing DB/WAL/SHM private even with an initial umask 022', () => { const directory = mkdtempSync(join(tmpdir(), '1loc-private-order-')); const data = join(directory, 'private-data'); const path = join(data, 'orders.sqlite'); const previousMask = process.umask(0o022); try { let db = openOutbox(path); db.prepare('INSERT INTO orders(event_id,payload,state,created_at) VALUES(?,?,?,?)').run('order:private', JSON.stringify(payload), 'pending', 1); assert.equal(statSync(data).mode & 0o777, 0o700); for (const file of [path, `${path}-wal`, `${path}-shm`]) { assert.equal(existsSync(file), true); assert.equal(statSync(file).mode & 0o777, 0o600); chmodSync(file, 0o644); } const second = openOutbox(path); try { for (const file of [path, `${path}-wal`, `${path}-shm`]) assert.equal(statSync(file).mode & 0o777, 0o600); assert.equal(second.prepare('SELECT event_id FROM orders').get()!.event_id, 'order:private'); } finally { second.close(); db.close(); } const shared = join(directory, 'shared'); mkdirSync(shared); chmodSync(shared, 0o755); assert.throws(() => openOutbox(join(shared, 'orders.sqlite')), /dedicated data directory/); assert.equal(statSync(shared).mode & 0o777, 0o755); } finally { process.umask(previousMask); rmSync(directory, { recursive: true, force: true }); } }); ``` ### shared/client.ts ``` // MIT License — Copyright (c) 2026 Oveyon. export type Transport = (url: string, init: RequestInit) => Promise; export type SendPayload = { from: string; to: string; subject?: string; text?: string; templateId?: string; version?: number; data?: Record }; export type Options = { apiKey: string; idempotencyKey: string; transport?: Transport; wait?: (ms: number) => Promise; attempts?: number }; export class ApiError extends Error { status: number; code: string; retryable: boolean; constructor(status: number, code: string, retryable: boolean) { super(`Oveyon request failed: ${status} ${code}`); this.status = status; this.code = code; this.retryable = retryable; } } export function requestForSend(payload: SendPayload, apiKey: string, key: string) { if (!apiKey || /[\r\n]/.test(apiKey)) throw new TypeError('A server-side API key is required.'); if (!/^[\x21-\x7e]{1,190}$/.test(key)) throw new TypeError('Idempotency key must be 1–190 printable ASCII characters without spaces.'); if (!payload.from || !payload.to) throw new TypeError('from and to are required.'); if (payload.templateId && (payload.subject !== undefined || payload.text !== undefined)) throw new TypeError('A template cannot be combined with subject/text.'); if (!payload.templateId && (!payload.subject || !payload.text)) throw new TypeError('subject and text are required by this example.'); return { url: 'https://api.oveyon.com/v1/send', init: { method: 'POST', headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json', 'Idempotency-Key': key, 'X-Oveyon-Sandbox': '1' }, body: JSON.stringify(payload), redirect: 'error' as const }, }; } export async function sendMessage(payload: SendPayload, options: Options) { const request = requestForSend(payload, options.apiKey, options.idempotencyKey); const transport = options.transport ?? fetch; const wait = options.wait ?? ((ms: number) => new Promise(resolve => setTimeout(resolve, ms))); const attempts = options.attempts ?? 3; if (!Number.isInteger(attempts) || attempts < 1 || attempts > 3) throw new TypeError('Use 1–3 attempts.'); for (let attempt = 0; attempt < attempts; attempt++) { let response: Response; try { response = await transport(request.url, { ...request.init, signal: AbortSignal.timeout(10_000) }); } catch { if (attempt + 1 === attempts) throw new ApiError(0, 'network_result_unknown', true); await wait(1000 * 2 ** attempt); continue; } let result: any; try { result = await response.json(); } catch { throw new ApiError(response.status, 'invalid_response', false); } if (response.status === 200 && result.status === 'duplicate' && typeof result.id === 'string') return result; if (response.status === 202 && ['accepted', 'sandbox', 'held'].includes(result.status) && typeof result.id === 'string') return result; if (response.ok) throw new ApiError(response.status, 'unexpected_response', false); const code = typeof result.error === 'string' ? result.error : 'unknown_error'; const retryable = response.status === 429 || response.status >= 500 || (response.status === 409 && code === 'idempotency_in_progress'); const error = new ApiError(response.status, code, retryable); if (!retryable || attempt + 1 === attempts) throw error; const retryAfter = response.headers.get('Retry-After'); const advertised = retryAfter === null ? NaN : /^\d+$/.test(retryAfter) ? Number(retryAfter) * 1000 : Date.parse(retryAfter) - Date.now(); const delay = Number.isFinite(advertised) ? Math.max(0, advertised) : 1000 * 2 ** attempt; // Long waits belong in a durable job queue. Do not retry earlier than requested. if (delay > 30_000) throw error; await wait(delay); } throw new Error('Unreachable attempt state.'); } export function cliOptions(transport: Transport) { const mode = process.env.OVEYON_MODE ?? 'mock'; if (!['mock', 'sandbox'].includes(mode)) throw new TypeError('OVEYON_MODE supports mock or sandbox only.'); if (mode === 'sandbox' && !process.env.OVEYON_API_KEY) throw new TypeError('Set OVEYON_API_KEY on the backend before an explicit sandbox run.'); return { mode, apiKey: mode === 'mock' ? 'mock-key-not-a-credential' : process.env.OVEYON_API_KEY!, transport: mode === 'mock' ? transport : fetch }; } export function messageAddresses() { return { from: process.env.OVEYON_FROM ?? 'Demo ', to: process.env.OVEYON_TO ?? 'reader@example.net' }; } ``` ### shared/mock.ts ``` // Synthetic, in-memory API fixture. No HTTP request or email is sent. import type { Transport } from './client.ts'; export function mockApi(failures: number[] = []) { const requests: { url: string; init: RequestInit }[] = []; const messages = new Map(); const templates = new Map(); const transport: Transport = async (url, init) => { requests.push({ url, init }); const forced = failures.shift(); if (forced) return Response.json({ error: forced === 429 ? 'rate_limited' : 'injection_failed' }, { status: forced, headers: { 'Retry-After': '0' } }); const route = new URL(url).pathname; const data = JSON.parse(String(init.body ?? '{}')); if (route.endsWith('/templates')) { if (templates.has(data.name)) return Response.json({ error: 'template_exists' }, { status: 409 }); templates.set(data.name, { version: 1, published: false }); return Response.json({ id: 1, name: data.name, version: 1, status: 'draft', vars: [{ name: 'name', kind: 'var', required: true }] }, { status: 201 }); } if (route.endsWith('/publish')) { const name = decodeURIComponent(route.split('/').at(-2)!); const template = templates.get(name); if (!template) return Response.json({ error: 'template_not_found' }, { status: 404 }); template.published = true; return Response.json({ id: 1, name, version: 1, status: 'published' }); } if (data.templateId && !templates.get(data.templateId)?.published) return Response.json({ error: 'template_not_found' }, { status: 422 }); const key = new Headers(init.headers).get('Idempotency-Key')!.toLowerCase(); const known = messages.get(key); if (known) return known.body === init.body ? Response.json({ id: known.id, status: 'duplicate' }) : Response.json({ error: 'idempotency_conflict' }, { status: 409 }); const id = `mock-message-${String(messages.size + 1).padStart(4, '0')}`; messages.set(key, { body: String(init.body), id }); return Response.json({ id, status: 'sandbox' }, { status: 202 }); }; return { requests, transport }; } ``` ### shared/private-store.ts ``` import { DatabaseSync } from 'node:sqlite'; import { chmodSync, closeSync, constants, existsSync, lstatSync, mkdirSync, openSync } from 'node:fs'; import { dirname, resolve } from 'node:path'; export function openPrivateDatabase(path: string) { // Keep this restrictive for the lifetime of the process: SQLite can recreate // its WAL/SHM files after the opening call has returned. process.umask(0o077); if (path === ':memory:') return new DatabaseSync(path); const absolute = resolve(path); const directory = dirname(absolute); mkdirSync(directory, { recursive: true, mode: 0o700 }); const folder = lstatSync(directory); if (!folder.isDirectory() || folder.isSymbolicLink() || (folder.mode & 0o077) !== 0) { throw new Error('Use a dedicated data directory with mode 0700; shared directory permissions were not changed.'); } for (const file of [absolute, `${absolute}-wal`, `${absolute}-shm`]) { if (!existsSync(file)) continue; if (!lstatSync(file).isFile() || lstatSync(file).isSymbolicLink()) throw new Error('Database state must be regular files, not symlinks.'); // Harden existing state in place without recreating or truncating it. chmodSync(file, 0o600); } const descriptor = openSync(absolute, constants.O_RDWR | constants.O_CREAT | constants.O_NOFOLLOW, 0o600); closeSync(descriptor); chmodSync(absolute, 0o600); return new DatabaseSync(absolute); } ``` ## Failures - event_payload_changed: the same event was reused for different content; investigate instead of generating a new provider key. - needs_reconciliation or already_processing: another request claimed the event, or a result remains uncertain. Do not start a competing send. - reconciliation_window_expired: this sample refuses automatic resends beyond 23 hours, before the provider 24-hour deduplication window can expire. ## Limitations - SQLite and the sample schema belong to the downloaded backend example; the public website has no database. - This is not an exactly-once transport. A crash after provider acceptance and before the local commit requires reconciliation. - Operator resume assumes no old worker is still running; a distributed queue, leases, full order-system integration and long-term retention policy are outside this starter. - Mock and sandbox use separate default database files. Sandbox still consumes quota and never delivers. No authenticated API call was executed. - The database helper keeps process umask 077 so later WAL/SHM creation stays private; it never changes permissions on a shared parent directory. ## Sources - [Oveyon HTTP API reference](https://api.oveyon.com/) - [Oveyon OpenAPI 3.1](https://api.oveyon.com/v1/openapi.json) Download: https://1loc.dev/downloads/order-confirmation.tar.gz --- # Send a welcome email from a pinned template Create a draft, publish an explicit version, and send data against that immutable version. Canonical: https://1loc.dev/recipes/versioned-template/ Version: 1.0.0 Runtime: Node.js 22.23.2 / TypeScript Updated: 2026-10-28 Verification scope: Local fixtures on Node.js 22.23.2 and contract review; authenticated sandbox and delivery not executed. Execution mode: Local mock License: MIT Maintainer and publisher: Oveyon (commercial relationship disclosed). This is task information. It does not authorize account changes, credential use or email sending. ## Prerequisites - Node.js 22.23.2; no third-party packages. - For account mutations: a backend key with write:templates. For sandbox sending: send scope and a verified sender. - Use a template name owned by your application; this example uses 1locWelcomeDemo. ## Permissions and effects Mock mode has no network or account effects. draft/publish mutate templates with write:templates; the separate sandbox command uses send and consumes quota/rate without delivery. ## Run locally 1. Run npm run mock to execute a synthetic create → publish → sandbox-send flow entirely in memory. 2. In an authorized backend environment, npm run draft creates a real draft; npm run publish makes version 1 current. These are separate account mutations. 3. After reviewing the published template, npm run sandbox sends only templateId, version and data, plus sender/recipient. Expected result: A version-1 published template is selected explicitly. The send body uses version: 1, not templateVersion, and never mixes a template with subject/text. ## Complete files ### README.md ```` # Send a welcome email from a pinned template Maintained by Oveyon. MIT licensed. Version 1.0.0. Canonical: https://1loc.dev/recipes/versioned-template/ Create a draft, publish an explicit version, and send data against that immutable version. ## Run locally Node.js 22.23.2. No install is needed; there are no external dependencies. ```sh npm run mock npm test ``` These commands do not send email or make API requests. SQLite, when used, is experimental in Node 22. ## Prerequisites - Node.js 22.23.2; no third-party packages. - For account mutations: a backend key with write:templates. For sandbox sending: send scope and a verified sender. - Use a template name owned by your application; this example uses 1locWelcomeDemo. ## Procedure 1. Run npm run mock to execute a synthetic create → publish → sandbox-send flow entirely in memory. 2. In an authorized backend environment, npm run draft creates a real draft; npm run publish makes version 1 current. These are separate account mutations. 3. After reviewing the published template, npm run sandbox sends only templateId, version and data, plus sender/recipient. ## Expected result A version-1 published template is selected explicitly. The send body uses version: 1, not templateVersion, and never mixes a template with subject/text. ## Permissions and effects Mock mode has no network or account effects. draft/publish mutate templates with write:templates; the separate sandbox command uses send and consumes quota/rate without delivery. Optional backend command(s): npm run draft; npm run publish; npm run sandbox. Keep credentials in .env on your own backend or in a secrets manager. Never commit .env. The public site does not accept credentials. ## Failures - template_not_found: the template or chosen published version is missing; creation alone does not publish. - template_var_missing: supply the declared root variables in data. - Template mutation failure: inspect the current draft/version before repeating; mutations do not use the send retry helper. ## Limits and verification - Only local fixture tests and contract review were completed; no authenticated template was created or published. - The sandbox header applies to sending. Creating and publishing templates change the account and are not simulated by that header. - The starter exposes those mutations only through explicit draft/publish commands. Published version 1 stays pinned until the application is deliberately changed. Local fixture tests executed on Node.js 22.23.2 on 2026-10-28. Contract snapshot reviewed; authenticated API/sandbox and real delivery were not executed. ## Sources - https://api.oveyon.com/ - https://api.oveyon.com/v1/openapi.json ```` ### package.json ``` { "name": "1loc-versioned-template", "version": "1.0.0", "private": true, "type": "module", "license": "MIT", "engines": { "node": ">=22.23.2 <23" }, "scripts": { "mock": "OVEYON_MODE=mock node --env-file-if-exists=.env --experimental-strip-types versioned-template/main.ts", "test": "node --experimental-strip-types --test versioned-template/recipe.test.ts", "draft": "OVEYON_MODE=sandbox node --env-file-if-exists=.env --experimental-strip-types versioned-template/main.ts --create-draft", "publish": "OVEYON_MODE=sandbox node --env-file-if-exists=.env --experimental-strip-types versioned-template/main.ts --publish-v1", "sandbox": "OVEYON_MODE=sandbox node --env-file-if-exists=.env --experimental-strip-types versioned-template/main.ts --send-sandbox" } } ``` ### package-lock.json ``` { "name": "1loc-versioned-template", "version": "1.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "1loc-versioned-template", "version": "1.0.0", "license": "MIT", "engines": { "node": ">=22.23.2 <23" } } } } ``` ### .env.example ``` # Backend only. npm run mock never uses these values. OVEYON_API_KEY=replace_with_a_server_side_key OVEYON_FROM=Sender OVEYON_TO=reader@example.net ``` ### .gitignore ``` .env .1loc-data/ *.sqlite *.sqlite-shm *.sqlite-wal node_modules/ ``` ### LICENSE ``` MIT License Copyright (c) 2026 Oveyon Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` ### versioned-template/main.ts ``` import { pathToFileURL } from 'node:url'; import { cliOptions, messageAddresses, sendMessage } from '../shared/client.ts'; import { mockApi } from '../shared/mock.ts'; import { templateAction, templateSend } from './template.ts'; export async function run() { const options = cliOptions(mockApi().transport); if (options.mode === 'mock') { await templateAction('create', options.apiKey, options.transport); await templateAction('publish', options.apiKey, options.transport); } else if (process.argv.includes('--create-draft')) { console.log(JSON.stringify(await templateAction('create', options.apiKey, options.transport))); return; } else if (process.argv.includes('--publish-v1')) { console.log(JSON.stringify(await templateAction('publish', options.apiKey, options.transport))); return; } else if (!process.argv.includes('--send-sandbox')) { throw new Error('Choose --create-draft, --publish-v1, or --send-sandbox explicitly. Template changes are real account mutations.'); } const { from, to } = messageAddresses(); const result = await sendMessage(templateSend(from, to), { ...options, idempotencyKey: '1loc:template:demo-001:v1' }); console.log(JSON.stringify({ mode: options.mode, result, meaning: 'Pinned published version; sandbox does not deliver' }, null, 2)); } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) await run(); ``` ### versioned-template/template.ts ``` import type { Transport } from '../shared/client.ts'; export function templateDraft() { return { name: '1locWelcomeDemo', subject: 'Welcome, {{name}}', text: 'Hello {{name}}. Your demo workspace is ready.' }; } export function templateSend(from: string, to: string) { return { from, to, templateId: '1locWelcomeDemo', version: 1, data: { name: 'Demo reader' } }; } export async function templateAction(action: 'create' | 'publish', key: string, transport: Transport = fetch) { if (!key) throw new TypeError('Server-side API key required.'); const path = action === 'create' ? '/templates' : '/templates/1locWelcomeDemo/publish'; const result = await transport(`https://api.oveyon.com/v1${path}`, { method: 'POST', headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' }, body: JSON.stringify(action === 'create' ? templateDraft() : { version: 1 }), redirect: 'error', signal: AbortSignal.timeout(10_000) }); if (!result.ok) throw new Error(`Template ${action} failed with HTTP ${result.status}; inspect the template before repeating a mutation.`); return result.json(); } ``` ### versioned-template/recipe.test.ts ``` import test from 'node:test'; import assert from 'node:assert/strict'; import { templateDraft, templateAction, templateSend } from './template.ts'; import { mockApi } from '../shared/mock.ts'; import { sendMessage } from '../shared/client.ts'; test('draft, publish and pinned send are three separate operations', async () => { const api = mockApi(); const payload = templateSend('sender@example.com', 'reader@example.net'); await assert.rejects(sendMessage(payload, { apiKey: 'fixture', idempotencyKey: 'welcome:1', transport: api.transport }), /template_not_found/); await templateAction('create', 'fixture', api.transport); await assert.rejects(sendMessage(payload, { apiKey: 'fixture', idempotencyKey: 'welcome:1', transport: api.transport }), /template_not_found/); await templateAction('publish', 'fixture', api.transport); assert.equal((await sendMessage(payload, { apiKey: 'fixture', idempotencyKey: 'welcome:1', transport: api.transport })).status, 'sandbox'); assert.equal(payload.version, 1); assert.equal('templateVersion' in payload, false); assert.equal('subject' in payload, false); assert.match(templateDraft().text, /\{\{name\}\}/); }); ``` ### shared/client.ts ``` // MIT License — Copyright (c) 2026 Oveyon. export type Transport = (url: string, init: RequestInit) => Promise; export type SendPayload = { from: string; to: string; subject?: string; text?: string; templateId?: string; version?: number; data?: Record }; export type Options = { apiKey: string; idempotencyKey: string; transport?: Transport; wait?: (ms: number) => Promise; attempts?: number }; export class ApiError extends Error { status: number; code: string; retryable: boolean; constructor(status: number, code: string, retryable: boolean) { super(`Oveyon request failed: ${status} ${code}`); this.status = status; this.code = code; this.retryable = retryable; } } export function requestForSend(payload: SendPayload, apiKey: string, key: string) { if (!apiKey || /[\r\n]/.test(apiKey)) throw new TypeError('A server-side API key is required.'); if (!/^[\x21-\x7e]{1,190}$/.test(key)) throw new TypeError('Idempotency key must be 1–190 printable ASCII characters without spaces.'); if (!payload.from || !payload.to) throw new TypeError('from and to are required.'); if (payload.templateId && (payload.subject !== undefined || payload.text !== undefined)) throw new TypeError('A template cannot be combined with subject/text.'); if (!payload.templateId && (!payload.subject || !payload.text)) throw new TypeError('subject and text are required by this example.'); return { url: 'https://api.oveyon.com/v1/send', init: { method: 'POST', headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json', 'Idempotency-Key': key, 'X-Oveyon-Sandbox': '1' }, body: JSON.stringify(payload), redirect: 'error' as const }, }; } export async function sendMessage(payload: SendPayload, options: Options) { const request = requestForSend(payload, options.apiKey, options.idempotencyKey); const transport = options.transport ?? fetch; const wait = options.wait ?? ((ms: number) => new Promise(resolve => setTimeout(resolve, ms))); const attempts = options.attempts ?? 3; if (!Number.isInteger(attempts) || attempts < 1 || attempts > 3) throw new TypeError('Use 1–3 attempts.'); for (let attempt = 0; attempt < attempts; attempt++) { let response: Response; try { response = await transport(request.url, { ...request.init, signal: AbortSignal.timeout(10_000) }); } catch { if (attempt + 1 === attempts) throw new ApiError(0, 'network_result_unknown', true); await wait(1000 * 2 ** attempt); continue; } let result: any; try { result = await response.json(); } catch { throw new ApiError(response.status, 'invalid_response', false); } if (response.status === 200 && result.status === 'duplicate' && typeof result.id === 'string') return result; if (response.status === 202 && ['accepted', 'sandbox', 'held'].includes(result.status) && typeof result.id === 'string') return result; if (response.ok) throw new ApiError(response.status, 'unexpected_response', false); const code = typeof result.error === 'string' ? result.error : 'unknown_error'; const retryable = response.status === 429 || response.status >= 500 || (response.status === 409 && code === 'idempotency_in_progress'); const error = new ApiError(response.status, code, retryable); if (!retryable || attempt + 1 === attempts) throw error; const retryAfter = response.headers.get('Retry-After'); const advertised = retryAfter === null ? NaN : /^\d+$/.test(retryAfter) ? Number(retryAfter) * 1000 : Date.parse(retryAfter) - Date.now(); const delay = Number.isFinite(advertised) ? Math.max(0, advertised) : 1000 * 2 ** attempt; // Long waits belong in a durable job queue. Do not retry earlier than requested. if (delay > 30_000) throw error; await wait(delay); } throw new Error('Unreachable attempt state.'); } export function cliOptions(transport: Transport) { const mode = process.env.OVEYON_MODE ?? 'mock'; if (!['mock', 'sandbox'].includes(mode)) throw new TypeError('OVEYON_MODE supports mock or sandbox only.'); if (mode === 'sandbox' && !process.env.OVEYON_API_KEY) throw new TypeError('Set OVEYON_API_KEY on the backend before an explicit sandbox run.'); return { mode, apiKey: mode === 'mock' ? 'mock-key-not-a-credential' : process.env.OVEYON_API_KEY!, transport: mode === 'mock' ? transport : fetch }; } export function messageAddresses() { return { from: process.env.OVEYON_FROM ?? 'Demo ', to: process.env.OVEYON_TO ?? 'reader@example.net' }; } ``` ### shared/mock.ts ``` // Synthetic, in-memory API fixture. No HTTP request or email is sent. import type { Transport } from './client.ts'; export function mockApi(failures: number[] = []) { const requests: { url: string; init: RequestInit }[] = []; const messages = new Map(); const templates = new Map(); const transport: Transport = async (url, init) => { requests.push({ url, init }); const forced = failures.shift(); if (forced) return Response.json({ error: forced === 429 ? 'rate_limited' : 'injection_failed' }, { status: forced, headers: { 'Retry-After': '0' } }); const route = new URL(url).pathname; const data = JSON.parse(String(init.body ?? '{}')); if (route.endsWith('/templates')) { if (templates.has(data.name)) return Response.json({ error: 'template_exists' }, { status: 409 }); templates.set(data.name, { version: 1, published: false }); return Response.json({ id: 1, name: data.name, version: 1, status: 'draft', vars: [{ name: 'name', kind: 'var', required: true }] }, { status: 201 }); } if (route.endsWith('/publish')) { const name = decodeURIComponent(route.split('/').at(-2)!); const template = templates.get(name); if (!template) return Response.json({ error: 'template_not_found' }, { status: 404 }); template.published = true; return Response.json({ id: 1, name, version: 1, status: 'published' }); } if (data.templateId && !templates.get(data.templateId)?.published) return Response.json({ error: 'template_not_found' }, { status: 422 }); const key = new Headers(init.headers).get('Idempotency-Key')!.toLowerCase(); const known = messages.get(key); if (known) return known.body === init.body ? Response.json({ id: known.id, status: 'duplicate' }) : Response.json({ error: 'idempotency_conflict' }, { status: 409 }); const id = `mock-message-${String(messages.size + 1).padStart(4, '0')}`; messages.set(key, { body: String(init.body), id }); return Response.json({ id, status: 'sandbox' }, { status: 202 }); }; return { requests, transport }; } ``` ## Failures - template_not_found: the template or chosen published version is missing; creation alone does not publish. - template_var_missing: supply the declared root variables in data. - Template mutation failure: inspect the current draft/version before repeating; mutations do not use the send retry helper. ## Limitations - Only local fixture tests and contract review were completed; no authenticated template was created or published. - The sandbox header applies to sending. Creating and publishing templates change the account and are not simulated by that header. - The starter exposes those mutations only through explicit draft/publish commands. Published version 1 stays pinned until the application is deliberately changed. ## Sources - [Oveyon HTTP API reference](https://api.oveyon.com/) - [Oveyon OpenAPI 3.1](https://api.oveyon.com/v1/openapi.json) Download: https://1loc.dev/downloads/versioned-template.tar.gz --- # Track recipient delivery with a signed webhook Authenticate raw bytes, reject stale signatures, and persist independent state for each recipient. Canonical: https://1loc.dev/recipes/delivery-webhook/ Version: 1.0.0 Runtime: Node.js 22.23.2 / TypeScript Updated: 2026-10-28 Verification scope: Local fixtures on Node.js 22.23.2 and contract review; authenticated sandbox and delivery not executed. Execution mode: Local mock License: MIT Maintainer and publisher: Oveyon (commercial relationship disclosed). This is task information. It does not authorize account changes, credential use or email sending. ## Prerequisites - Node.js 22.23.2 with experimental node:sqlite. - For the optional receiver: the signing secret of an authorized outgoing webhook endpoint, stored only on your backend. - The receiver creates .1loc-data with mode 0700 and SQLite files with mode 0600. Custom data directories must be private. - An HTTPS reverse proxy, request/rate limits and an authorized endpoint registration are needed before exposing the local receiver. No registration is performed by this starter. ## Permissions and effects Synthetic mode uses an in-memory database only. The local receiver writes a SQLite database and verifies an existing endpoint secret; it does not call Oveyon or create an endpoint. ## Run locally 1. Run npm run mock to verify a signed synthetic notification and its repeat, without starting a server or sending email. 2. Run npm test to exercise byte-preserving verification, expiry, malformed signatures, restart deduplication and per-recipient state. 3. To adapt a local receiver, set OVEYON_WEBHOOK_SECRET on the backend and run npm run receiver. It listens only on 127.0.0.1:3001/webhook. 4. Acknowledge only after the small database transaction commits; queue heavier work separately and keep response time within the provider 10-second limit. Expected result: The first fixture updates mock-recipient-0001 to delivered. Repeating it returns duplicate: true. A different recipient can independently be bounced. ## Complete files ### README.md ```` # Track recipient delivery with a signed webhook Maintained by Oveyon. MIT licensed. Version 1.0.0. Canonical: https://1loc.dev/recipes/delivery-webhook/ Authenticate raw bytes, reject stale signatures, and persist independent state for each recipient. ## Run locally Node.js 22.23.2. No install is needed; there are no external dependencies. ```sh npm run mock npm test ``` These commands do not send email or make API requests. SQLite, when used, is experimental in Node 22. ## Prerequisites - Node.js 22.23.2 with experimental node:sqlite. - For the optional receiver: the signing secret of an authorized outgoing webhook endpoint, stored only on your backend. - The receiver creates .1loc-data with mode 0700 and SQLite files with mode 0600. Custom data directories must be private. - An HTTPS reverse proxy, request/rate limits and an authorized endpoint registration are needed before exposing the local receiver. No registration is performed by this starter. ## Procedure 1. Run npm run mock to verify a signed synthetic notification and its repeat, without starting a server or sending email. 2. Run npm test to exercise byte-preserving verification, expiry, malformed signatures, restart deduplication and per-recipient state. 3. To adapt a local receiver, set OVEYON_WEBHOOK_SECRET on the backend and run npm run receiver. It listens only on 127.0.0.1:3001/webhook. 4. Acknowledge only after the small database transaction commits; queue heavier work separately and keep response time within the provider 10-second limit. ## Expected result The first fixture updates mock-recipient-0001 to delivered. Repeating it returns duplicate: true. A different recipient can independently be bounced. ## Permissions and effects Synthetic mode uses an in-memory database only. The local receiver writes a SQLite database and verifies an existing endpoint secret; it does not call Oveyon or create an endpoint. Optional backend command(s): npm run receiver. Keep credentials in .env on your own backend or in a secrets manager. Never commit .env. The public site does not accept credentials. ## Failures - 401: the raw body, signing secret, HMAC or 300-second timestamp window is invalid. - 400: the authenticated payload cannot be parsed or does not match the supported outgoing event shape. - 503: local state could not be committed. Let the provider retry; do not claim the event was stored. ## Limits and verification - The public OpenAPI outgoing-event schema is permissive. messageId, optional deliveryId, recipient, status and timestamp were reviewed against the current producer; no real signed provider request was observed. - Outgoing notifications do not expose the inbound eventId guarantee. This example deduplicates the same event/recipient/timestamp tuple and applies status idempotently; separately emitted equivalent notifications may remain separate observations. - Recipient identity always uses messageId plus the exact recipient address. Optional deliveryId does not change that identity or bypass ordering/deduplication. - Only delivered/bounced and their fallback variants are stored. Engagement, complaint, blocked, inbound and approval events are ignored by this focused handler. - An older notification cannot overwrite a newer observation. Equal-time conflicting states are not ordered; reconcile them with the message API. - Recipient-server acceptance does not establish inbox placement. A fresh signed retry may contain an old event timestamp; anti-replay uses the signed header timestamp. Local fixture tests executed on Node.js 22.23.2 on 2026-10-28. Contract snapshot reviewed; authenticated API/sandbox and real delivery were not executed. ## Sources - https://api.oveyon.com/ - https://api.oveyon.com/v1/openapi.json ```` ### package.json ``` { "name": "1loc-delivery-webhook", "version": "1.0.0", "private": true, "type": "module", "license": "MIT", "engines": { "node": ">=22.23.2 <23" }, "scripts": { "mock": "OVEYON_MODE=mock node --env-file-if-exists=.env --experimental-strip-types delivery-webhook/main.ts", "test": "node --experimental-strip-types --test delivery-webhook/recipe.test.ts", "receiver": "node --env-file-if-exists=.env --experimental-strip-types delivery-webhook/server.ts" } } ``` ### package-lock.json ``` { "name": "1loc-delivery-webhook", "version": "1.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "1loc-delivery-webhook", "version": "1.0.0", "license": "MIT", "engines": { "node": ">=22.23.2 <23" } } } } ``` ### .env.example ``` # Backend only; never put the real value in a public site. OVEYON_WEBHOOK_SECRET=replace_with_your_endpoint_secret # DELIVERY_DB=.1loc-data/delivery-state.sqlite # Existing custom data directories must have mode 0700. ``` ### .gitignore ``` .env .1loc-data/ *.sqlite *.sqlite-shm *.sqlite-wal node_modules/ ``` ### LICENSE ``` MIT License Copyright (c) 2026 Oveyon Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` ### delivery-webhook/main.ts ``` import { pathToFileURL } from 'node:url'; import { openDeliveryStore, receive } from './receiver.ts'; import { syntheticEvent, syntheticSecret, fixtureHeaders } from './fixture.ts'; export function run() { const db = openDeliveryStore(':memory:'); try { const raw = Buffer.from(JSON.stringify(syntheticEvent)); const now = Math.floor(Date.now() / 1000); const headers = fixtureHeaders(raw, now); const first = receive(db, raw, headers, syntheticSecret, now); const repeated = receive(db, raw, headers, syntheticSecret, now); console.log(JSON.stringify({ mode: 'synthetic fixture; no email is sent', first, repeated, meaning: 'Recipient server acceptance does not prove inbox placement.' }, null, 2)); } finally { db.close(); } } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) run(); ``` ### delivery-webhook/receiver.ts ``` import { createHmac, timingSafeEqual } from 'node:crypto'; import type { DatabaseSync } from 'node:sqlite'; import { openPrivateDatabase } from '../shared/private-store.ts'; type Headers = { timestamp: string; signature: string; event?: string }; type Delivery = { event: string; messageId: string; deliveryId?: string; recipient: string; status: string; timestamp: string }; const supported = new Map([['delivered', 'delivered'], ['fallback_delivered', 'delivered'], ['bounced', 'bounced'], ['fallback_bounced', 'bounced']]); export function verifySignature(raw: Buffer, headers: Headers, secret: string, nowSeconds: number) { if (raw.byteLength > 65_536 || secret.length < 16 || !/^\d{10,12}$/.test(headers.timestamp) || !/^sha256=[a-f0-9]{64}$/.test(headers.signature)) return false; const timestamp = Number(headers.timestamp); if (!Number.isSafeInteger(timestamp) || !Number.isFinite(nowSeconds) || Math.abs(nowSeconds - timestamp) > 300) return false; const expected = createHmac('sha256', secret).update(`${headers.timestamp}.`).update(raw).digest(); const given = Buffer.from(headers.signature.slice(7), 'hex'); return given.length === expected.length && timingSafeEqual(expected, given); } export function openDeliveryStore(path: string) { const db = openPrivateDatabase(path); db.exec('PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; CREATE TABLE IF NOT EXISTS seen_events (event_key TEXT PRIMARY KEY); CREATE TABLE IF NOT EXISTS recipient_state (message_id TEXT NOT NULL, recipient_key TEXT NOT NULL, status TEXT NOT NULL, event_at TEXT NOT NULL, PRIMARY KEY(message_id,recipient_key));'); return db; } function validString(value: unknown, max: number): value is string { return typeof value === 'string' && value.length > 0 && value.length <= max; } export function receive(db: DatabaseSync, raw: Buffer, headers: Headers, secret: string, nowSeconds = Date.now() / 1000) { if (!verifySignature(raw, headers, secret, nowSeconds)) throw new Error('invalid_signature_or_timestamp'); const event: Delivery = JSON.parse(raw.toString('utf8')); if (!event || !validString(event.event, 80) || (headers.event && headers.event !== event.event)) throw new TypeError('Invalid event name.'); if (!supported.has(event.event)) return { ignored: true, reason: 'This example stores only delivery/bounce outcomes.' }; if (!validString(event.messageId, 100) || !validString(event.recipient, 320) || !validString(event.timestamp, 40) || !Number.isFinite(Date.parse(event.timestamp)) || (event.deliveryId !== undefined && !validString(event.deliveryId, 100))) throw new TypeError('Unsupported outgoing delivery payload.'); const outcome = supported.get(event.event)!; if (event.status !== outcome) throw new TypeError('Event and recipient status disagree.'); // Outgoing notifications do not promise inbound's eventId. This key identifies // the same frozen outgoing notification, not every future equivalent event. // messageId + recipient is stable even when optional deliveryId is absent on // one notification. Preserve the exact address; do not rewrite its local part. const recipientKey = event.recipient; const eventAt = new Date(event.timestamp).toISOString(); const eventKey = JSON.stringify([event.messageId, recipientKey, event.event, eventAt]); db.exec('BEGIN IMMEDIATE'); try { const inserted = db.prepare('INSERT OR IGNORE INTO seen_events(event_key) VALUES(?)').run(eventKey); if (inserted.changes === 0) { db.exec('COMMIT'); return { duplicate: true }; } // An older notification can be retried after a newer one. Do not overwrite // the current per-recipient state with an older observation. db.prepare('INSERT INTO recipient_state(message_id,recipient_key,status,event_at) VALUES(?,?,?,?) ON CONFLICT(message_id,recipient_key) DO UPDATE SET status=excluded.status,event_at=excluded.event_at WHERE excluded.event_at>recipient_state.event_at').run(event.messageId, recipientKey, outcome, eventAt); db.exec('COMMIT'); return { duplicate: false, recipientKey, status: outcome }; } catch (error) { db.exec('ROLLBACK'); throw error; } } ``` ### delivery-webhook/fixture.ts ``` import { createHmac } from 'node:crypto'; export const syntheticSecret = 'synthetic-fixture-only-not-a-production-secret'; export const syntheticEvent = { event: 'delivered', messageId: 'mock-message-0001', deliveryId: 'mock-recipient-0001', recipient: 'reader@example.net', status: 'delivered', detail: {}, timestamp: '2026-10-28T12:00:00.000Z' }; export function fixtureHeaders(raw: Buffer, timestamp: number, secret = syntheticSecret) { return { timestamp: String(timestamp), signature: `sha256=${createHmac('sha256', secret).update(`${timestamp}.`).update(raw).digest('hex')}`, event: JSON.parse(raw.toString()).event }; } ``` ### delivery-webhook/server.ts ``` import { createServer } from 'node:http'; import { openDeliveryStore, receive } from './receiver.ts'; const secret = process.env.OVEYON_WEBHOOK_SECRET; if (!secret || secret.length < 16 || secret.includes('replace_')) throw new Error('Provide the actual endpoint secret on your backend, never in a browser.'); const port = Number(process.env.WEBHOOK_PORT ?? '3001'); if (!Number.isInteger(port) || port < 0 || port > 65_535) throw new Error('WEBHOOK_PORT must be an integer between 0 and 65535.'); const db = openDeliveryStore(process.env.DELIVERY_DB ?? '.1loc-data/delivery-state.sqlite'); const server = createServer(async (req, res) => { if (req.method !== 'POST' || req.url !== '/webhook') { res.writeHead(404).end(); return; } if (!req.headers['content-type']?.startsWith('application/json')) { res.writeHead(415).end(); req.resume(); return; } const chunks: Buffer[] = []; let size = 0; try { for await (const chunk of req) { size += chunk.length; if (size > 65_536) { res.writeHead(413).end(); req.destroy(); return; } chunks.push(chunk); } const result = receive(db, Buffer.concat(chunks), { timestamp: String(req.headers['x-oveyon-timestamp'] ?? ''), signature: String(req.headers['x-oveyon-signature'] ?? ''), event: String(req.headers['x-oveyon-event'] ?? '') }, secret); res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify(result)); } catch (error) { // Reject invalid input without logging bodies, addresses, signatures or keys. res.writeHead(error instanceof Error && error.message === 'invalid_signature_or_timestamp' ? 401 : error instanceof SyntaxError || error instanceof TypeError ? 400 : 503).end(); } }); server.requestTimeout = 15_000; server.headersTimeout = 10_000; server.listen(port, '127.0.0.1', () => { const address = server.address(); if (!address || typeof address === 'string') throw new Error('Expected a loopback TCP listener.'); console.log(`Local receiver: http://127.0.0.1:${address.port}/webhook. Add your own HTTPS reverse proxy and rate limits before registration.`); }); function close() { server.close(() => { db.close(); process.exit(0); }); } process.on('SIGINT', close); process.on('SIGTERM', close); ``` ### delivery-webhook/recipe.test.ts ``` import test from 'node:test'; import assert from 'node:assert/strict'; import { mkdtempSync, rmSync, statSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { verifySignature, openDeliveryStore, receive } from './receiver.ts'; import { syntheticEvent, syntheticSecret, fixtureHeaders } from './fixture.ts'; const now = 1793196000; test('signature uses exact raw bytes and signed timestamp, not reserialized JSON', () => { const raw = Buffer.from(JSON.stringify(syntheticEvent, null, 2)); const headers = fixtureHeaders(raw, now); assert.equal(verifySignature(raw, headers, syntheticSecret, now), true); assert.equal(verifySignature(Buffer.from(JSON.stringify(syntheticEvent)), headers, syntheticSecret, now), false); assert.equal(verifySignature(raw, headers, syntheticSecret, now + 301), false); assert.equal(verifySignature(raw, { ...headers, timestamp: 'NaN' }, syntheticSecret, now), false); assert.equal(verifySignature(raw, { ...headers, signature: 'sha256=bad' }, syntheticSecret, now), false); assert.equal(verifySignature(Buffer.alloc(65_537), headers, syntheticSecret, now), false); }); test('outgoing notifications persist deduplication and keep each recipient separate', () => { const directory = mkdtempSync(join(tmpdir(), '1loc-webhook-')); const path = join(directory, 'state.sqlite'); try { let db = openDeliveryStore(path); const raw = Buffer.from(JSON.stringify(syntheticEvent)); const headers = fixtureHeaders(raw, now); assert.equal(receive(db, raw, headers, syntheticSecret, now).duplicate, false); db.close(); db = openDeliveryStore(path); try { assert.equal(receive(db, raw, headers, syntheticSecret, now).duplicate, true); const other = Buffer.from(JSON.stringify({ ...syntheticEvent, recipient: 'other@example.net', deliveryId: 'mock-recipient-0002', event: 'bounced', status: 'bounced' })); receive(db, other, fixtureHeaders(other, now), syntheticSecret, now); assert.equal(db.prepare('SELECT COUNT(*) AS n FROM recipient_state').get()!.n, 2); assert.equal(db.prepare('SELECT status FROM recipient_state WHERE recipient_key=?').get('reader@example.net')!.status, 'delivered'); } finally { db.close(); } } finally { rmSync(directory, { recursive: true, force: true }); } }); test('optional deliveryId cannot fragment state or bypass ordering/deduplication', () => { const db = openDeliveryStore(':memory:'); try { const newest = { ...syntheticEvent, timestamp: '2026-10-28T13:00:00Z' }; const { deliveryId, ...withoutDeliveryId } = newest; const first = Buffer.from(JSON.stringify(newest)); receive(db, first, fixtureHeaders(first, now), syntheticSecret, now); const repeated = Buffer.from(JSON.stringify(withoutDeliveryId)); assert.equal(receive(db, repeated, fixtureHeaders(repeated, now), syntheticSecret, now).duplicate, true); const old = Buffer.from(JSON.stringify({ ...withoutDeliveryId, event: 'bounced', status: 'bounced', timestamp: '2026-10-28T12:00:00Z' })); receive(db, old, fixtureHeaders(old, now), syntheticSecret, now); assert.equal(db.prepare('SELECT COUNT(*) AS n FROM recipient_state').get()!.n, 1); assert.equal(db.prepare('SELECT status FROM recipient_state').get()!.status, 'delivered'); } finally { db.close(); } }); test('delivery state creates a private directory and SQLite files under umask 022', () => { const directory = mkdtempSync(join(tmpdir(), '1loc-private-delivery-')); const data = join(directory, 'private-data'); const path = join(data, 'state.sqlite'); const previousMask = process.umask(0o022); try { const db = openDeliveryStore(path); try { const raw = Buffer.from(JSON.stringify(syntheticEvent)); receive(db, raw, fixtureHeaders(raw, now), syntheticSecret, now); assert.equal(statSync(data).mode & 0o777, 0o700); for (const file of [path, `${path}-wal`, `${path}-shm`]) assert.equal(statSync(file).mode & 0o777, 0o600); } finally { db.close(); } } finally { process.umask(previousMask); rmSync(directory, { recursive: true, force: true }); } }); test('old notifications cannot overwrite newer recipient state; invalid payload rolls back', () => { const db = openDeliveryStore(':memory:'); try { for (const event of [{ ...syntheticEvent, event: 'bounced', status: 'bounced', timestamp: '2026-10-28T13:00:00Z' }, syntheticEvent]) { const raw = Buffer.from(JSON.stringify(event)); receive(db, raw, fixtureHeaders(raw, now), syntheticSecret, now); } assert.equal(db.prepare('SELECT status FROM recipient_state').get()!.status, 'bounced'); const invalid = Buffer.from(JSON.stringify({ ...syntheticEvent, status: 'queued' })); assert.throws(() => receive(db, invalid, fixtureHeaders(invalid, now), syntheticSecret, now), /disagree/); } finally { db.close(); } }); ``` ### shared/private-store.ts ``` import { DatabaseSync } from 'node:sqlite'; import { chmodSync, closeSync, constants, existsSync, lstatSync, mkdirSync, openSync } from 'node:fs'; import { dirname, resolve } from 'node:path'; export function openPrivateDatabase(path: string) { // Keep this restrictive for the lifetime of the process: SQLite can recreate // its WAL/SHM files after the opening call has returned. process.umask(0o077); if (path === ':memory:') return new DatabaseSync(path); const absolute = resolve(path); const directory = dirname(absolute); mkdirSync(directory, { recursive: true, mode: 0o700 }); const folder = lstatSync(directory); if (!folder.isDirectory() || folder.isSymbolicLink() || (folder.mode & 0o077) !== 0) { throw new Error('Use a dedicated data directory with mode 0700; shared directory permissions were not changed.'); } for (const file of [absolute, `${absolute}-wal`, `${absolute}-shm`]) { if (!existsSync(file)) continue; if (!lstatSync(file).isFile() || lstatSync(file).isSymbolicLink()) throw new Error('Database state must be regular files, not symlinks.'); // Harden existing state in place without recreating or truncating it. chmodSync(file, 0o600); } const descriptor = openSync(absolute, constants.O_RDWR | constants.O_CREAT | constants.O_NOFOLLOW, 0o600); closeSync(descriptor); chmodSync(absolute, 0o600); return new DatabaseSync(absolute); } ``` ## Failures - 401: the raw body, signing secret, HMAC or 300-second timestamp window is invalid. - 400: the authenticated payload cannot be parsed or does not match the supported outgoing event shape. - 503: local state could not be committed. Let the provider retry; do not claim the event was stored. ## Limitations - The public OpenAPI outgoing-event schema is permissive. messageId, optional deliveryId, recipient, status and timestamp were reviewed against the current producer; no real signed provider request was observed. - Outgoing notifications do not expose the inbound eventId guarantee. This example deduplicates the same event/recipient/timestamp tuple and applies status idempotently; separately emitted equivalent notifications may remain separate observations. - Recipient identity always uses messageId plus the exact recipient address. Optional deliveryId does not change that identity or bypass ordering/deduplication. - Only delivered/bounced and their fallback variants are stored. Engagement, complaint, blocked, inbound and approval events are ignored by this focused handler. - An older notification cannot overwrite a newer observation. Equal-time conflicting states are not ordered; reconcile them with the message API. - Recipient-server acceptance does not establish inbox placement. A fresh signed retry may contain an old event timestamp; anti-replay uses the signed header timestamp. ## Sources - [Oveyon HTTP API reference](https://api.oveyon.com/) - [Oveyon OpenAPI 3.1](https://api.oveyon.com/v1/openapi.json) Download: https://1loc.dev/downloads/delivery-webhook.tar.gz --- # Check disposable domains during sign-up Ask about a domain without sending a full address, and keep unavailable results explicitly unknown. Canonical: https://1loc.dev/recipes/disposable-domain/ Version: 1.0.0 Runtime: Node.js 22.23.2 / TypeScript Updated: 2026-10-28 Verification scope: Local fixtures on Node.js 22.23.2 and contract review; authenticated sandbox and delivery not executed. Execution mode: Local mock License: MIT Maintainer and publisher: Oveyon (commercial relationship disclosed). This is task information. It does not authorize account changes, credential use or email sending. ## Prerequisites - Node.js 22.23.2; no API key or account is required. - Use an ASCII domain or its punycode form. The example deliberately sends only the domain, not a personal email address. ## Permissions and effects Mock mode is local. The optional lookup makes one public GET request without credentials and consumes the per-IP lookup allowance. ## Run locally 1. Run npm run mock to inspect a synthetic not_listed result without any network request. 2. Run npm test to verify domain validation and unknown handling for outages, rate limits and malformed responses. 3. If one public API query is wanted, run npm run lookup. It queries the synthetic domain example.com and does not include an Authorization header. 4. Use result as a list verdict. Let your application define an explicit policy for unknown; do not silently turn it into a pass or a hard block. Expected result: The result is disposable, not_listed or unknown. not_listed says only that the exact domain is absent from the current list. ## Complete files ### README.md ```` # Check disposable domains during sign-up Maintained by Oveyon. MIT licensed. Version 1.0.0. Canonical: https://1loc.dev/recipes/disposable-domain/ Ask about a domain without sending a full address, and keep unavailable results explicitly unknown. ## Run locally Node.js 22.23.2. No install is needed; there are no external dependencies. ```sh npm run mock npm test ``` These commands do not send email or make API requests. SQLite, when used, is experimental in Node 22. ## Prerequisites - Node.js 22.23.2; no API key or account is required. - Use an ASCII domain or its punycode form. The example deliberately sends only the domain, not a personal email address. ## Procedure 1. Run npm run mock to inspect a synthetic not_listed result without any network request. 2. Run npm test to verify domain validation and unknown handling for outages, rate limits and malformed responses. 3. If one public API query is wanted, run npm run lookup. It queries the synthetic domain example.com and does not include an Authorization header. 4. Use result as a list verdict. Let your application define an explicit policy for unknown; do not silently turn it into a pass or a hard block. ## Expected result The result is disposable, not_listed or unknown. not_listed says only that the exact domain is absent from the current list. ## Permissions and effects Mock mode is local. The optional lookup makes one public GET request without credentials and consumes the per-IP lookup allowance. Optional backend command(s): npm run lookup. Keep credentials in .env on your own backend or in a secrets manager. Never commit .env. The public site does not accept credentials. ## Failures - 400 or an invalid domain: correct the domain format. - 429: the public endpoint has a per-IP limit. Honor Retry-After rather than retrying a registration loop. - 503, network timeout or malformed response: preserve unknown; do not claim the address was checked. ## Limits and verification - Only fixtures were executed; the public lookup command has not been run as a verification claim. - The lookup does not establish mailbox existence, deliverability, trustworthiness or inbox placement. - Matching is for the exact domain, not every subdomain. The documented cap is 60 lookups per IP per hour; use the public list directly for bulk processing. Local fixture tests executed on Node.js 22.23.2 on 2026-10-28. Contract snapshot reviewed; authenticated API/sandbox and real delivery were not executed. ## Sources - https://api.oveyon.com/ - https://api.oveyon.com/v1/openapi.json ```` ### package.json ``` { "name": "1loc-disposable-domain", "version": "1.0.0", "private": true, "type": "module", "license": "MIT", "engines": { "node": ">=22.23.2 <23" }, "scripts": { "mock": "OVEYON_MODE=mock node --env-file-if-exists=.env --experimental-strip-types disposable-domain/main.ts", "test": "node --experimental-strip-types --test disposable-domain/recipe.test.ts", "lookup": "OVEYON_MODE=public-lookup node --env-file-if-exists=.env --experimental-strip-types disposable-domain/main.ts" } } ``` ### package-lock.json ``` { "name": "1loc-disposable-domain", "version": "1.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "1loc-disposable-domain", "version": "1.0.0", "license": "MIT", "engines": { "node": ">=22.23.2 <23" } } } } ``` ### .env.example ``` # No credential is required. Mock is the default. ``` ### .gitignore ``` .env .1loc-data/ *.sqlite *.sqlite-shm *.sqlite-wal node_modules/ ``` ### LICENSE ``` MIT License Copyright (c) 2026 Oveyon Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` ### disposable-domain/main.ts ``` import { pathToFileURL } from 'node:url'; import { lookup } from './lookup.ts'; export async function run() { const mode = process.env.OVEYON_MODE ?? 'mock'; if (!['mock', 'public-lookup'].includes(mode)) throw new Error('Use mock, or public-lookup for one explicit public API query.'); const transport = mode === 'mock' ? async () => Response.json({ domain: 'example.com', result: 'not_listed', disposable: false }) : fetch; const result = await lookup('example.com', transport); console.log(JSON.stringify({ mode, synthetic: mode === 'mock', ...result }, null, 2)); } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) await run(); ``` ### disposable-domain/lookup.ts ``` export type Verdict = 'disposable' | 'not_listed' | 'unknown'; export function lookupUrl(domain: string) { const normalized = domain.trim().toLowerCase().replace(/\.$/, ''); if (normalized.length > 253 || !/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/.test(normalized)) throw new TypeError('Use an ASCII domain, or its punycode form.'); const url = new URL('https://api.oveyon.com/v1/disposable'); url.searchParams.set('domain', normalized); return url.href; } export async function lookup(domain: string, transport: typeof fetch = fetch): Promise<{ result: Verdict; httpStatus: number; reason: string }> { const url = lookupUrl(domain); let response: Response; try { response = await transport(url, { method: 'GET', redirect: 'error', signal: AbortSignal.timeout(5000) }); } catch { return { result: 'unknown', httpStatus: 0, reason: 'Lookup unavailable; do not turn an outage into a positive verdict.' }; } const body = await response.json().catch(() => null); if (response.status !== 200 || !body || !['disposable', 'not_listed', 'unknown'].includes(body.result)) return { result: 'unknown', httpStatus: response.status, reason: 'The service did not provide a usable verdict.' }; return { result: body.result, httpStatus: response.status, reason: body.result === 'not_listed' ? 'Not on the current list; mailbox existence and deliverability were not checked.' : body.result === 'disposable' ? 'This exact domain is on the disposable-domain list.' : 'The service cannot determine the result.' }; } ``` ### disposable-domain/recipe.test.ts ``` import test from 'node:test'; import assert from 'node:assert/strict'; import { lookup, lookupUrl } from './lookup.ts'; test('domain query is encoded and needs no authentication header', async () => { assert.equal(lookupUrl(' Example.COM. '), 'https://api.oveyon.com/v1/disposable?domain=example.com'); assert.throws(() => lookupUrl('person@example.com')); await lookup('example.com', async (url, init) => { assert.equal(new Headers(init?.headers).has('Authorization'), false); assert.equal(new URL(String(url)).searchParams.has('email'), false); return Response.json({ result: 'not_listed' }); }); }); test('unavailable, rate limited and malformed responses stay unknown', async () => { for (const status of [429, 503]) assert.equal((await lookup('example.com', async () => Response.json({ result: 'unknown', disposable: null }, { status }))).result, 'unknown'); assert.equal((await lookup('example.com', async () => { throw new Error('offline'); })).result, 'unknown'); assert.equal((await lookup('example.com', async () => Response.json({ result: 'trustworthy' }))).result, 'unknown'); assert.match((await lookup('example.com', async () => Response.json({ result: 'not_listed' }))).reason, /existence and deliverability were not checked/); }); ``` ## Failures - 400 or an invalid domain: correct the domain format. - 429: the public endpoint has a per-IP limit. Honor Retry-After rather than retrying a registration loop. - 503, network timeout or malformed response: preserve unknown; do not claim the address was checked. ## Limitations - Only fixtures were executed; the public lookup command has not been run as a verification claim. - The lookup does not establish mailbox existence, deliverability, trustworthiness or inbox placement. - Matching is for the exact domain, not every subdomain. The documented cap is 60 lookups per IP per hour; use the public list directly for bulk processing. ## Sources - [Oveyon HTTP API reference](https://api.oveyon.com/) - [Oveyon OpenAPI 3.1](https://api.oveyon.com/v1/openapi.json) Download: https://1loc.dev/downloads/disposable-domain.tar.gz --- # The one-line sheet Every curated JavaScript utility on 1loc.dev as the exact function the lab or the tests run, grouped by topic. Canonical: https://1loc.dev/library/cheatsheet/ Maintained by Oveyon. Updated 2026-10-28. ## array ### Clone an array Create a new array without copying the objects inside it. https://1loc.dev/array/clone-an-array/ ```javascript function clone(values) { return [...values]; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). This is a shallow copy: nested objects keep the same identity. ### Remove duplicate values Keep the first occurrence of each value, in its original order. https://1loc.dev/array/remove-duplicate-values-in-an-array/ ```javascript function unique(values) { return [...new Set(values)]; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Set compares objects by reference. Two separately created objects are not duplicates. ### Flatten a nested array Turn a nested array into one sequence of values. https://1loc.dev/array/flatten-an-array/ ```javascript function flatten(values) { return values.flat(Infinity); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Input depth is capped at 12 and the total element count at 1,000 in this lab. ### Split an array into chunks Build consecutive chunks without changing the original array. https://1loc.dev/array/split-an-array-into-chunks/ ```javascript function chunk({ values, size }) { return Array.from({ length: Math.ceil(values.length / size) }, (_, i) => values.slice(i * size, (i + 1) * size)); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Size must be an integer from 1 to 1,000; zero is rejected before allocation. ### Find the intersection of arrays Return the distinct values that occur in both arrays. https://1loc.dev/array/get-the-intersection-of-arrays/ ```javascript function intersection({ left, right }) { const other = new Set(right); return [...new Set(left)].filter(value => other.has(value)); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Result order follows the first array. Duplicate results are removed. ### Sort numbers in ascending order Sort a numeric copy instead of using JavaScript’s default string ordering. https://1loc.dev/array/sort-an-array-of-numbers/ ```javascript function sortNumbers(values) { return [...values].sort((a, b) => a - b); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The lab accepts finite numbers only. The source array remains unchanged. ### Sum an array of numbers Add numeric values with an explicit result for an empty array. https://1loc.dev/array/get-the-sum-of-an-array-of-numbers/ ```javascript function sum(values) { return values.reduce((total, value) => total + value, 0); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Floating-point arithmetic is approximate; use integer minor units or a decimal library for money. ### Group objects by a key Collect records by a string or numeric field without prototype-key collisions. https://1loc.dev/array/group-an-array-of-objects-by-a-key/ ```javascript function groupBy({ values, key }) { const groups = new Map(); for (const value of values) { const group = String(value[key]); groups.set(group, [...(groups.get(group) || []), value]); } return Object.fromEntries(groups); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Every record must own the grouping field, with a string or number value. ### Cast a value as an array Wrap a single value in an array and return arrays unchanged. https://1loc.dev/array/cast-a-value-as-an-array/ ```javascript function castArray(value) { return Array.isArray(value) ? value : [value]; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Arrays are returned as they are, not copied. ### Convert an array of strings to numbers Map every string with Number. https://1loc.dev/array/convert-an-array-of-strings-to-numbers/ ```javascript function toNumbers(values) { return values.map(Number); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Number("") is 0 and surrounding spaces are ignored, as the edge case shows. Invalid strings become NaN (null in JSON) — validate user input first. ### Get all subsets of an array Build the power set, smallest subsets first. https://1loc.dev/array/get-all-subsets-of-an-array/ ```javascript function getSubsets(values) { return values.reduce((subsets, value) => subsets.concat(subsets.map(subset => [...subset, value])), [[]]); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The result has 2^n subsets, so the lab accepts at most 10 values (1,024 subsets). ### Get union of arrays Merge arrays and keep each value once, in first-seen order. https://1loc.dev/array/get-union-of-arrays/ ```javascript function union(arrays) { return [...new Set(arrays.flat())]; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original took the arrays as separate arguments; the lab passes one array of arrays. ### Swap the rows and columns of a matrix Transpose a rectangular matrix. https://1loc.dev/array/swap-the-rows-and-columns-of-a-matrix/ ```javascript function transpose(matrix) { return matrix[0].map((_, column) => matrix.map(row => row[column])); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Rows must have the same length; the lab requires a non-empty rectangular matrix. ### Swap two array items Return a copy with the items at i and j exchanged. https://1loc.dev/array/swap-two-array-items/ ```javascript function swapItems({ values, i, j }) { const copy = [...values]; [copy[i], copy[j]] = [copy[j], copy[i]]; return copy; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original only swapped when both items were truthy, so arrays containing 0 or "" were returned unchanged. Destructuring swaps any values and works in either index order. ### Unzip an array of arrays Regroup the n-th item of every array into the n-th output array. https://1loc.dev/array/unzip-an-array-of-arrays/ ```javascript function unzip(arrays) { return Array.from({ length: Math.max(0, ...arrays.map(array => array.length)) }, (_, i) => arrays.filter(array => i < array.length).map(array => array[i])); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Shorter arrays simply contribute fewer items. ### Compare two arrays Check the same length and the same items in the same order. https://1loc.dev/array/compare-two-arrays/ ```javascript function isEqual({ a, b }) { return a.length === b.length && a.every((value, i) => Object.is(value, b[i])); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Shallow comparison with Object.is. The original JSON.stringify variant treats undefined and null alike and depends on key order for nested objects. ### Convert an array of objects to a single object Index records by a key field. https://1loc.dev/array/convert-an-array-of-objects-to-a-single-object/ ```javascript function toObject({ values, key }) { return Object.fromEntries(values.map(item => [item[key], item])); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A repeated key keeps the last record, as the edge case shows. ### Count the occurrences of a value in an array Count items strictly equal to a value. https://1loc.dev/array/count-the-occurrences-of-a-value-in-an-array/ ```javascript function countOccurrences({ values, value }) { return values.filter(item => item === value).length; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Strict equality: 1 and "1" differ. ### Count the occurrences of array elements Tally every distinct value into an object. https://1loc.dev/array/count-the-occurrences-of-array-elements/ ```javascript function countEach(values) { return { ...values.reduce((counts, value) => ((counts[value] = (counts[value] || 0) + 1), counts), Object.create(null)) }; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Keys become strings, so 1 and "1" share a count. ### Create an array of numbers in the given range List the integers from min to max inclusive. https://1loc.dev/array/create-an-array-of-numbers-in-the-given-range/ ```javascript function range({ min, max }) { return Array.from({ length: max - min + 1 }, (_, i) => min + i); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The lab requires min ≤ max and at most 1,000 numbers before allocating. ### Create cartesian product Combine one item from each set in every possible way. https://1loc.dev/array/create-cartesian-product/ ```javascript function cartesian(sets) { return sets.reduce((product, set) => product.flatMap(prefix => set.map(item => [...prefix, item])), [[]]); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The result size is the product of the set sizes; the lab caps it at 1,000 combinations. ### Find the minimum item of an array Spread the numbers into Math.min. https://1loc.dev/array/find-the-minimum-item-of-an-array/ ```javascript function min(values) { return Math.min(...values); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). An empty array returns Infinity (null in JSON); check the length first. Spreading very large arrays can exceed the argument limit; reduce instead. ### Get the rank of an array of numbers Rank each number by how many values are larger, starting at 1. https://1loc.dev/array/get-the-rank-of-an-array-of-numbers/ ```javascript function ranking(values) { return values.map(value => values.filter(other => other > value).length + 1); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Ties share a rank and the next rank is skipped (competition ranking). ### Remove falsy values from array Filter with Boolean. https://1loc.dev/array/remove-falsy-values-from-array/ ```javascript function removeFalsy(values) { return values.filter(Boolean); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). 0 and "" are falsy too — filter explicitly when they are valid values. ### Zip multiple arrays Pair the n-th items of several arrays. https://1loc.dev/array/zip-multiple-arrays/ ```javascript function zip(arrays) { return Array.from({ length: Math.max(0, ...arrays.map(array => array.length)) }, (_, i) => arrays.map(array => array[i] ?? null)); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Missing items become null (undefined in the original) so the result is JSON-representable. ### Compare two arrays regardless of order Compare the sorted sets of distinct values. https://1loc.dev/array/compare-two-arrays-regardless-of-order/ ```javascript function isEqualIgnoringOrder({ a, b }) { const normalize = values => JSON.stringify([...new Set(values)].sort()); return normalize(a) === normalize(b); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Duplicates are ignored, as the edge case shows; compare counts when multiplicity matters. ### Count by the properties of an array of objects Tally records by the value of one field. https://1loc.dev/array/count-by-the-properties-of-an-array-of-objects/ ```javascript function countBy({ values, key }) { return { ...values.reduce((counts, item) => ((counts[item[key]] = (counts[item[key]] || 0) + 1), counts), Object.create(null)) }; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Records without the field are counted under "undefined". ### Create an array of cumulative sum Replace each number with the running total up to it. https://1loc.dev/array/create-an-array-of-cumulative-sum/ ```javascript function accumulate(values) { let total = 0; return values.map(value => (total += value)); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Floating-point totals can drift; sum integer minor units for money. ### Find the index of the maximum item of an array Return the index of the first largest number. https://1loc.dev/array/find-the-index-of-the-maximum-item-of-an-array/ ```javascript function indexOfMax(values) { return values.reduce((best, value, i) => (value > values[best] ? i : best), 0); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The first maximum wins on ties. An empty array returns 0, as in the original — check the length first. ### Find the maximum item of an array by given key Return the record with the largest value in a field. https://1loc.dev/array/find-the-maximum-item-of-an-array-by-given-key/ ```javascript function maxBy({ values, key }) { return values.reduce((best, item) => (best === null || item[key] > best[key] ? item : best), null); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). An empty array returns null; the original returned {}. ### Find the maximum item of an array Spread the numbers into Math.max. https://1loc.dev/array/find-the-maximum-item-of-an-array/ ```javascript function max(values) { return Math.max(...values); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). An empty array returns -Infinity (null in JSON); check the length first. ### Generate an array of alphabet characters List the first count lowercase ASCII letters. https://1loc.dev/array/generate-an-array-of-alphabet-characters/ ```javascript function alphabet(count) { return Array.from({ length: count }, (_, i) => String.fromCharCode(97 + i)); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original produced all 26 letters as a constant; a count input makes it runnable here. ### Get all arrays of consecutive elements Slide a window of a given size across an array. https://1loc.dev/array/get-all-arrays-of-consecutive-elements/ ```javascript function windows({ values, size }) { return size > values.length ? [] : values.slice(size - 1).map((_, i) => values.slice(i, i + size)); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A window larger than the array yields no windows. ### Get indices of a value in an array Collect every index where a value appears. https://1loc.dev/array/get-indices-of-a-value-in-an-array/ ```javascript function indices({ values, value }) { return values.flatMap((item, i) => (item === value ? [i] : [])); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original second variant dropped index 0, because filter(Boolean) removes it; flatMap keeps it. ### Get the average of an array Divide the sum by the count. https://1loc.dev/array/get-the-average-of-an-array/ ```javascript function average(values) { return values.reduce((sum, value) => sum + value, 0) / values.length; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Floating-point sums are approximate, as the edge case shows. ### Get the unique values of an array Keep the first occurrence of each value with a Set. https://1loc.dev/array/get-the-unique-values-of-an-array/ ```javascript function uniqueValues(values) { return [...new Set(values)]; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Same idea as Remove duplicate values; SameValueZero treats NaN as equal to NaN. ### Intersperse element between elements Insert a separator between every pair of items. https://1loc.dev/array/intersperse-element-between-elements/ ```javascript function intersperse({ values, separator }) { return values.flatMap((value, i) => (i === 0 ? [value] : [separator, value])); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original built Array(2n − 1), which throws for an empty array; flatMap returns []. ### Sort an array of items by given key Return a copy sorted by one field, ascending. https://1loc.dev/array/sort-an-array-of-items-by-given-key/ ```javascript function sortBy({ values, key }) { return [...values].sort((a, b) => (a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0)); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Mixed types compare unpredictably; keep the field one type. ### Check if an array is empty Return true for an array without items. https://1loc.dev/array/check-if-an-array-is-empty/ ```javascript function isEmptyArray(value) { return Array.isArray(value) && !value.length; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Non-arrays return false rather than throwing. ### Find the closest number from an array Return the item nearest to a target. https://1loc.dev/array/find-the-closest-number-from-an-array/ ```javascript function closest({ values, target }) { return values.reduce((best, value) => (Math.abs(value - target) < Math.abs(best - target) ? value : best)); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The first candidate wins on ties, as the edge case shows. The lab requires at least one number. ### Find the index of the minimum item of an array Return the index of the first smallest number. https://1loc.dev/array/find-the-index-of-the-minimum-item-of-an-array/ ```javascript function indexOfMin(values) { return values.reduce((best, value, i) => (value < values[best] ? i : best), 0); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The first minimum wins on ties. An empty array returns 0 — check the length first. ### Find the length of the longest string in an array Map strings to lengths and take the maximum. https://1loc.dev/array/find-the-length-of-the-longest-string-in-an-array/ ```javascript function longestLength(words) { return Math.max(0, ...words.map(word => word.length)); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Starting from 0 makes an empty array return 0; the original returned -Infinity. ### Find the minimum item of an array by given key Return the record with the smallest value in a field. https://1loc.dev/array/find-the-minimum-item-of-an-array-by-given-key/ ```javascript function minBy({ values, key }) { return values.reduce((best, item) => (best === null || item[key] < best[key] ? item : best), null); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). An empty array returns null; the original returned {}. ### Get all nth items of an array Keep every nth item, starting with the nth. https://1loc.dev/array/get-all-nth-items-of-an-array/ ```javascript function getNthItems({ values, nth }) { return values.filter((_, i) => i % nth === nth - 1); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). nth must be a positive integer. ### Merge two arrays Concatenate two arrays, optionally dropping duplicates. https://1loc.dev/array/merge-two-arrays/ ```javascript function merge({ a, b, unique = false }) { return unique ? [...new Set([...a, ...b])] : [...a, ...b]; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original page showed both versions; unique selects one. ### Repeat an array Concatenate an array with itself n times. https://1loc.dev/array/repeat-an-array/ ```javascript function repeatArray({ values, times }) { return Array(times).fill(values).flat(); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). flat() flattens one level only, so nested arrays inside values stay nested. ### Empty an array Remove every item in place, so all references see an empty array. https://1loc.dev/array/empty-an-array/ ```javascript function empty(values) { values.length = 0; return values; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Setting length mutates the array. Assigning [] only rebinds one variable, as the second example shows. ### Find the index of the last matching item of an array Scan from the end and return the first index whose item matches. https://1loc.dev/array/find-the-index-of-the-last-matching-item-of-an-array/ ```javascript function lastIndex(values, predicate) { return values.findLastIndex(predicate); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Array.prototype.findLastIndex is ES2023: Node.js 18+ and current browsers. The original reduced the whole array; findLastIndex stops at the first match from the end. ### Partition an array based on a condition Split items into [matching, not matching] in one pass. https://1loc.dev/array/partition-an-array-based-on-a-condition/ ```javascript function partition(values, predicate) { return values.reduce((groups, value) => (groups[predicate(value) ? 0 : 1].push(value), groups), [[], []]); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The predicate’s result is tested for truthiness: n % 2 puts odd numbers first. ### Shuffle an array Return a new array in random order, every order equally likely. https://1loc.dev/array/shuffle-an-array/ ```javascript function shuffle(values) { const result = [...values]; for (let i = result.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [result[i], result[j]] = [result[j], result[i]]; } return result; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Fisher–Yates in O(n). The original sorted by random keys, which is also unbiased but O(n log n); avoid sort(() => Math.random() - 0.5), which is biased. ## validator ### Check whether all values are equal Compare every item with the first using Object.is. https://1loc.dev/validator/check-if-all-items-in-an-array-are-equal/ ```javascript function allEqual(values) { return values.every(value => Object.is(value, values[0])); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The empty array returns true: no item violates the condition. ### Check whether an object is empty Check for own enumerable string keys on a JSON object. https://1loc.dev/validator/check-if-an-object-is-empty/ ```javascript function isEmpty(value) { return Object.keys(value).length === 0; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Input must be a non-null object, not an array. Symbol and non-enumerable keys are outside this JSON contract. ### Check whether an integer is even Test parity for safe integers, including zero and negative values. https://1loc.dev/validator/check-if-a-number-is-even/ ```javascript function isEven(value) { return value % 2 === 0; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The input must be a safe integer. Fractional values are rejected. ### Check a leap year Apply the Gregorian divisible-by-4, century and 400-year rules. https://1loc.dev/validator/check-if-a-year-is-leap-year/ ```javascript function isLeapYear(year) { return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Input is an integer year from 1 to 9,999 in the proleptic Gregorian calendar. ### Check if a character is a digit Test that a string is exactly one ASCII digit from 0 to 9. https://1loc.dev/validator/check-if-a-character-is-a-digit/ ```javascript function isDigit(char) { return /^[0-9]$/.test(char); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original `char < 10` accepted "", " " and "-1" because of numeric coercion, and one variant referenced an undefined variable. This version tests exactly one ASCII digit. ### Check if a date is a weekend Return true when a YYYY-MM-DD date falls on a Saturday or Sunday. https://1loc.dev/validator/check-if-a-date-is-a-weekend/ ```javascript function isWeekend(date) { return new Date(date).getUTCDay() % 6 === 0; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The date is read as a UTC calendar day, so the result does not depend on the machine’s time zone. The original used local time on a Date object. ### Check if a flat array has duplicate values Compare the size of a Set with the array length. https://1loc.dev/validator/check-if-a-flat-array-has-duplicate-values/ ```javascript function hasDuplicates(values) { return new Set(values).size !== values.length; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Values use SameValueZero: NaN equals NaN, and objects compare by reference. ### Check if a date is between two dates Test whether a YYYY-MM-DD date falls inside an inclusive range. https://1loc.dev/validator/check-if-a-date-is-between-two-dates/ ```javascript function isBetween({ date, min, max }) { const time = Date.parse(date); return time >= Date.parse(min) && time <= Date.parse(max); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Both ends are included. Dates are UTC calendar days, so the machine’s time zone does not matter. ### Check if a date is today Compare the UTC calendar day of a date-time with the current one. https://1loc.dev/validator/check-if-a-date-is-today/ ```javascript function isToday({ dateTime, now }) { return new Date(dateTime).toISOString().slice(0, 10) === new Date(now).toISOString().slice(0, 10); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). now is an input so the result is testable; pass new Date().toISOString() in your code. ### Check if a date occurs in the current year Compare the UTC year of a date-time with the current one. https://1loc.dev/validator/check-if-a-date-occurs-in-the-current-year/ ```javascript function isCurrentYear({ dateTime, now }) { return new Date(dateTime).getUTCFullYear() === new Date(now).getUTCFullYear(); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The year is the UTC year: New Year’s Eve at 23:00 in São Paulo is already 2026 in UTC, as the edge case shows. ### Check if a given integer is a prime number Trial division up to the square root, without allocating an array. https://1loc.dev/validator/check-if-a-given-integer-is-a-prime-number/ ```javascript function isPrime(n) { if (n < 2) return false; for (let i = 2; i * i <= n; i++) if (n % i === 0) return false; return true; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original built an array of candidates; a loop stops at the first divisor and allocates nothing. ### Check if a number is positive Return true for numbers greater than zero. https://1loc.dev/validator/check-if-a-number-is-positive/ ```javascript function isPositive(n) { return Math.sign(n) === 1; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Zero is neither positive nor negative. ### Check if a string contains upper case characters Compare a string with its lowercase form. https://1loc.dev/validator/check-if-a-string-contains-upper-case-characters/ ```javascript function containsUpperCase(text) { return text !== text.toLowerCase(); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Any cased letter counts, in any script. Digits and symbols never do. ### Check if a date is a weekday Return true for a YYYY-MM-DD date from Monday to Friday. https://1loc.dev/validator/check-if-a-date-is-a-weekday/ ```javascript function isWeekday(date) { return new Date(date).getUTCDay() % 6 !== 0; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Reads the UTC calendar day; the original used local time on a Date object. Public holidays are not considered. ### Check if a number is a power of 2 Use the bit trick n & (n − 1) on a positive integer. https://1loc.dev/validator/check-if-a-number-is-a-power-of-2/ ```javascript function isPowerOfTwo(n) { return n > 0 && (n & (n - 1)) === 0; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original returned true for 0; this version requires n > 0. ### Check if a number is negative Return true for numbers below zero. https://1loc.dev/validator/check-if-a-number-is-negative/ ```javascript function isNegative(n) { return n < 0; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). -0 is not negative here, matching n < 0. ### Check if a string contains only letters and numbers Test for one or more ASCII letters or digits. https://1loc.dev/validator/check-if-a-string-contains-only-letters-and-numbers/ ```javascript function isAlphanumeric(text) { return /^[0-9A-Z]+$/i.test(text); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). ASCII only: accented letters and spaces fail. The empty string fails too. ### Check if a string is a MongoDB ObjectId Test for exactly 24 hexadecimal characters. https://1loc.dev/validator/check-if-a-string-is-a-mongo-db-object-id/ ```javascript function isMongoId(text) { return /^[0-9a-f]{24}$/i.test(text); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). This checks the format only, not that the document exists. ### Check if a string is upper case Compare a string with its uppercase form. https://1loc.dev/validator/check-if-a-string-is-upper-case/ ```javascript function isUpperCase(text) { return text === text.toUpperCase(); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A string without letters is unchanged by toUpperCase, so it counts as upper case, as the edge case shows. ### Check if all array elements are equal to a given value Compare every item with a value using ===. https://1loc.dev/validator/check-if-all-array-elements-are-equal-to-a-given-value/ ```javascript function isEqual({ values, value }) { return values.every(item => item === value); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). An empty array returns true: no item differs. ### Check if a number is in a given range Test an inclusive range whose ends may be given in any order, with an optional tolerance. https://1loc.dev/validator/check-if-a-number-is-in-a-given-range/ ```javascript function inRange({ value, a, b, threshold = 0 }) { return Math.min(a, b) - threshold <= value && value <= Math.max(a, b) + threshold; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Both ends are included; threshold widens the range on both sides. ### Check if a number is odd Test that an integer leaves a remainder when divided by 2. https://1loc.dev/validator/check-if-a-number-is-odd/ ```javascript function isOdd(n) { return n % 2 !== 0; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Comparing with !== 0 handles negatives: -3 % 2 is -1. ### Check if a string contains lower case characters Compare a string with its uppercase form. https://1loc.dev/validator/check-if-a-string-contains-lower-case-characters/ ```javascript function containsLowerCase(text) { return text !== text.toUpperCase(); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Any cased letter counts, in any script. ### Check if a string contains only ASCII characters Test that every character is in the 0–127 range. https://1loc.dev/validator/check-if-a-string-contains-only-ascii-characters/ ```javascript function isAscii(text) { return /^[\x00-\x7F]+$/.test(text); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The empty string fails. ### Check if a string contains only digits Test for one or more ASCII digits. https://1loc.dev/validator/check-if-a-string-contains-only-digits/ ```javascript function isNumeric(text) { return /^[0-9]+$/.test(text); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original returned true for the empty string; this version requires at least one digit. ### Check if a string contains only letters Test for one or more ASCII letters. https://1loc.dev/validator/check-if-a-string-contains-only-letters/ ```javascript function isAlpha(text) { return /^[A-Z]+$/i.test(text); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). ASCII only: use /^\p{L}+$/u for letters in any script. ### Check if a string is a hexadecimal color Accept #rgb, #rgba, #rrggbb and #rrggbbaa. https://1loc.dev/validator/check-if-a-string-is-a-hexadecimal-color/ ```javascript function isHexColor(color) { return /^#([0-9A-F]{3}|[0-9A-F]{4}|[0-9A-F]{6}|[0-9A-F]{8})$/i.test(color); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Named colors, rgb() and hsl() are not hexadecimal. ### Check if a string is a hexadecimal number Test for one or more hexadecimal digits. https://1loc.dev/validator/check-if-a-string-is-a-hexadecimal-number/ ```javascript function isHexadecimal(text) { return /^[0-9a-f]+$/i.test(text); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A 0x prefix fails, as the edge case shows; strip it first. ### Check if a string is an octal number Test for octal digits with an optional 0o prefix. https://1loc.dev/validator/check-if-a-string-is-an-octal-number/ ```javascript function isOctal(text) { return /^(0o)?[0-7]+$/i.test(text); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Legacy leading-zero octal such as 0755 passes as plain digits. ### Check if a string is lower case Compare a string with its lowercase form. https://1loc.dev/validator/check-if-a-string-is-lower-case/ ```javascript function isLowerCase(text) { return text === text.toLowerCase(); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A string without letters counts as lower case. ### Check if a value is a business identifier code Test the shape of an 8- or 11-character BIC (SWIFT) code. https://1loc.dev/validator/check-if-a-value-is-a-business-identifier-code/ ```javascript function isBic(value) { return /^[a-zA-Z]{6}[a-zA-Z0-9]{2}([a-zA-Z0-9]{3})?$/.test(value); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). This checks the ISO 9362 format only — not that the institution or country code exists. ### Check if a value is a plain object Return true for objects whose prototype is Object.prototype or null. https://1loc.dev/validator/check-if-a-value-is-a-plain-object/ ```javascript function isPlainObject(value) { return value !== null && typeof value === 'object' && [null, Object.prototype].includes(Object.getPrototypeOf(value)); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Uses Object.getPrototypeOf instead of the __proto__ accessor, which an own "__proto__" key can shadow. ### Check if a value is a string Use Object.prototype.toString so String objects count too. https://1loc.dev/validator/check-if-a-value-is-a-string/ ```javascript function isString(value) { return Object.prototype.toString.call(value) === '[object String]'; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). typeof value === "string" is enough unless you must accept new String() objects. ### Check if a value is base32 encoded Test the RFC 4648 base32 alphabet and a length that is a multiple of 8. https://1loc.dev/validator/check-if-a-value-is-base32-encoded/ ```javascript function isBase32(value) { return value.length % 8 === 0 && /^[A-Z2-7]+=*$/.test(value); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Uppercase alphabet only; the amount of padding is not verified. ### Check if a value is base58 encoded Test the Bitcoin base58 alphabet, which leaves out 0, O, I and l. https://1loc.dev/validator/check-if-a-value-is-base58-encoded/ ```javascript function isBase58(value) { return /^[A-HJ-NP-Za-km-z1-9]*$/.test(value); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The empty string passes; checksums such as Base58Check are not verified. ### Check if a value is nil Return true for null and undefined. https://1loc.dev/validator/check-if-a-value-is-nil/ ```javascript function isNil(value) { return value == null; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). == null is the one loose comparison worth keeping: it matches exactly null and undefined. JSON cannot express undefined. ### Check if an array is not empty Return true for an array with at least one item. https://1loc.dev/validator/check-if-an-array-is-not-empty/ ```javascript function isNotEmpty(value) { return Array.isArray(value) && value.length > 0; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Uses length rather than Object.keys; the two differ only for sparse arrays, which JSON cannot express. ### Check if an array is a subset of another array Return true when every value of subset appears in of. https://1loc.dev/validator/check-if-an-array-is-subset-of-other-array/ ```javascript function isSubset({ subset, of }) { const all = new Set(of); return subset.every(value => all.has(value)); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original comment said “b is a subset of a” while its code tested the opposite, and its second variant compared joined strings. Named fields remove the ambiguity. ### Validate a Gregorian date Check that a year, a 1-based month and a day form a real calendar date. https://1loc.dev/validator/validate-a-gregorian-date/ ```javascript function isValidDate({ year, month, day }) { const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); return day >= 1 && day <= [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1]; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original used a zero-based month with new Date(y, m, 0), which reads the previous month’s length and accepted February 30. This version uses a 1-based month and explicit Gregorian rules. ### Check if a string contains whitespace Test for any whitespace character. https://1loc.dev/validator/check-if-a-string-contains-whitespace/ ```javascript function containsWhitespace(text) { return /\s/.test(text); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original returned a function — which is always truthy — instead of a boolean. This version returns the test result. ### Check if a value is a number Accept finite numbers and numeric strings. https://1loc.dev/validator/check-if-a-value-is-a-number/ ```javascript function isNumber(value) { return !isNaN(parseFloat(value)) && isFinite(value); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Numeric strings pass on purpose. For numbers only, use Number.isFinite(value). ### Check if a value is an object Return true for any non-null object, including arrays. https://1loc.dev/validator/check-if-a-value-is-an-object/ ```javascript function isObject(value) { return value !== null && typeof value === 'object'; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Arrays are objects here; use the plain-object check to exclude them. ### Check if a value is base64 encoded Test standard, padded base64. https://1loc.dev/validator/check-if-a-value-is-base64-encoded/ ```javascript function isBase64(value) { return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/.test(value); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Unpadded and URL-safe (- _) variants fail. Oveyon expects standard base64 for attachment content. ### Check if an object is an array Use Array.isArray, which works across realms. https://1loc.dev/validator/check-if-an-object-is-an-array/ ```javascript function isArray(value) { return Array.isArray(value); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Prefer Array.isArray to instanceof Array, which fails for arrays from another frame. ### Check if a value is a regular expression Read the internal tag, which also works for values from another realm. https://1loc.dev/validator/check-if-a-value-is-a-regular-expression/ ```javascript function isRegExp(value) { return Object.prototype.toString.call(value) === '[object RegExp]'; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Works across realms (iframes, vm contexts), where instanceof RegExp fails. Symbol.toStringTag can spoof the tag. ### Check if an array contains a value matching some criterias True when at least one item satisfies the predicate. https://1loc.dev/validator/check-if-an-array-contains-a-value-matching-some-criterias/ ```javascript function contains(values, predicate) { return values.some(predicate); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). some stops at the first match and returns false for an empty array, as the last line shows. ### Check if an object is a Promise Detect a thenable: an object or function with a then method. https://1loc.dev/validator/check-if-an-object-is-a-promise/ ```javascript function isPromise(value) { return value !== null && (typeof value === 'object' || typeof value === 'function') && typeof value.then === 'function'; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). This detects thenables, which is what await and Promise.resolve accept; a plain object with then counts, as the second line shows. ## object ### Pick properties from an object Build a new object with only the requested own properties. https://1loc.dev/object/pick-a-subset-of-properties-of-an-object/ ```javascript function pick({ value, keys }) { return Object.fromEntries(keys.filter(key => Object.hasOwn(value, key)).map(key => [key, value[key]])); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Missing and inherited properties are skipped. Values are not deeply cloned. ### Omit properties from an object Keep the own enumerable fields that are not in a supplied list. https://1loc.dev/object/omit-a-subset-of-properties-from-an-object/ ```javascript function omit({ value, keys }) { return Object.fromEntries(Object.entries(value).filter(([key]) => !keys.includes(key))); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). This copies enumerable string-keyed properties only. Values remain shared. ### Create an object from pairs of key and value Turn [key, value] pairs into a plain object with Object.fromEntries. https://1loc.dev/object/create-an-object-from-the-pairs-of-key-and-value/ ```javascript function toObject(pairs) { return Object.fromEntries(pairs); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). When a key repeats, the later pair wins, as the edge case shows. ### Check if multiple objects are equal Compare JSON serializations with the first object. https://1loc.dev/object/check-if-multiple-objects-are-equal/ ```javascript function areEqual(objects) { return objects.every(object => JSON.stringify(object) === JSON.stringify(objects[0])); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Key order matters to JSON.stringify, as the edge case shows; undefined values and functions are dropped. Use a deep-equality library for robust comparison. ### Get the value at given path of an object Follow a dot-separated path, stopping at a missing step. https://1loc.dev/object/get-the-value-at-given-path-of-an-object/ ```javascript function getValue({ path, object }) { return path.split('.').reduce((value, key) => (value == null ? undefined : value[key]), object) ?? null; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Missing paths return null here (undefined in the original), so the result is JSON-representable. ### Immutably rename object keys Return a copy with keys renamed through a mapping. https://1loc.dev/object/immutably-rename-object-keys/ ```javascript function renameKeys({ keysMap, object }) { return Object.fromEntries(Object.entries(object).map(([key, value]) => [keysMap[key] || key, value])); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Object.fromEntries replaces the original reduce with spread, which copied the accumulator on every key. ### Invert keys and values of an object Swap every key with its value. https://1loc.dev/object/invert-keys-and-values-of-an-object/ ```javascript function invert(object) { return Object.fromEntries(Object.entries(object).map(([key, value]) => [value, key])); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Values become string keys; duplicates keep the last key, as the edge case shows. ### Extract values of a property from an array of objects Pluck one field from every record. https://1loc.dev/object/extract-values-of-a-property-from-an-array-of-objects/ ```javascript function pluck({ objects, property }) { return objects.map(object => object[property] ?? null); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Missing fields become null (undefined in the original). ### Sort an object by its properties Rebuild an object with its keys in sorted order. https://1loc.dev/object/sort-an-object-by-its-properties/ ```javascript function sortKeys(object) { return Object.fromEntries(Object.keys(object).sort().map(key => [key, object[key]])); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Integer-like keys always come first in ascending numeric order, whatever you sort, as the edge case shows. Useful for stable JSON before hashing — but sign raw bytes, as webhooks do. ### Remove all null and undefined properties from an object Drop keys whose value is null or undefined. https://1loc.dev/object/remove-all-null-and-undefined-properties-from-an-object/ ```javascript function removeNullish(object) { return Object.fromEntries(Object.entries(object).filter(([, value]) => value != null)); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Only null and undefined are removed: 0, "" and false stay, as the edge case shows. ### Shallow copy an object Copy own enumerable properties into a new object. https://1loc.dev/object/shallow-copy-an-object/ ```javascript function shallowCopy(object) { return { ...object }; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Nested objects are shared, not copied. Use structuredClone for a deep copy. ### Get unique objects from an array by key Keep one record per key value, the last one seen. https://1loc.dev/object/get-unique-arr-obj/ ```javascript function uniqueBy({ objects, key }) { return [...new Map(objects.map(item => [item[key], item])).values()]; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The last record per key wins, in the position of the first one — handy for keeping the latest state per recipient. ### Create an empty map that does not have properties An object with no prototype: no inherited keys such as toString or __proto__. https://1loc.dev/object/create-an-empty-map-that-does-not-have-properties/ ```javascript function createDictionary() { return Object.create(null); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Keys from user input, such as "__proto__", stay ordinary data, as the last lines show. ## string ### Capitalize a string Uppercase the first Unicode code point and preserve the remaining text. https://1loc.dev/string/capitalize-a-string/ ```javascript function capitalize(value) { const [first, ...rest] = Array.from(value); return first ? first.toUpperCase() + rest.join('') : ''; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Uppercasing can expand a character, such as ß into SS. This is not locale-aware title casing. ### Reverse a string Reverse Unicode code points without splitting surrogate pairs. https://1loc.dev/string/reverse-a-string/ ```javascript function reverse(value) { return Array.from(value).reverse().join(''); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Combining marks and joined emoji can still split: code points are not grapheme clusters. ### Check a palindrome Compare a string with its code-point reversal. https://1loc.dev/string/check-if-a-string-is-a-palindrome/ ```javascript function palindrome(value) { return value === Array.from(value).reverse().join(''); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Case, punctuation, spaces and Unicode normalization are significant. ### Create a simple URL slug Normalize a Latin-text label into lowercase ASCII words separated by hyphens. https://1loc.dev/string/convert-a-string-to-url-slug/ ```javascript function slugify(value) { return value.normalize('NFKD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, ''); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). This deliberately produces ASCII slugs. Many non-Latin scripts become empty. ### Convert snake case to camel case Uppercase a lowercase ASCII letter immediately after an underscore. https://1loc.dev/string/convert-snake-case-to-camel-case/ ```javascript function camelCase(value) { return value.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Consecutive underscores, digits and uppercase letters are preserved unless directly matched. ### Remove duplicate lines Keep the first occurrence of every exact line while normalizing CRLF to LF. https://1loc.dev/string/remove-duplicate-lines-of-a-text-document/ ```javascript function uniqueLines(value) { return [...new Set(value.split(/\r?\n/))].join('\n'); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Whitespace and case matter. One empty line is retained; line endings become LF. ### Check if a URL is absolute Detect a scheme such as https: at the start of a URL string. https://1loc.dev/string/check-if-a-url-is-absolute/ ```javascript function isAbsoluteUrl(url) { return /^[a-z][a-z0-9+.-]*:/i.test(url); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A scheme is not a safety check: javascript: and data: URLs are absolute too. Allow-list https: before storing or following a URL, such as a webhook endpoint. ### Check if a path is relative Return true unless the path starts with a slash or backslash, optionally after a drive or scheme. https://1loc.dev/string/check-if-a-path-is-relative/ ```javascript function isRelative(path) { return !/^([a-z]+:)?[\\/]/i.test(path); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A scheme without slashes, such as mailto: or data:, still counts as relative. Use the URL-absolute check for URLs. ### Convert a base64 encoded string to an Uint8Array Decode base64 into its byte values. https://1loc.dev/string/convert-a-base64-encoded-string-to-an-uint8-array/ ```javascript function base64ToBytes(base64) { return Array.from(atob(base64), char => char.charCodeAt(0)); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Returns plain numbers so the lab can show them; wrap the result with Uint8Array.from in your code. ### Convert an Uint8Array to a base64 encoded string Encode byte values as base64 with btoa. https://1loc.dev/string/convert-an-uint8-array-to-a-base64-encoded-string/ ```javascript function bytesToBase64(bytes) { return btoa(String.fromCharCode(...bytes)); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Spreading is fine for the lab’s 1,000 bytes. For files, use Buffer.from(bytes).toString("base64") in Node.js or encode in chunks. ### Check if a string consists of a repeated character sequence Find the string inside itself doubled, past the first position. https://1loc.dev/string/check-if-a-string-consists-of-a-repeated-character-sequence/ ```javascript function consistsRepeatedSubstring(text) { return `${text}${text}`.indexOf(text, 1) !== text.length; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The empty string returns false. Comparison is by UTF-16 code units. ### Check if two strings are anagrams Compare the sorted, lowercased characters of both strings. https://1loc.dev/string/check-if-two-strings-are-anagram/ ```javascript function areAnagram({ first, second }) { const sorted = text => Array.from(text.toLowerCase()).sort().join(''); return sorted(first) === sorted(second); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Spaces and punctuation count, as the edge case shows; strip them first for phrase anagrams. ### Convert a letter to its regional indicator emoji Map a–z to the regional indicator symbols 🇦–🇿. https://1loc.dev/string/convert-a-letter-to-associate-emoji/ ```javascript function letterToEmoji(letter) { return String.fromCodePoint(letter.toLowerCase().charCodeAt(0) + 127365); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Input is one ASCII letter. Two indicators side by side render as a country flag in many fonts. ### Sort the characters of a string in alphabetical order Sort code points with an explicit English collation. https://1loc.dev/string/sort-the-characters-of-a-string-in-the-alphabetical-order/ ```javascript function sortCharacters(text) { return Array.from(text).sort((a, b) => a.localeCompare(b, 'en')).join(''); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original used the runtime’s default locale, which can differ between machines; this version names the locale. ### Generate a hash of a string Compute the 32-bit hash Java’s String.hashCode uses. https://1loc.dev/string/generate-a-hash-of-a-string/ ```javascript function hashString(text) { return text.split('').reduce((hash, char) => (Math.imul(31, hash) + char.charCodeAt(0)) | 0, 0); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Not cryptographic and collision-prone: use it for bucketing, never for integrity. To authenticate data use HMAC-SHA256, as in the webhook signature lab. ### Get the length of a string in bytes Count UTF-8 bytes rather than characters. https://1loc.dev/string/get-the-length-of-a-string-in-bytes/ ```javascript function byteLength(text) { return new TextEncoder().encode(text).length; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). UTF-8 is what most APIs and email bodies use. Email header lines are limited to 998 bytes excluding CRLF (RFC 5322); measure bytes, not characters. ### Strip ANSI codes from a string Remove terminal color and cursor escape sequences. https://1loc.dev/string/strip-ansi-codes-from-a-string/ ```javascript function stripAnsi(text) { return text.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, ''); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Covers SGR colors and common CSI sequences, not every operating-system command sequence. ### Swap case of characters in a string Uppercase lowercase letters and lowercase the rest. https://1loc.dev/string/swap-case-of-characters-in-a-string/ ```javascript function swapCase(text) { return Array.from(text).map(char => char === char.toLowerCase() ? char.toUpperCase() : char.toLowerCase()).join(''); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Case mapping can change length: ß uppercases to SS. ### Convert a string to Pascal case Join alphanumeric words, each starting with an uppercase letter. https://1loc.dev/string/convert-a-string-to-pascal-case/ ```javascript function toPascalCase(text) { return (text.match(/[a-zA-Z0-9]+/g) || []).map(word => `${word.charAt(0).toUpperCase()}${word.slice(1)}`).join(''); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Only ASCII letters and digits form words; accented letters split words. ### Convert a Windows file path to a Unix path Use forward slashes and drop a drive letter or leading ./. https://1loc.dev/string/convert-a-windows-file-path-to-unix-path/ ```javascript function toUnixPath(path) { return path.replace(/[\\/]+/g, '/').replace(/^([a-zA-Z]+:|\.\/)/, ''); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The drive letter is discarded, not mapped to a mount point. ### Convert camel case to kebab case and vice versa Switch a single identifier between camelCase and kebab-case. https://1loc.dev/string/convert-camel-case-to-kebab-case-and-vice-versa/ ```javascript function convertCase({ value, to }) { return to === 'kebab' ? value.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase() : value.replace(/-./g, match => match[1].toUpperCase()); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original page offered two functions; here one takes the target as to: "kebab" or "camel". ### Count the number of words in a string Count runs of non-whitespace characters. https://1loc.dev/string/count-the-number-of-words-in-a-string/ ```javascript function countWords(text) { return (text.match(/\S+/g) || []).length; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original split on whitespace and returned 1 for a blank string; this version returns 0. ### Get the file extension from a file name Return the text after the last dot, or an empty string. https://1loc.dev/string/get-the-file-extension-from-a-file-name/ ```javascript function fileExtension(name) { const dot = name.lastIndexOf('.'); return dot > 0 ? name.slice(dot + 1) : ''; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original returned the whole name when there was no dot. A leading dot marks a hidden file, not an extension. ### Get the file name from a URL Take the last path segment, ignoring the query and fragment. https://1loc.dev/string/get-the-file-name-from-a-url/ ```javascript function fileNameFromUrl(url) { const path = url.split(/[?#]/)[0]; return path.slice(path.lastIndexOf('/') + 1); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original kept the query string; this version drops ?… and #… first. ### Get the number of a character in a string Split on a character and count the pieces. https://1loc.dev/string/get-the-number-of-a-character-in-a-string/ ```javascript function characterCount({ text, char }) { return text.split(char).length - 1; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). char is a single character; longer strings count non-overlapping occurrences. ### Normalize file path slashes Collapse runs of slashes and backslashes into single forward slashes. https://1loc.dev/string/normalize-file-path-slashes/ ```javascript function normalizePath(path) { return path.replace(/[\\/]+/g, '/'); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). This also collapses the // after a URL scheme; do not apply it to URLs. ### Remove spaces from a string Delete every whitespace character, including tabs and line breaks. https://1loc.dev/string/remove-spaces-from-a-string/ ```javascript function removeSpaces(text) { return text.replace(/\s/g, ''); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). \s also matches non-breaking and other Unicode spaces. ### Repeat a string Concatenate a string with itself a given number of times. https://1loc.dev/string/repeat-a-string/ ```javascript function repeat({ text, times }) { return text.repeat(times); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The lab caps the result at 16,000 characters before allocating it. ### Replace all line breaks with br elements Turn LF and CRLF line breaks into
. https://1loc.dev/string/replace-all-line-breaks-with-br-elements/ ```javascript function nl2br(text) { return text.replace(/\r?\n/g, '
'); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Escape the text first. Converting untrusted text to HTML without escaping is an injection risk — in a web page and in an HTML email. ### Replace all tab characters with spaces Replace each tab with a fixed number of spaces. https://1loc.dev/string/replace-all-tab-characters-with-spaces/ ```javascript function tabsToSpaces({ text, spaces }) { return text.replaceAll('\t', ' '.repeat(spaces)); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). This does not align to tab stops; every tab becomes the same width. ### Mask the first characters of a string Replace the first count characters with a mask character, keeping the length. https://1loc.dev/string/replace-the-first-given-number-of-characters-of-a-string-with-another-character/ ```javascript function maskStart({ text, count, mask }) { return text.slice(count).padStart(text.length, mask); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Masking for display is not tokenization; never store or log the original value. ### Reverse the order of lines of a text Split on LF or CRLF and reverse the lines. https://1loc.dev/string/reverse-the-order-of-lines-of-a-text/ ```javascript function reverseLines(text) { return text.split(/\r?\n/).reverse().join('\n'); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Line endings become LF. ### Sort lines of a text document in alphabetical order Split into lines and sort them by UTF-16 code units. https://1loc.dev/string/sort-lines-of-a-text-document-in-the-alphabetical-order/ ```javascript function sortLines(text) { return text.split(/\r?\n/).sort().join('\n'); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Default sort order puts uppercase before lowercase, as the edge case shows. Use localeCompare for human ordering. ### Trim slashes at the beginning and the end of a string Remove leading and trailing forward slashes. https://1loc.dev/string/trim-slashes-at-the-beginning-and-the-end-of-a-string/ ```javascript function trimSlashes(text) { return text.replace(/^\/+|\/+$/g, ''); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Inner slashes are kept. ### Trim the file extension from a file name Remove the text from the last dot onward. https://1loc.dev/string/trim-the-file-extension-from-a-file-name/ ```javascript function trimExtension(name) { const dot = name.lastIndexOf('.'); return dot > 0 ? name.slice(0, dot) : name; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original turned ".env" into an empty string; a leading dot is kept here. ### Convert a string to camel case Remove separators and uppercase the character after each one. https://1loc.dev/string/convert-a-string-to-camel-case/ ```javascript function toCamelCase(text) { return text.trim().replace(/[-_\s]+(.)?/g, (_, char) => char ? char.toUpperCase() : ''); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A leading separator uppercases the first letter, as the edge case shows. The first word is otherwise kept as typed. ### Convert the name of an Excel column to a number Read a column name as a base-26 number where A is 1. https://1loc.dev/string/convert-the-name-of-an-excel-column-to-number/ ```javascript function columnNumber(column) { return column.split('').reduce((total, letter) => total * 26 + parseInt(letter, 36) - 9, 0); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The lab accepts 1–6 letters (up to ZZZZZZ). Lowercase letters work too. ### Count the occurrences of a character in a string Count code points equal to a given character. https://1loc.dev/string/count-the-occurrences-of-a-character-in-a-string/ ```javascript function countOccurrences({ text, char }) { return Array.from(text).filter(item => item === char).length; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Iterates code points, so emoji count once. ### Decapitalize a string Lowercase the first code point and keep the rest. https://1loc.dev/string/decapitalize-a-string/ ```javascript function decapitalize(text) { const [first = '', ...rest] = Array.from(text); return first.toLowerCase() + rest.join(''); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Not locale-aware: Turkish dotted İ needs toLocaleLowerCase("tr"). ### Escape HTML special characters Replace & < > " and ' with HTML entities. https://1loc.dev/string/escape-html-special-characters/ ```javascript function escapeHtml(text) { return text.replace(/[&<>"']/g, char => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char]); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Escape untrusted text before placing it in HTML, including HTML email templates. This protects text content and quoted attribute values, not URLs, scripts or CSS. ### Format a string Replace {0}, {1}… placeholders with values in order. https://1loc.dev/string/format-a-string/ ```javascript function format({ template, values }) { return values.reduce((text, value, i) => text.replaceAll(`{${i}}`, String(value)), template); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Replacements run in order, so a value containing "{1}" is replaced again by the next value. Use a template engine with escaping for HTML. ### Get the base URL without any parameters Drop the query string and fragment. https://1loc.dev/string/get-the-base-url-without-any-parameters/ ```javascript function baseUrl(url) { return url.split(/[?#]/)[0]; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original removed only the query; a fragment is not a parameter either, so it is dropped too. ### Make the first character of a string lowercase Lowercase only the first character. https://1loc.dev/string/make-the-first-character-of-a-string-lowercase/ ```javascript function lowercaseFirst(text) { return `${text.charAt(0).toLowerCase()}${text.slice(1)}`; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). charAt works on UTF-16 code units; for text that may start with an emoji, use the code-point version in Decapitalize a string. ### Prepend a line number to each line of a text document Number lines from 1, right-aligned to two characters. https://1loc.dev/string/prepend-a-line-number-to-each-line-of-a-text-document/ ```javascript function prependNumbers(text) { return text.split(/\r?\n/).map((line, i) => `${String(i + 1).padStart(2, ' ')} ${line}`).join('\n'); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Numbers above 99 widen the gutter. An empty text is one empty line. ### Replace multiple spaces with a single space Collapse runs of two or more whitespace characters. https://1loc.dev/string/replace-multiple-spaces-with-a-single-space/ ```javascript function collapseSpaces(text) { return text.replace(/\s\s+/g, ' '); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A single tab or line break is left as it is, as the edge case shows. ### Trim a character from both ends Remove a repeated character from the start and the end only. https://1loc.dev/string/trim-some-character/ ```javascript function trimCharacter({ text, char }) { const escaped = char.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); return text.replace(new RegExp(`^(?:${escaped})+|(?:${escaped})+$`, 'g'), ''); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original split on the character and joined with commas, which also removed inner characters; this version trims the ends only. ### Truncate a string at full words Cut at the last space that fits, then add a suffix. https://1loc.dev/string/truncate-a-string-at-full-words/ ```javascript function truncateWords({ text, max, suffix }) { if (text.length <= max) return text; const cut = text.slice(0, max - suffix.length); const space = cut.lastIndexOf(' '); return `${space > 0 ? cut.slice(0, space) : cut}${suffix}`; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original truncated strings exactly max long and returned only the suffix when the first word was too long; both are fixed. ### Unescape HTML special characters Turn & < > " and ' back into characters in one pass. https://1loc.dev/string/unescape-html-special-characters/ ```javascript function unescapeHtml(text) { return text.replace(/&(?:amp|lt|gt|quot|#0*39);/g, entity => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[entity] ?? "'"); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original replaced entities one after another, so "&lt;" became "<". A single pass keeps it as "<". ### Uppercase the first character of each word Capitalize every space-separated word. https://1loc.dev/string/uppercase-the-first-character-of-each-word-in-a-string/ ```javascript function uppercaseWords(text) { return text.split(' ').map(word => `${word.charAt(0).toUpperCase()}${word.slice(1)}`).join(' '); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Only spaces separate words; this is not language-aware title case. ### Remove empty lines of a text document Drop lines that are empty or whitespace only. https://1loc.dev/string/remove-empty-lines-of-a-text-document/ ```javascript function removeEmptyLines(text) { return text.split(/\r?\n/).filter(line => line.trim() !== '').join('\n'); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Line endings become LF. ### Decode numeric HTML entities Turn é and é style references into characters. https://1loc.dev/string/decode-html-entities/ ```javascript function decodeNumericEntities(text) { return text.replace(/&#(x[0-9a-f]+|\d+);/gi, (entity, code) => { const point = code[0].toLowerCase() === 'x' ? parseInt(code.slice(1), 16) : Number(code); return point <= 0x10ffff ? String.fromCodePoint(point) : entity; }); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Numeric references only; named ones such as é need an HTML parser. The original regex mishandled hexadecimal references. ## number ### Clamp a number to a range Keep a number inside an inclusive minimum and maximum. https://1loc.dev/number/clamp-a-number-between-two-values/ ```javascript function clamp({ value, min, max }) { return Math.min(max, Math.max(min, value)); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). All values must be finite numbers and min must not exceed max. ### Round to a number of digits Apply decimal scaling and JavaScript rounding for display-oriented values. https://1loc.dev/number/round-a-number-to-a-given-number-of-digits/ ```javascript function roundTo({ value, digits }) { const factor = 10 ** digits; return Math.round(value * factor) / factor; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Binary floating-point explains the 1.005 edge case. This is not exact decimal arithmetic. ### Add an ordinal suffix to a number Append st, nd, rd or th to a positive integer. https://1loc.dev/number/add-an-ordinal-suffix-to-a-number/ ```javascript function addOrdinal(n) { return `${n}${['st', 'nd', 'rd'][((((n + 90) % 100) - 10) % 10) - 1] || 'th'}`; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). 11, 12 and 13 take th, as the edge case shows. English only; use Intl.PluralRules({ type: "ordinal" }) for other languages. ### Calculate Fibonacci numbers Return the nth Fibonacci number with memoized recursion. https://1loc.dev/number/calculate-fibonacci-numbers/ ```javascript function fibonacci(n, memo = {}) { return memo[n] || (n <= 2 ? 1 : (memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo))); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The lab stops at n = 78, the largest Fibonacci number below Number.MAX_SAFE_INTEGER; use BigInt beyond it. ### Calculate the division of numbers Divide the first number by each of the others in turn. https://1loc.dev/number/calculate-the-division-of-arguments/ ```javascript function division(values) { return values.reduce((a, b) => a / b); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original used rest arguments; the lab passes one array with at least one number. Dividing by 0 gives Infinity (null in JSON). ### Calculate the mod of a collection index Wrap an index into 0…length−1, also for negative numbers. https://1loc.dev/number/calculate-the-mod-of-collection-index/ ```javascript function mod({ index, length }) { return ((index % length) + length) % length; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). JavaScript’s % keeps the sign of the dividend (-1 % 5 is -1); adding length first fixes it. ### Compute the greatest common divisor between two numbers Apply Euclid’s algorithm. https://1loc.dev/number/compute-the-greatest-common-divisor-between-two-numbers/ ```javascript function gcd({ a, b }) { return b === 0 ? Math.abs(a) : gcd({ a: b, b: a % b }); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Returns a non-negative result; the original could return a negative divisor. ### Calculate the average of numbers Divide the sum by the count. https://1loc.dev/number/calculate-the-average-of-arguments/ ```javascript function averageOf(values) { return values.reduce((a, b) => a + b) / values.length; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The lab passes one array with at least one number. ### Calculate the remainder of division of numbers Apply % from left to right. https://1loc.dev/number/calculate-the-remainder-of-division-of-arguments/ ```javascript function remainder(values) { return values.reduce((a, b) => a % b); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). % keeps the sign of the dividend, as the edge case shows; use the collection-index mod for wrapping. ### Subtract numbers Subtract each number from the first in turn. https://1loc.dev/number/subtract-arguments/ ```javascript function subtract(values) { return values.reduce((a, b) => a - b); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Binary floating-point: 0.3 − 0.1 is not exactly 0.2, as the edge case shows. ### Calculate the factorial of a number Multiply the integers from 1 to n recursively. https://1loc.dev/number/calculate-the-factorial-of-a-number/ ```javascript function factorial(n) { return n <= 1 ? 1 : n * factorial(n - 1); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The lab stops at 18: 19! exceeds Number.MAX_SAFE_INTEGER. Use BigInt for larger values. ### Calculate the sum of numbers Add numbers from left to right. https://1loc.dev/number/calculate-the-sum-of-arguments/ ```javascript function sumOf(values) { return values.reduce((a, b) => a + b); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Example: recipients per request — each recipient is one quota unit on Oveyon’s /v1/send. ### Convert a number to equivalent characters Turn a zero-based index into a spreadsheet-style column name. https://1loc.dev/number/convert-a-number-to-equivalent-characters/ ```javascript function toChars(n) { return `${n >= 26 ? toChars(Math.floor(n / 26) - 1) : ''}${'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[n % 26]}`; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Zero-based: 0 is A and 25 is Z. The inverse of Convert the name of an Excel column to a number, minus one. ### Multiply numbers Multiply numbers from left to right. https://1loc.dev/number/multiply-arguments/ ```javascript function multiply(values) { return values.reduce((a, b) => a * b); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The lab passes one array with at least one number. ### Truncate a number at decimal Drop the fractional part toward zero. https://1loc.dev/number/truncate-a-number-at-decimal/ ```javascript function truncate(n) { return Math.trunc(n); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original ~~n only works within 32 bits: ~~3000000000 is -1294967296. Math.trunc works for every number. ### Convert a string to a number Use unary plus. https://1loc.dev/number/convert-a-string-to-number/ ```javascript function toNumber(text) { return +text; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The empty string becomes 0 and invalid text becomes NaN (null in JSON). Validate first, or use Number.parseFloat for partial parsing. ### Convert decimal to binary recursively Build the binary digits of a non-negative integer as a decimal-looking number. https://1loc.dev/number/convert-decimal-to-binary-recursively/ ```javascript function decToBinary(num) { return num === 0 ? 0 : (num % 2) + 10 * decToBinary(Math.floor(num / 2)); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The result is a number whose digits are bits, so the lab stops at 65,535 to stay exact. For real work use num.toString(2). ### Prefix an integer with zeros Pad a non-negative integer to a given width. https://1loc.dev/number/prefix-an-integer-with-zeros/ ```javascript function prefixWithZeros({ n, length }) { return String(n).padStart(length, '0'); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Longer numbers are never cut, as the edge case shows. The original toFixed variant broke for numbers with as many digits as the width. ### Truncate a number to decimal places without rounding Cut the decimal representation after a number of digits. https://1loc.dev/number/truncate-a-number-to-a-given-number-of-decimal-places-without-rounding/ ```javascript function toFixedDown({ n, digits }) { return Number(`${n}`.match(new RegExp(`^-?\\d+(?:\\.\\d{0,${digits}})?`))[0]); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Works on the decimal string, so floating-point drift does not round the result up. ### Wrap a number between two values Map a number into [min, max) like an angle or a carousel index. https://1loc.dev/number/wrap-a-number-between-two-values/ ```javascript function wrap({ num, min, max }) { return ((((num - min) % (max - min)) + (max - min)) % (max - min)) + min; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). max is exclusive. The lab requires min < max. ### Get the arrays of digits from a number Split a non-negative integer into its decimal digits. https://1loc.dev/number/get-the-arrays-of-digits-from-a-number/ ```javascript function digitize(n) { return [...`${n}`].map(digit => Number(digit)); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Non-negative integers only: a minus sign or decimal point would not be a digit. ### Get the intersection range between two ranges Return the overlap of two closed ranges, or an empty array. https://1loc.dev/number/get-the-intersection-range-between-two-ranges/ ```javascript function intersectRanges({ a, b }) { return a[0] > b[1] || a[1] < b[0] ? [] : [Math.max(a[0], b[0]), Math.min(a[1], b[1])]; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Ranges are [start, end] with start ≤ end; touching ranges overlap in one point. ## misc ### Convert Celsius to Fahrenheit Apply the temperature conversion without rounding the result. https://1loc.dev/misc/convert-celsius-to-fahrenheit/ ```javascript function toFahrenheit(value) { return value * 9 / 5 + 32; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). This is a mathematical conversion. It does not enforce a physical temperature range. ### Convert hex to RGB Expand #rgb if needed and read the red, green and blue channels. https://1loc.dev/misc/convert-hex-to-rgb/ ```javascript function hexToRgb(hex) { return hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i, (_, r, g, b) => `#${r}${r}${g}${g}${b}${b}`).substring(1).match(/.{2}/g).map(channel => parseInt(channel, 16)); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Accepts #rgb and #rrggbb with or without #; alpha channels are outside this contract. ### Convert URL parameters to object Read a query string into an object; repeated keys become arrays. https://1loc.dev/misc/convert-url-parameters-to-object/ ```javascript function getUrlParams(query) { return Array.from(new URLSearchParams(query)).reduce((params, [key, value]) => Object.assign(params, { [key]: Object.hasOwn(params, key) ? [].concat(params[key], value) : value }), {}); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Values are strings; + decodes to a space as in HTML forms. ### Convert 3 digits color to 6 digits color Double each digit of a #rgb color. https://1loc.dev/misc/convert-3-digits-color-to-6-digits-color/ ```javascript function toFullHexColor(color) { return `#${(color.startsWith('#') ? color.slice(1) : color).split('').map(digit => `${digit}${digit}`).join('')}`; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Input must be three hexadecimal digits, with or without #. ### Convert Fahrenheit to Celsius Subtract 32 and multiply by 5/9. https://1loc.dev/misc/convert-fahrenheit-to-celsius/ ```javascript function fahrenheitToCelsius(fahrenheit) { return (fahrenheit - 32) * 5 / 9; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The inverse of Convert Celsius to Fahrenheit; results are not rounded. ### Get the value of a param from a URL Parse an absolute URL and read one query parameter. https://1loc.dev/misc/get-the-value-of-a-param-from-a-url/ ```javascript function getParam({ url, param }) { return new URL(url).searchParams.get(param); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A missing parameter returns null. Repeated parameters return the first value; use getAll for every value. ### Convert RGB color to hex Pack three 0–255 channels into a #rrggbb string. https://1loc.dev/misc/convert-rgb-color-to-hex/ ```javascript function rgbToHex({ red, green, blue }) { return `#${((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1)}`; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The 1 << 24 term keeps leading zeros. Channels must be integers from 0 to 255. ### Convert cookie to object Parse a Cookie header string into name–value pairs. https://1loc.dev/misc/convert-cookie-to-object/ ```javascript function parseCookies(cookie) { return Object.fromEntries(cookie.split(';').filter(item => item.includes('=')).map(item => [item.slice(0, item.indexOf('=')).trim(), item.slice(item.indexOf('=') + 1).trim()])); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original read document.cookie and split on every =, which cut values such as "abc=def"; this version parses any header string and splits on the first = only. ### Easing functions Evaluate a common easing curve at progress t between 0 and 1. https://1loc.dev/misc/easing-functions/ ```javascript function ease({ name, t }) { return { linear: t, easeInQuad: t * t, easeOutQuad: t * (2 - t), easeInOutQuad: t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t, easeInCubic: t ** 3, easeOutCubic: (t - 1) ** 3 + 1 }[name]; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original listed separate functions; one function selects the curve by name. Curves follow the gist the original cites (gre/1650294). ### Encode a URL component strictly Percent-encode a value, including !'()* that encodeURIComponent leaves alone. https://1loc.dev/misc/encode-a-url/ ```javascript function encodeStrict(value) { return encodeURIComponent(value).replace(/[!'()*]/g, char => `%${char.charCodeAt(0).toString(16).toUpperCase()}`); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). RFC 3986 unreserved characters (- _ . ~) stay as they are, as the edge case shows. The original also encoded ~, which RFC 3986 leaves unreserved. ### Get the value of a cookie Find one cookie by name in a Cookie header string. https://1loc.dev/misc/get-the-value-of-a-cookie/ ```javascript function getCookie({ cookie, name }) { const match = `; ${cookie}`.split(`; ${name}=`); return match.length > 1 ? match.pop().split(';').shift() : null; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A missing cookie returns null; the original returned the whole cookie string for an unknown name. ### Get the type of a variable as a string Read the internal [[Class]] tag via Object.prototype.toString. https://1loc.dev/misc/get-type-of-a-variable-in-string/ ```javascript function getTypeOf(value) { return Object.prototype.toString.call(value).match(/\[object (.*)\]/)[1]; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Distinguishes Array, Null, Date and RegExp where typeof says "object". Objects can override the tag with Symbol.toStringTag. ### Swap two variables Exchange two values with array destructuring. https://1loc.dev/misc/swap-two-variables/ ```javascript function swap([a, b]) { [a, b] = [b, a]; return [a, b]; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Destructuring works for any values. The original’s arithmetic tricks (a = b + ((b = a), 0)) only work for numbers and are harder to read. ### Decode a JWT token Read the JSON payload of a JSON Web Token — without verifying it. https://1loc.dev/misc/decode-a-jwt-token/ ```javascript function decodeJwtPayload(token) { const base64 = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'); return JSON.parse(decodeURIComponent(Array.from(atob(base64.padEnd(Math.ceil(base64.length / 4) * 4, '=')), char => `%${char.charCodeAt(0).toString(16).padStart(2, '0')}`).join(''))); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Decoding is not verification: anyone can forge a payload. Verify the signature with your JWT library before trusting any claim. ### Get the first defined and non-null value Return the first item that is neither null nor undefined. https://1loc.dev/misc/get-the-first-defined-and-non-null-argument/ ```javascript function coalesce(values) { return values.find(item => item !== undefined && item !== null) ?? null; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). 0 and "" count as defined, as the example shows — unlike ||. The ?? operator does the same for two values. ### Convert a Lab color to an LCH color Turn a and b into chroma and hue degrees. https://1loc.dev/misc/convert-a-lab-color-to-an-lch-color/ ```javascript function labToLch([l, a, b]) { return [l, Math.hypot(a, b), ((Math.atan2(b, a) * 180) / Math.PI + 360) % 360]; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Hue is normalized to 0–360°; the original could return negative hues, as the edge case would. ### Convert an LCH color to a Lab color Turn chroma and hue degrees back into a and b. https://1loc.dev/misc/convert-an-lch-color-to-a-lab-color/ ```javascript function lchToLab([l, c, h]) { return [l, Math.cos((h * Math.PI) / 180) * c, Math.sin((h * Math.PI) / 180) * c]; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Floating-point trigonometry leaves tiny residues such as 6e-16, as the edge case shows; round for display. ### Check if the code is running in Jest Look for the JEST_WORKER_ID variable that Jest sets in its workers. https://1loc.dev/misc/check-if-the-code-is-running-in-jest/ ```javascript function isRunningInJest() { return typeof process !== 'undefined' && process.env.JEST_WORKER_ID !== undefined; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Other runners, such as Vitest or node --test, are not detected. ### Check if the code is running in NodeJS Look for process.versions.node. https://1loc.dev/misc/check-if-the-code-is-running-in-node-js/ ```javascript function isNode() { return typeof process !== 'undefined' && process.versions?.node != null; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Node-compatible runtimes such as Bun also set process.versions.node, so this detects compatibility, not Node.js itself. The browser tests confirm it returns false in Chromium. ### Check if the code is running in the browser Look for the window and document globals. https://1loc.dev/misc/check-if-the-code-is-running-in-the-browser/ ```javascript function isBrowser() { return typeof window === 'object' && typeof document === 'object'; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Returns false in web and service workers, which have no document, and in Node.js, as the unit tests confirm. ### Clear all cookies Expire every cookie that JavaScript can see on the current path. https://1loc.dev/misc/clear-all-cookies/ ```javascript function clearCookies() { for (const cookie of document.cookie.split(';')) { const name = cookie.split('=')[0].trim(); if (name) document.cookie = `${name}=; Max-Age=0; path=/`; } } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). HttpOnly cookies, such as most session cookies, are invisible to JavaScript; only the server can clear them with Set-Cookie. ### Detect dark mode Read the prefers-color-scheme media feature. https://1loc.dev/misc/detect-dark-mode/ ```javascript function isDarkMode() { return window.matchMedia?.('(prefers-color-scheme: dark)').matches ?? false; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The preference can change while the page is open: listen for the change event on the MediaQueryList. ### Emulate a dice throw Return an integer from 1 to 6. https://1loc.dev/misc/emulate-a-dice-throw/ ```javascript function throwDice() { return Math.floor(Math.random() * 6) + 1; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original’s ~~ truncates like Math.floor only for non-negative numbers below 2³¹; Math.floor states the intent. ### Generate an unique and increment id Create a counter that returns 0, 1, 2… on successive calls. https://1loc.dev/misc/generate-an-unique-and-increment-id/ ```javascript function createIdGenerator(start = 0) { let id = start; return () => id++; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original assigned to an undeclared id: a ReferenceError in strict mode and ES modules, a leaked global otherwise. ### Redirect the page to HTTPS if it is in HTTP Replace an http: address with the same address over https:. https://1loc.dev/misc/redirect-the-page-to-https-if-it-is-in-http/ ```javascript function redirectToHttps() { if (location.protocol !== 'http:') return; const url = new URL(location.href); url.protocol = 'https:'; location.replace(url); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A client-side redirect runs after the insecure page has loaded. Redirect at the server or CDN with a 301, and send Strict-Transport-Security so browsers stop requesting HTTP. ### Run Promises in sequence Start each task after the previous one finishes and collect the results in order. https://1loc.dev/misc/run-promises-in-sequence/ ```javascript async function runInSequence(tasks) { const results = []; for (const task of tasks) results.push(await task()); return results; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Pass functions that start the work, not promises: a promise is already running once it exists. The original took promises, so it ordered the results but not the work, as the last lines show. ### Wait for an amount of time Return a promise that resolves after the given milliseconds. https://1loc.dev/misc/wait-for-an-amount-of-time/ ```javascript function wait(milliseconds) { return new Promise(resolve => setTimeout(resolve, milliseconds)); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). setTimeout is a minimum delay, not a schedule: a busy event loop or a background tab can delay it much longer. ### Wait for the next event loop Resolve after the current task, letting queued timers, I/O and rendering run. https://1loc.dev/misc/wait-for-the-next-event-loop/ ```javascript function nextTask() { return new Promise(resolve => setTimeout(resolve, 0)); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Promise callbacks (microtasks) still run before the timer, as the example shows. ## date & time ### Compare two dates Compare validated ISO calendar dates in UTC and return -1, 0 or 1. https://1loc.dev/date-time/compare-two-dates/ ```javascript function compareDates({ first, second }) { return Math.sign(new Date(first).getTime() - new Date(second).getTime()); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The lab requires real YYYY-MM-DD calendar dates and validates before execution. ### Add AM PM suffix to an hour Turn an hour from 0 to 23 into a 12-hour label with am or pm. https://1loc.dev/date-time/add-am-pm-suffix-to-an-hour/ ```javascript function suffixAmPm(hour) { return `${hour % 12 === 0 ? 12 : hour % 12}${hour < 12 ? 'am' : 'pm'}`; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Input is an integer hour from 0 to 23. ### Calculate the number of days between two dates Count whole calendar days between two YYYY-MM-DD dates. https://1loc.dev/date-time/calculate-the-number-of-difference-days-between-two-dates/ ```javascript function diffDays({ first, second }) { return Math.round(Math.abs(Date.parse(second) - Date.parse(first)) / 86400000); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Both dates are UTC calendar days, so daylight-saving changes cannot add or lose an hour. The original rounded local Date differences up with Math.ceil. ### Convert a date to YYYY-MM-DD format Format an ISO date-time as its UTC calendar date. https://1loc.dev/date-time/convert-a-date-to-yyyy-mm-dd-format/ ```javascript function formatYmd(dateTime) { return new Date(dateTime).toISOString().slice(0, 10); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). This is the UTC date. A local evening can already be tomorrow in UTC, as the edge case shows. ### Convert seconds to hh:mm:ss format Format a whole number of seconds as zero-padded hours, minutes and seconds. https://1loc.dev/date-time/convert-seconds-to-hh-mm-ss-format/ ```javascript function formatSeconds(seconds) { return [Math.floor(seconds / 3600), Math.floor(seconds % 3600 / 60), seconds % 60].map(part => String(part).padStart(2, '0')).join(':'); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Hours keep counting past 24. The original toISOString version wrapped around after one day. ### Calculate the number of months between two dates Count calendar month boundaries from start to end. https://1loc.dev/date-time/calculate-the-number-of-months-between-two-dates/ ```javascript function monthDiff({ start, end }) { const a = new Date(start), b = new Date(end); return Math.max(0, (b.getUTCFullYear() - a.getUTCFullYear()) * 12 - a.getUTCMonth() + b.getUTCMonth()); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Days are ignored: January 31 to February 1 counts as one month. An end before the start returns 0. ### Extract year, month, day, hour, minute, second and millisecond from a date Split the UTC ISO string into its numeric parts. https://1loc.dev/date-time/extract-year-month-day-hour-minute-second-and-millisecond-from-a-date/ ```javascript function extract(dateTime) { return new Date(dateTime).toISOString().split(/[^0-9]/).slice(0, -1); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Parts are zero-padded strings in UTC, as in the original; an offset shifts them, as the edge case shows. ### Get the current timestamp in seconds Convert a date-time to whole Unix seconds. https://1loc.dev/date-time/get-the-current-timestamp-in-seconds/ ```javascript function unixSeconds(now) { return Math.floor(Date.parse(now) / 1000); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). now is an input so the result is testable; pass new Date().toISOString(), or use Math.floor(Date.now() / 1000). ### Get the first date in the month of a date Set the UTC day of the month to 1. https://1loc.dev/date-time/get-the-first-date-in-the-month-of-a-date/ ```javascript function firstDateOfMonth(date) { const d = new Date(date); d.setUTCDate(1); return d.toISOString().slice(0, 10); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Works on UTC calendar dates; the original built a local Date at midnight. ### Get the total number of days in a year Return 366 for Gregorian leap years and 365 otherwise. https://1loc.dev/date-time/get-the-total-number-of-days-in-a-year/ ```javascript function daysInYear(year) { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 366 : 365; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Proleptic Gregorian rules: 1900 is not a leap year, 2000 is. ### Set the time of a date to midnight Return the start of the UTC day of a date-time. https://1loc.dev/date-time/initialize-the-current-date-but-set-time-to-midnight/ ```javascript function midnightUtc(now) { const d = new Date(now); d.setUTCHours(0, 0, 0, 0); return d.toISOString(); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original used local midnight via setHours; this version is UTC so it is the same on every server. Use setHours for the reader’s local day. ### Format a date for the given locale Use Intl.DateTimeFormat with an explicit locale and time zone. https://1loc.dev/date-time/format-a-date-for-the-given-locale/ ```javascript function formatDate({ date, locale }) { return new Intl.DateTimeFormat(locale, { timeZone: 'UTC' }).format(new Date(date)); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). timeZone: "UTC" keeps a YYYY-MM-DD date on the same day; without it a local time zone west of UTC shows the previous day. ### Get the current quarter of a date Map the month to a quarter from 1 to 4. https://1loc.dev/date-time/get-the-current-quarter-of-a-date/ ```javascript function quarter(date) { return Math.ceil((new Date(date).getUTCMonth() + 1) / 3); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Calendar quarters; fiscal years that start in another month need an offset. ### Get the day of the year from a date Count days from January 1, which is day 1. https://1loc.dev/date-time/get-the-day-of-the-year-from-a-date/ ```javascript function dayOfYear(date) { return Math.round((Date.parse(date) - Date.parse(`${date.slice(0, 4)}-01-01`)) / 86400000) + 1; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). UTC dates, so daylight-saving changes cannot shift the count; the original subtracted local Date objects. ### Get the last date in the month of a date Step to day 0 of the next month in UTC. https://1loc.dev/date-time/get-the-last-date-in-the-month-of-a-date/ ```javascript function lastDateOfMonth(date) { const d = new Date(date); d.setUTCMonth(d.getUTCMonth() + 1, 0); return d.toISOString().slice(0, 10); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Day 0 of a month is the last day of the previous one — the same trick as the original, in UTC. ### Get the month name of a date Look up the English month name of a date. https://1loc.dev/date-time/get-the-month-name-of-a-date/ ```javascript function monthName(date) { return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][new Date(date).getUTCMonth()]; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). English only. For other languages use new Intl.DateTimeFormat(locale, { month: "long", timeZone: "UTC" }). ### Get the tomorrow date Add one calendar day in UTC. https://1loc.dev/date-time/get-the-tomorrow-date/ ```javascript function tomorrow(date) { const d = new Date(date); d.setUTCDate(d.getUTCDate() + 1); return d.toISOString().slice(0, 10); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original’s second variant added 24 hours, which is not one day across a daylight-saving change. ### Get the weekday of a date Look up the English weekday name of a date. https://1loc.dev/date-time/get-the-weekday-of-a-date/ ```javascript function weekday(date) { return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][new Date(date).getUTCDay()]; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). English only; Intl.DateTimeFormat with { weekday: "long" } localizes it. ### Sort an array of dates Sort dates ascending or descending without changing the input. https://1loc.dev/date-time/sort-an-array-of-dates/ ```javascript function sortDates({ dates, order = 'asc' }) { const sorted = [...dates].sort((a, b) => Date.parse(a) - Date.parse(b)); return order === 'desc' ? sorted.reverse() : sorted; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original descending comparator returned a boolean, which sort treats inconsistently; a numeric difference is required. It also sorted in place. ### Determine one year from a date Add one to the UTC year. https://1loc.dev/date-time/determine-one-year-from-now/ ```javascript function plusOneYear(date) { const d = new Date(date); d.setUTCFullYear(d.getUTCFullYear() + 1); return d.toISOString().slice(0, 10); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). February 29 rolls over to March 1 in a non-leap year, as the edge case shows; clamp to February 28 if your contract requires it. ### Get the number of days in a given month Read day 0 of the next month for a 1-based month. https://1loc.dev/date-time/get-the-number-of-days-in-given-month/ ```javascript function daysInMonth({ year, month }) { const d = new Date(0); d.setUTCFullYear(year, month, 0); return d.getUTCDate(); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original comment called the month zero-based, but new Date(year, month, 0) gives the length of a 1-based month; this page says so explicitly. ### Get the yesterday date Subtract one calendar day in UTC. https://1loc.dev/date-time/get-the-yesterday-date/ ```javascript function yesterday(date) { const d = new Date(date); d.setUTCDate(d.getUTCDate() - 1); return d.toISOString().slice(0, 10); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Calendar days, not 24-hour steps. ### Get hours and minutes from decimal time Split decimal hours into whole hours and whole minutes. https://1loc.dev/date-time/get-hours-and-minutes-from-decimal-time/ ```javascript function hoursAndMinutes(value) { return [Math.floor(value), Math.floor((value * 60) % 60)]; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Minutes are floored, not rounded, as the edge case shows. The lab accepts 0 or more hours. ### Get the timezone string Read the runtime’s IANA time zone, such as America/Sao_Paulo. https://1loc.dev/date-time/get-the-timezone-string/ ```javascript function getTimezone() { return Intl.DateTimeFormat().resolvedOptions().timeZone; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Returns the zone of the runtime: the visitor’s in a browser, the server’s (often UTC) in Node.js. Store instants in UTC and convert for display. ## math ### Convert degrees to radians Multiply by π and divide by 180. https://1loc.dev/math/convert-degrees-to-radians/ ```javascript function degreesToRadians(degrees) { return degrees * Math.PI / 180; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Results are binary floating-point approximations of π multiples. ### Check if a rectangle contains another one Compare corners: a contains b when b’s corners sit inside or on a’s edges. https://1loc.dev/math/check-if-a-rectangle-contains-other-one/ ```javascript function contains({ a, b }) { return a.x1 <= b.x1 && a.y1 <= b.y1 && a.x2 >= b.x2 && a.y2 >= b.y2; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). (x1, y1) is the top-left and (x2, y2) the bottom-right corner; the lab requires x1 ≤ x2 and y1 ≤ y2. ### Check if a rectangle overlaps another one Two rectangles overlap when they overlap on both axes. https://1loc.dev/math/check-if-a-rectangle-overlaps-other-one/ ```javascript function overlaps({ a, b }) { return a.x1 < b.x2 && b.x1 < a.x2 && a.y1 < b.y2 && b.y1 < a.y2; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original combined the axes with ||, so rectangles side by side at different heights counted as overlapping. Both axes must overlap. ### Calculate the angle of a line defined by two points Use Math.atan2 for the angle from the x axis, in radians or degrees. https://1loc.dev/math/calculate-the-angle-of-a-line-defined-by-two-points/ ```javascript function angle({ p1, p2, unit = 'radians' }) { const radians = Math.atan2(p2.y - p1.y, p2.x - p1.x); return unit === 'degrees' ? radians * 180 / Math.PI : radians; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). atan2 handles every quadrant, unlike atan(dy / dx). The result is in (−π, π]. ### Calculate the distance between two points Apply the Pythagorean theorem with Math.hypot. https://1loc.dev/math/calculate-the-distance-between-two-points/ ```javascript function distance({ p1, p2 }) { return Math.hypot(p2.x - p1.x, p2.y - p1.y); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Math.hypot avoids overflow in intermediate squares that Math.sqrt(dx² + dy²) can hit. ### Calculate the linear interpolation between two numbers Blend from a to b by an amount between 0 and 1. https://1loc.dev/math/calculate-the-linear-interpolation-between-two-numbers/ ```javascript function lerp({ a, b, amount }) { return (1 - amount) * a + amount * b; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Amounts outside 0–1 extrapolate, as the edge case shows; clamp first when you need to stay in range. ### Normalize the ratio of a number in a range Map a value in [min, max] to [0, 1]. https://1loc.dev/math/normalize-the-ratio-of-a-number-in-a-range/ ```javascript function normalizeRatio({ value, min, max }) { return (value - min) / (max - min); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Values outside the range give ratios outside 0–1. The lab requires min < max. ### Calculate the midpoint between two points Average the x and y coordinates. https://1loc.dev/math/calculate-the-midpoint-between-two-points/ ```javascript function midpoint({ p1, p2 }) { return [(p1.x + p2.x) / 2, (p1.y + p2.y) / 2]; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Returns [x, y] as in the original. ### Check if a point is inside a rectangle Compare the point with the rectangle’s edges. https://1loc.dev/math/check-if-a-point-is-inside-a-rectangle/ ```javascript function isInside({ point, rect }) { return point.x > rect.left && point.x < rect.right && point.y > rect.top && point.y < rect.bottom; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Points on an edge are outside, as the edge case shows. ### Round a number to the nearest multiple of a given value Divide, round and multiply back. https://1loc.dev/math/round-a-number-to-the-nearest-multiple-of-a-given-value/ ```javascript function roundNearest({ value, nearest }) { return Math.round(value / nearest) * nearest; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Math.round rounds .5 up, toward +∞. Fractional steps can produce floating-point noise. ### Convert radians to degrees Multiply by 180 and divide by π. https://1loc.dev/math/convert-radians-to-degrees/ ```javascript function radiansToDegrees(radians) { return radians * 180 / Math.PI; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Results are floating-point approximations. ### Calculate the midpoint of a given range Average the two ends of a [from, to] range. https://1loc.dev/math/calculate-the-midpoint-of-a-given-range/ ```javascript function rangeMidpoint([from, to]) { return (from + to) / 2; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The order of the ends does not matter. ### Linear scale a number between ranges Map a value from one range onto another. https://1loc.dev/math/linear-scale-number-in-ranges/ ```javascript function linearScale({ value, inMin, inMax, outMin, outMax }) { return ((value - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Output ranges may be reversed, as the edge case shows. The lab requires inMin ≠ inMax. ### Linear scale of a number between two ranges The arrow-function form of the same mapping. https://1loc.dev/math/linear-scale-of-a-number-between-two-ranges/ ```javascript function scale({ value, from, to }) { return ((value - from[0]) * (to[1] - to[0])) / (from[1] - from[0]) + to[0]; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Values outside the input range extrapolate, as the edge case shows. ## email ### Convert an email domain to punycode Keep the local part and convert an international domain to its ASCII xn-- form. https://1loc.dev/email/convert-an-email-domain-to-punycode/ ```javascript function toAsciiAddress(address) { const at = address.lastIndexOf('@'); return `${address.slice(0, at)}@${new URL(`http://${address.slice(at + 1)}`).hostname}`; } ``` Written by Oveyon (MIT). Oveyon accepts ASCII addresses only: an international domain must be sent in its xn-- form, anything else is refused with address_not_ascii. ### Get the domain of an email address Take the part after the last @ and lowercase it, for domain checks and grouping. https://1loc.dev/email/get-the-domain-of-an-email-address/ ```javascript function emailDomain(address) { return address.slice(address.lastIndexOf('@') + 1).toLowerCase(); } ``` Written by Oveyon (MIT). The last @ separates the domain, so a quoted local part containing @ still works. This does not validate the address. ### Mask an email address for logs Keep the first character and the domain; hide the rest of the local part. https://1loc.dev/email/mask-an-email-address/ ```javascript function maskEmail(address) { return `${address.slice(0, 1)}•••${address.slice(address.lastIndexOf('@'))}`; } ``` Written by Oveyon (MIT). Masking reduces exposure in logs; it is not anonymization, and the domain stays visible. ### Normalize an email address for comparison Trim whitespace and lowercase only the domain, preserving the local part. https://1loc.dev/email/normalize-an-email-address/ ```javascript function normalizeEmail(address) { const value = address.trim(); const at = value.lastIndexOf('@'); return `${value.slice(0, at)}@${value.slice(at + 1).toLowerCase()}`; } ``` Written by Oveyon (MIT). The local part is kept as typed: its case rules belong to the receiving server. ### Read a Retry-After header Turn delay-seconds or an HTTP date into milliseconds to wait, never negative. https://1loc.dev/email/parse-a-retry-after-header/ ```javascript function retryAfterMs({ retryAfter, date }) { const seconds = Number(retryAfter); return Math.max(0, Number.isFinite(seconds) ? seconds * 1000 : Date.parse(retryAfter) - Date.parse(date)); } ``` Written by Oveyon (MIT). An HTTP date is compared with the response’s own Date header, not your clock, so clock skew cannot shorten the wait. The lab accepts delay-seconds from 0 to 86,400. ### Compute a backoff delay with full jitter Double the window on every attempt, cap it, then pick a point inside it. https://1loc.dev/email/compute-an-exponential-backoff-delay/ ```javascript function backoffMs({ attempt, baseMs, capMs, random }) { return Math.round(random * Math.min(capMs, baseMs * 2 ** attempt)); } ``` Written by Oveyon (MIT). random is an input so the result is testable; pass Math.random() in production. Honor a Retry-After header when the server sends one. ### Build an idempotency key from an event Join a scope, a business id and a version into one stable, colon-separated key. https://1loc.dev/email/build-an-idempotency-key/ ```javascript function idempotencyKey({ scope, id, version }) { return [scope, id, version].map(part => encodeURIComponent(String(part))).join(':'); } ``` Written by Oveyon (MIT). Derive the key from the business event, never from time or randomness: a retry must send the same key. ### Classify an SMTP reply Read the reply code and enhanced status code, and tell a temporary failure from a permanent one. https://1loc.dev/email/classify-an-smtp-reply/ ```javascript function classifySmtpReply(reply) { const [, code, enhanced] = /^([2-5]\d{2})(?:[ -]([245]\.\d{1,3}\.\d{1,3}))?/.exec(reply); return { code: Number(code), enhanced: enhanced || null, outcome: { 2: 'success', 3: 'intermediate', 4: 'transient', 5: 'permanent' }[code[0]], retry: code[0] === '4' }; } ``` Written by Oveyon (MIT). Reply classes follow RFC 5321: 2xx success, 3xx intermediate, 4xx transient, 5xx permanent. Enhanced codes (RFC 3463, class.subject.detail) refine the reason; servers may omit them. ### Build a DMARC record Compose the TXT value for _dmarc. from a policy and an optional report address. https://1loc.dev/email/build-a-dmarc-record/ ```javascript function dmarcRecord({ policy, rua }) { return ['v=DMARC1', `p=${policy}`, ...(rua ? [`rua=${rua}`] : [])].join('; '); } ``` Written by Oveyon (MIT). Publish the value as a TXT record at _dmarc.; v=DMARC1 must come first (RFC 7489). Start with p=none and aggregate reports, then move to quarantine and reject once SPF or DKIM alignment holds. ### Parse a DMARC record Split a published DMARC TXT value into its tags. https://1loc.dev/email/parse-a-dmarc-record/ ```javascript function parseDmarc(record) { return Object.fromEntries(record.split(';').map(tag => tag.trim()).filter(Boolean).map(tag => [tag.slice(0, tag.indexOf('=')).trim().toLowerCase(), tag.slice(tag.indexOf('=') + 1).trim()])); } ``` Written by Oveyon (MIT). Tag names are lowercased; values are kept as published. Unknown tags are returned, not validated. ## DOM ### Check if a given DOMRect is contained within another DOMRect True when the target lies inside the container or on its edges. https://1loc.dev/dom/check-if-a-given-dom-rect-is-contained-within-another-dom-rect/ ```javascript function isContained({ target, container }) { return target.x >= container.x && target.x + target.width <= container.x + container.width && target.y >= container.y && target.y + target.height <= container.y + container.height; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Pass rects from getBoundingClientRect() or plain { x, y, width, height } objects. The original read left and top, which plain objects lack. ### Check if two DOMRects intersect Two rects intersect when they meet on both axes. https://1loc.dev/dom/check-if-two-dom-rects-intersect/ ```javascript function intersect({ a, b }) { return b.x <= a.x + a.width && b.x + b.width >= a.x && b.y <= a.y + a.height && b.y + b.height >= a.y; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Touching edges count as intersecting, as the edge case shows. For a strict overlap use < and >, as in Check if a rectangle overlaps another one. ### Compare two DOMRects for size and position match Compare x, y, width and height exactly. https://1loc.dev/dom/compare-two-dom-rects-for-size-and-position-match/ ```javascript function sameRect({ a, b }) { return ['x', 'y', 'width', 'height'].every(key => a[key] === b[key]); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Exact comparison. Layout coordinates are often fractional, as the edge case shows; compare rendered positions with a tolerance such as Math.abs(a - b) < 0.5. ### Get the center point of a DOMRect Return [x, y] of the rect’s center. https://1loc.dev/dom/get-the-center-point-of-a-dom-rect/ ```javascript function getCenter({ x, y, width, height }) { return [x + width / 2, y + height / 2]; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Coordinates are in the rect’s own space: viewport pixels for getBoundingClientRect(). Add window.scrollX and scrollY for document coordinates. ### Calculate the distance to the bottom of a page Pixels left to scroll before the end of the page. https://1loc.dev/dom/calculate-the-distance-to-the-bottom-of-a-page/ ```javascript function distanceToBottom() { return document.documentElement.scrollHeight - window.innerHeight - window.scrollY; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). document.documentElement.scrollHeight measures the whole page. The original used document.body.scrollHeight, which can differ when body has margins or a fixed height. ### Check if an element has CSS overflow True when either axis is styled to scroll: overflow auto or scroll. https://1loc.dev/dom/check-if-an-element-has-css-overflow/ ```javascript function hasCssOverflow(element) { const { overflowX, overflowY } = getComputedStyle(element); return [overflowX, overflowY].some(value => ['auto', 'scroll'].includes(value)); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original read the overflow shorthand, which is "hidden auto" when the axes differ, as the last line shows; reading overflowX and overflowY handles both. ### Check if an element has overflow True when the content is larger than the element’s visible box. https://1loc.dev/dom/check-if-an-element-has-overflow/ ```javascript function hasOverflow(element) { return element.scrollHeight > element.clientHeight || element.scrollWidth > element.clientWidth; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Compares content size with the visible box, whatever the overflow style: use it to decide whether to show a “Show more” control. ### Check if an element is a descendant of another True when child is inside parent, at any depth. https://1loc.dev/dom/check-if-an-element-is-a-descendant-of-another/ ```javascript function isDescendant(child, parent) { return child !== parent && parent.contains(child); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Node.contains returns true for the node itself, as the last line shows, so the original called an element its own descendant. ### Check if an element is focused Compare the element with document.activeElement. https://1loc.dev/dom/check-if-an-element-is-focused/ ```javascript function hasFocus(element) { return element === document.activeElement; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Inside shadow DOM, document.activeElement is the shadow host; element.matches(":focus") checks the element itself. ### Check if the touch events are supported True when the browser exposes touch events or reports touch points. https://1loc.dev/dom/check-if-the-touch-events-are-supported/ ```javascript function touchSupported() { return 'ontouchstart' in window || navigator.maxTouchPoints > 0; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Touch support is not touch use: many laptops have both. For layout, the pointer and hover media features describe the primary input, as the last line shows. ### Check if user scrolls to the bottom of the page True when the viewport has reached the end of the page. https://1loc.dev/dom/check-if-user-scrolls-to-the-bottom-of-the-page/ ```javascript function isAtBottom(tolerance = 1) { const { scrollHeight, clientHeight } = document.documentElement; return scrollHeight - clientHeight - window.scrollY <= tolerance; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A 1 px tolerance absorbs fractional scroll positions on zoomed and high-density screens, where the original’s exact comparison could stay false at the bottom. ### Detect Internet Explorer browser Look for document.documentMode, which only Internet Explorer defines. https://1loc.dev/dom/detect-internet-explorer-browser/ ```javascript function isInternetExplorer() { return 'documentMode' in document; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Microsoft retired the Internet Explorer 11 desktop application in June 2022. Keep this only to show an upgrade notice in legacy intranets. ### Detect macOS browser Guess whether the device is a Mac, iPhone or iPad from the platform string. https://1loc.dev/dom/detect-macos-browser/ ```javascript function isApplePlatform() { return /Mac|iPhone|iPad|iPod/.test(navigator.userAgentData?.platform ?? navigator.platform); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). navigator.platform is deprecated, and iPadOS reports "MacIntel" in desktop mode, so this cannot tell a Mac from an iPad. Chromium’s navigator.userAgentData is read where available. ### Get all siblings of an element Return the other element children of the element’s parent. https://1loc.dev/dom/get-all-siblings-of-an-element/ ```javascript function siblings(element) { return element.parentElement ? [...element.parentElement.children].filter(child => child !== element) : []; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Element siblings only: text and comment nodes are skipped. The original threw a TypeError for an element without a parent; this version returns []. ### Get the position of an element relative to the document Add the scroll offsets to the element’s viewport position. https://1loc.dev/dom/get-the-position-of-an-element-relative-to-the-document/ ```javascript function getPosition(element) { const rect = element.getBoundingClientRect(); return { left: rect.left + window.scrollX, top: rect.top + window.scrollY }; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original assigned to an undeclared r: a ReferenceError in strict mode and ES modules. ### Get the selected text Read the text of the current document selection. https://1loc.dev/dom/get-the-selected-text/ ```javascript function getSelectedText() { return window.getSelection()?.toString() ?? ''; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Text selected inside an input or textarea is not part of the document selection: read value.slice(selectionStart, selectionEnd) on the field. ### Go back to the previous page Move one step back in the session history. https://1loc.dev/dom/go-back-to-the-previous-page/ ```javascript function goBack() { history.back(); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). history.back() is asynchronous: wait for popstate (same-document entries) or for the page to unload. It does nothing without a previous entry. ### Hide an element Set the hidden attribute. https://1loc.dev/dom/hide-an-element/ ```javascript function hide(element) { element.hidden = true; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). hidden removes the element from layout and from the accessibility tree. A stylesheet rule such as display: flex overrides it; add [hidden] { display: none !important } to be safe. ### Insert an element after other one Place an element right after a reference element. https://1loc.dev/dom/insert-an-element-after-other-one/ ```javascript function insertAfter(element, reference) { reference.after(element); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Element.after, before and replaceWith are the modern ChildNode methods; the original used parentNode.insertBefore with nextSibling. ### Insert an element before other one Place an element right before a reference element. https://1loc.dev/dom/insert-an-element-before-other-one/ ```javascript function insertBefore(element, reference) { reference.before(element); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). before also accepts several nodes, and strings, which it inserts as text. ### Insert given HTML after an element Parse an HTML string and insert it after the element. https://1loc.dev/dom/insert-given-html-after-an-element/ ```javascript function insertHtmlAfter(html, element) { element.insertAdjacentHTML('afterend', html); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The string is parsed as HTML: never pass user input, or an attacker can inject markup and event handlers (XSS). For untrusted text, use insertAdjacentText or create elements. ### Insert given HTML before an element Parse an HTML string and insert it before the element. https://1loc.dev/dom/insert-given-html-before-an-element/ ```javascript function insertHtmlBefore(html, element) { element.insertAdjacentHTML('beforebegin', html); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The string is parsed as HTML: never pass user input (XSS). Inserted script elements do not run, but inline event handlers such as onerror do. ### Redirect to another page Navigate to a URL, adding an entry to the history. https://1loc.dev/dom/redirect-to-another-page/ ```javascript function goTo(url) { location.assign(url); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A URL taken from user input is an open redirect, and a javascript: URL runs code. Accept only relative paths or an allow-list of origins. ### Reload the current page Load the current document again. https://1loc.dev/dom/reload-the-current-page/ ```javascript function reload() { location.reload(); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Reloading discards in-memory state. Prefer updating the part of the page that changed. ### Replace an element Swap an element for another in the same position. https://1loc.dev/dom/replace-an-element/ ```javascript function replace(element, replacement) { element.replaceWith(replacement); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Element.replaceWith is the modern form of parentNode.replaceChild(newNode, oldNode), whose argument order is easy to swap by mistake. ### Scroll to top of the page Scroll the window back to the top. https://1loc.dev/dom/scroll-to-top-of-the-page/ ```javascript function goToTop() { window.scrollTo(0, 0); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). If the page sets scroll-behavior: smooth, the scroll animates. Keep smooth scrolling inside a prefers-reduced-motion: no-preference query. ### Serialize form data Turn a form’s fields into an object; repeated names become arrays. https://1loc.dev/dom/serialize-form-data/ ```javascript function serialize(form) { const groups = new Map(); for (const [key, value] of new FormData(form)) groups.set(key, [...(groups.get(key) ?? []), value]); return Object.fromEntries([...groups].map(([key, values]) => [key, values.length > 1 ? values : values[0]])); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original tested the first value for truthiness, so an empty first value was dropped: alias would have been "ana.s". ### Show an element Clear the hidden attribute and any inline display: none. https://1loc.dev/dom/show-an-element/ ```javascript function show(element) { element.hidden = false; element.style.removeProperty('display'); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). If a stylesheet hides the element, it stays hidden; toggle a class instead. ### Strip HTML from a given text Parse HTML in an inert document and return its text. https://1loc.dev/dom/strip-html-from-a-given-text/ ```javascript function stripHtml(html) { return new DOMParser().parseFromString(html, 'text/html').body.textContent ?? ''; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). DOMParser builds an inert document: scripts do not run and images do not load, so the second line is safe. The result is text; never insert the original HTML into the page. ### Toggle an element Flip the hidden attribute. https://1loc.dev/dom/toggle-an-element/ ```javascript function toggle(element) { element.hidden = !element.hidden; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original’s first version set display to block, which breaks flex and grid containers; toggling hidden restores the element’s own display. ## function ### Logical xor operator True when exactly one of two values is truthy. https://1loc.dev/function/logical-xor-operator/ ```javascript function xor([a, b]) { return Boolean(a) !== Boolean(b); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Operands are converted to booleans first. The original’s (a && !b) || (!a && b) returns an operand instead: for the edge case it returns "y", not true. ### Identity function Return the argument unchanged. https://1loc.dev/function/identity-function/ ```javascript function identity(value) { return value; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Useful as a default transform: a pipeline step that does nothing, or values.filter(identity) to keep truthy items. ### Box handler Chain transformations on a value, then unwrap the result. https://1loc.dev/function/box-handler/ ```javascript function boxHandler(value) { return { next: f => boxHandler(f(value)), done: f => f(value) }; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Each next returns a new box; nothing is mutated. An error thrown in a step propagates immediately. ### Check if a value is a function True for anything callable: functions, arrows, async and generator functions, classes. https://1loc.dev/function/check-if-a-value-is-a-function/ ```javascript function isFunction(value) { return typeof value === 'function'; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original also returned true for a Promise, which is not callable. typeof is the reliable test, as the last line shows. ### Check if a value is a generator function Read the internal tag of function* and async function* declarations. https://1loc.dev/function/check-if-a-value-is-a-generator-function/ ```javascript function isGeneratorFunction(value) { return ['[object GeneratorFunction]', '[object AsyncGeneratorFunction]'].includes(Object.prototype.toString.call(value)); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original missed async generator functions, as the second line shows. Symbol.toStringTag can spoof the tag. ### Check if a value is an async function Read the internal tag of async function declarations and arrows. https://1loc.dev/function/check-if-a-value-is-an-async-function/ ```javascript function isAsyncFunction(value) { return Object.prototype.toString.call(value) === '[object AsyncFunction]'; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A regular function that returns a promise is not detected, as the second line shows, and code transpiled to older JavaScript loses the tag. ### Compose functions from left to right Build one function that passes a value through each function in order. https://1loc.dev/function/compose-functions-from-left-to-right/ ```javascript function pipe(...fns) { return input => fns.reduce((value, fn) => fn(value), input); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Functions run in the order listed. With no functions, the input comes back unchanged. ### Compose functions Build one function that applies functions from right to left, as in f(g(x)). https://1loc.dev/function/compose-functions/ ```javascript function compose(...fns) { return input => fns.reduceRight((value, fn) => fn(value), input); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The last function runs first, as in mathematical notation. pipe lists the same steps in execution order. ### Create a function that accepts a single argument Wrap a function so it ignores every argument after the first. https://1loc.dev/function/create-a-function-that-accepts-a-single-argument/ ```javascript function unary(fn) { return value => fn(value); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). map passes (value, index, array), so parseInt received the index as its radix, as the first line shows. unary drops everything after the value. ### Create an empty function A function that does nothing and returns undefined. https://1loc.dev/function/create-an-empty-function/ ```javascript function noop() {} ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A shared noop makes a safe default callback, as in send above. ### Curry a function Collect arguments across calls until the function has as many as it declares. https://1loc.dev/function/curry-a-function/ ```javascript function curry(fn, ...args) { return fn.length <= args.length ? fn(...args) : (...more) => curry(fn, ...args, ...more); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The arity comes from fn.length, which stops at the first default or rest parameter: (a, b = 1) => … has length 1. ### Delay the evaluation of a function Turn a call into a thunk: a function that runs the call only when invoked. https://1loc.dev/function/delay-the-evaluation-of-a-function/ ```javascript function thunkify(fn) { return (...args) => () => fn(...args); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The thunk runs fn every time it is called; wrap it with Execute a function once to keep the first result. ### Execute a function once Run a function on the first call and return that result afterwards. https://1loc.dev/function/execute-a-function-once/ ```javascript function once(fn) { let done = false, result; return (...args) => { if (!done) { result = fn(...args); done = true; } return result; }; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Typical use: create one API client or connection pool lazily, on first use. ### Flip the arguments of a function Call a function with its arguments in reverse order. https://1loc.dev/function/flip-the-arguments-of-a-function/ ```javascript function flip(fn) { return (...args) => fn(...args.reverse()); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). All arguments are reversed. For two arguments, (b, a) => fn(a, b) is the explicit form. ### Memoize a function Cache results by argument so each input is computed once. https://1loc.dev/function/memoize-a-function/ ```javascript function memoize(fn) { const cache = new Map(); return arg => { if (!cache.has(arg)) cache.set(arg, fn(arg)); return cache.get(arg); }; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original cached with cache[arg] || …, so falsy results (0, "", false) were recomputed on every call: three calls above would have run three times. A Map also keeps 1 and "1" apart. ### Partially apply a function Fix the first arguments now and pass the rest later. https://1loc.dev/function/partially-apply-a-function/ ```javascript function partial(fn, ...preset) { return (...rest) => fn(...preset, ...rest); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). fn.bind(null, …preset) is the built-in equivalent for functions that do not use this. ### Uncurry a function Call a curried function with several arguments at once. https://1loc.dev/function/uncurry-a-function/ ```javascript function uncurry(fn, depth = 1) { return (...args) => args.slice(0, depth).reduce((next, arg) => next(arg), fn); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Arguments beyond depth are ignored, as in the original. depth must not exceed the curried function’s depth. ## random ### Generate a random boolean Return true or false with equal probability. https://1loc.dev/random/generate-a-random-boolean/ ```javascript function randomBoolean() { return Math.random() < 0.5; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Math.random returns [0, 1), so < 0.5 splits it into two equal halves. ### Generate a random floating point number in given range Scale Math.random into [min, max). https://1loc.dev/random/generate-a-random-floating-point-number-in-given-range/ ```javascript function randomFloat(min, max) { return Math.random() * (max - min) + min; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Results fall in [min, max). Floating-point rounding can occasionally produce max itself; clamp if that matters. ### Generate a random hex color Return a #rrggbb color from 24 random bits. https://1loc.dev/random/generate-a-random-hex-color/ ```javascript function randomColor() { return `#${Math.floor(Math.random() * 0x1000000).toString(16).padStart(6, '0')}`; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original’s second version omitted padStart, so colors below #100000 came out with fewer than six digits. ### Generate a random integer in given range Return an integer from min to max, both included. https://1loc.dev/random/generate-a-random-integer-in-given-range/ ```javascript function randomInteger(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). min and max must be integers. Both ends are included. ### Generate a random IP address Return a random IPv4 address from the ranges reserved for documentation. https://1loc.dev/random/generate-a-random-ip-address/ ```javascript function randomDocumentationIp() { const networks = ['192.0.2', '198.51.100', '203.0.113']; return `${networks[Math.floor(Math.random() * networks.length)]}.${Math.floor(Math.random() * 254) + 1}`; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). RFC 5737 reserves 192.0.2.0/24, 198.51.100.0/24 and 203.0.113.0/24 for documentation. They never belong to a real host, so fixtures and logs in examples cannot point at one. ### Generate a random sign Return 1 or -1 with equal probability. https://1loc.dev/random/generate-a-random-sign/ ```javascript function randomSign() { return Math.random() < 0.5 ? -1 : 1; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Multiply by a magnitude for symmetric noise: randomSign() * magnitude. ### Generate a random string from given characters Draw characters from an alphabet with a cryptographic generator, without bias. https://1loc.dev/random/generate-a-random-string-from-given-characters/ ```javascript function randomString(length, alphabet) { if (alphabet.length < 2 || alphabet.length > 256) throw new RangeError('alphabet must have 2 to 256 characters'); const limit = 256 - (256 % alphabet.length); let result = ''; while (result.length < length) { for (const byte of crypto.getRandomValues(new Uint8Array(length))) { if (byte < limit && result.length < length) result += alphabet[byte % alphabet.length]; } } return result; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Uses crypto.getRandomValues, a global in browsers and Node.js 19+. The original used Math.random, which is predictable and unsuitable for tokens. ### Generate a random string using Node crypto module Return random bytes from node:crypto as a hex string. https://1loc.dev/random/generate-a-random-string-using-node-crypto-module/ ```javascript import { randomBytes } from 'node:crypto'; function randomToken(bytes = 32) { return randomBytes(bytes).toString('hex'); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). 32 bytes are 256 bits of entropy: 64 hex characters. toString("base64url") gives a shorter token for URLs. ### Generate a random string with given length Return a lowercase Base32 identifier from a cryptographic generator. https://1loc.dev/random/generate-a-random-string-with-given-length/ ```javascript function randomId(length) { const alphabet = '0123456789abcdefghjkmnpqrstvwxyz'; return Array.from(crypto.getRandomValues(new Uint8Array(length)), byte => alphabet[byte % 32]).join(''); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). 32 symbols (Crockford’s Base32, lowercase) divide 256 evenly, so every symbol is equally likely without rejection sampling. It omits i, l, o and u, which are easy to misread. ### Generate a random UUID Return a version 4 UUID from the platform’s cryptographic generator. https://1loc.dev/random/generate-a-random-uuid/ ```javascript function uuid() { return crypto.randomUUID(); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). crypto.randomUUID() returns an RFC 9562 version 4 UUID. In browsers it requires a secure context: HTTPS or localhost. ### Generate a weighted random number in given range Return an integer in [min, max) skewed toward min. https://1loc.dev/random/generate-a-weighted-random-number-in-given-range/ ```javascript function weightedRandom(min, max) { return Math.floor(Math.random() ** 2 * (max - min)) + min; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Squaring a uniform number skews results toward min: about 71% of draws land in the lower half, which the example checks. max is excluded. ### Generate an array of random integers in a given range Return count integers from min to max, both included. https://1loc.dev/random/generate-an-array-of-random-integers-in-a-given-range/ ```javascript function randomIntegers(min, max, count) { return Array.from({ length: count }, () => Math.floor(Math.random() * (max - min + 1)) + min); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Values can repeat. For distinct values, shuffle a range and take the first count, as in Get random items of an array. ### Get a random item and remove it from an array Remove one random item from the array and return it. https://1loc.dev/random/get-a-random-item-and-remove-it-from-an-array/ ```javascript function takeRandomItem(values) { return values.splice(Math.floor(Math.random() * values.length), 1)[0]; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Mutates the array. The original returned the one-item array from splice, such as [7], not the item; [0] unwraps it. ### Get a random item from an array Return one item at a random index. https://1loc.dev/random/get-a-random-item-from-an-array/ ```javascript function randomItem(values) { return values[Math.floor(Math.random() * values.length)]; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). An empty array returns undefined. The original’s | 0 behaves like Math.floor only below 2³¹. ### Get random items of an array Return count distinct items in random order. https://1loc.dev/random/get-random-items-of-an-array/ ```javascript function randomItems(values, count) { const pool = [...values]; for (let i = pool.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [pool[i], pool[j]] = [pool[j], pool[i]]; } return pool.slice(0, count); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original spliced the array that reduce was walking, so reduce skipped the removed positions: asking for 8 of 10 items returned 5. ### Pick a random property of an object Return one of the object’s own enumerable keys. https://1loc.dev/random/pick-a-random-property-of-an-object/ ```javascript function randomKey(object) { const keys = Object.keys(object); return keys[Math.floor(Math.random() * keys.length)]; } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Own enumerable string keys only; an empty object returns undefined. The original called Object.keys twice. ### Pick random lines from a text document Split text into lines and return count of them in random order. https://1loc.dev/random/pick-random-lines-from-a-text-document/ ```javascript function randomLines(text, count) { const lines = text.split(/\r?\n/); for (let i = lines.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [lines[i], lines[j]] = [lines[j], lines[i]]; } return lines.slice(0, count); } ``` Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original had the same reduce-and-splice flaw as Get random items of an array: requesting more than half the lines returned fewer.