Reference

Programming languages

Choose TypeScript, Go, Rust or C++ and find syntax, everyday APIs, standard libraries and tools in one place.

Scope and conventions

TypeScript/Node, Go 1.23+, Rust 2024 and C++23: from a first CLI to files, JSON, HTTP, concurrency and testing. Complete programs are labeled; other examples identify their surrounding code/imports. Optional libraries and version requirements are named in each entry.

Time & randomness

Record wall-clock time for an event

TypeScript

Date represents an instant with millisecond precision; toISOString formats it in UTC.

Fragment

Wall time can jump when the system clock is adjusted; use a monotonic clock for elapsed duration.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const recordedAt = new Date().toISOString();
const epochMillis = Date.now();

Measure elapsed time with a monotonic clock

TypeScript

performance.now measures an elapsed interval independently of ordinary wall-clock adjustments.

Fragment

Modern Node/browser API. This fragment measures synchronous work; await an asynchronous operation before taking the second reading.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const start = performance.now();
work();
const elapsedMs = performance.now() - start;

Choose a random value for ordinary simulation

TypeScript

Math.random supports ordinary simulation/selection; it is not a cryptographic random source.

Fragment

For security-sensitive randomness choose a documented crypto API instead.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const die = Math.floor(Math.random() * 6) + 1;

Represent durations and add them to times: Temporal.Duration, time.Duration, std::time::Duration, std::chrono

TypeScript

Temporal.Duration is the standard duration type: named fields (hours, minutes, seconds and the calendar units days, weeks, months, years), ISO 8601 text such as PT8H30M, total(unit) to convert, round() to balance or round for display, and Duration.compare. Temporal.Instant.add and until do exact-time arithmetic with it; an Instant refuses days and larger units, which depend on a time zone or calendar.

Complete program

Complete program for Node 26+ or a current browser. On Node 22/24 use the milliseconds approach in the notes, or load temporal-polyfill.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import assert from 'node:assert/strict';

// Temporal.Duration is a typed span with named fields and ISO 8601 text (PT8H30M).
const ttl = Temporal.Duration.from({ hours: 8, minutes: 30 });
assert.equal(ttl.toString(), 'PT8H30M');
assert.equal(ttl.total('minutes'), 510);

// Parse config values written in ISO 8601.
const configured = Temporal.Duration.from('PT1H15M30.5S');
assert.equal(configured.total('seconds'), 4530.5);

// Balance and round for display: 90 minutes is 1 h 30 min; 1h15m30.5s rounds to 1h16m.
const meeting = Temporal.Duration.from({ minutes: 90 }).round({ largestUnit: 'hours' });
assert.equal(`${meeting.hours}h${meeting.minutes}m`, '1h30m');
assert.equal(configured.round({ smallestUnit: 'minutes' }).toString(), 'PT1H16M');
assert.equal(Temporal.Duration.compare(ttl, { hours: 8 }), 1);

// Instant + Duration is exact-time arithmetic.
const issued = Temporal.Instant.from('2026-11-08T09:00:00Z');
const expires = issued.add(ttl);
assert.equal(expires.toString(), '2026-11-08T17:30:00Z');
assert.equal(issued.until(expires).total('hours'), 8.5);

// Days and months are calendar units: an Instant refuses them; use a ZonedDateTime.
assert.throws(() => issued.add({ days: 1 }), RangeError);

// setTimeout, Date and performance.now still use plain milliseconds: convert at the edge.
const requestTimeoutMs = Temporal.Duration.from({ seconds: 30 }).total('milliseconds');
assert.equal(requestTimeoutMs, 30_000);
console.log(ttl.toString(), expires.toString(), ttl.toLocaleString('en'));

In practice: parse configured durations with Duration.from, add them to an Instant for expiry times, and convert to milliseconds only at the edge, because setTimeout, Date and performance.now still take plain numbers. Use a ZonedDateTime when "one day" or "one month" has to follow a calendar.

Temporal ships enabled in Node 26 and in current Chrome and Firefox; check MDN's compatibility table for other runtimes. Node 22 and 24 run this program with temporal-polyfill 1.0.8 (node --import temporal-polyfill/global). TypeScript 6.0+ has the types in lib "esnext.temporal".

Without Temporal, durations are plain milliseconds: name the unit (const SESSION_TTL_MS = 8 * 3_600_000 + 30 * 60_000) and add to an instant with new Date(issued.getTime() + SESSION_TTL_MS).

setTimeout clamps delays above 2^31 - 1 ms (about 24.8 days) to 1 ms and Node prints a TimeoutOverflowWarning; schedule long waits in steps.

toLocaleString formats with Intl.DurationFormat ("8 hr, 30 min" in English) and falls back to the ISO string (PT8H30M) where Intl.DurationFormat is missing, as on Node 22; the exact text depends on the ICU version, so do not compare it in tests.

Format and parse timestamps: Temporal.Instant, time.Parse layouts, jiff, std::chrono::parse

TypeScript

Temporal.Instant is the standard type for an exact time. Instant.from parses ISO 8601 / RFC 9557 strings and requires a Z or an offset (it accepts more than RFC 3339, such as a missing seconds field or the basic format, so check the shape with a regular expression first when you need strict RFC 3339). It applies the offset and throws a RangeError for an impossible date or a non-ISO string. toString() formats as UTC with only the fraction digits needed (fractionalSecondDigits fixes them, timeZone shows another offset), JSON.stringify uses it, and epochMilliseconds is Unix time in milliseconds.

Complete program

Complete program for Node 26+ or a current browser. On Node 22/24 use the Date approach in the notes, or load temporal-polyfill.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import assert from 'node:assert/strict';

// Temporal.Instant is an exact time. from() parses ISO 8601 / RFC 9557 and needs an offset.
const instant = Temporal.Instant.from('2026-11-08T14:05:09Z');
assert.equal(instant.toString(), '2026-11-08T14:05:09Z');
assert.ok(Temporal.Instant.from('2026-11-08T15:05:09+01:00').equals(instant)); // offset applied
assert.equal(instant.epochMilliseconds, Date.UTC(2026, 10, 8, 14, 5, 9)); // Unix time in ms

// Missing offsets, impossible dates and non-ISO text throw instead of guessing.
for (const bad of ['2026-11-08T10:00:00', '2026-02-30T10:00:00Z', '11/08/2026']) {
  assert.throws(() => Temporal.Instant.from(bad), RangeError);
}

// Formatting options for machines; toLocaleString (Intl) for people.
assert.equal(instant.toString({ fractionalSecondDigits: 3 }), '2026-11-08T14:05:09.000Z');
assert.equal(instant.toString({ timeZone: 'Europe/Berlin' }), '2026-11-08T15:05:09+01:00');
assert.equal(JSON.stringify({ at: instant }), '{"at":"2026-11-08T14:05:09Z"}');
console.log(instant.toLocaleString('en-GB', { timeZone: 'UTC', dateStyle: 'medium', timeStyle: 'short' }));

// Interop with Date-based code goes through epoch milliseconds.
const legacy = new Date(instant.epochMilliseconds);
assert.equal(legacy.toISOString(), '2026-11-08T14:05:09.000Z'); // always UTC with milliseconds
assert.ok(Temporal.Instant.fromEpochMilliseconds(legacy.getTime()).equals(instant));
console.log(Temporal.Now.instant().round({ smallestUnit: 'second' }).toString());

In practice: send and store full RFC 3339 timestamps with an offset, parse them with Instant.from, and use toLocaleString (Intl) only for text meant for people. Convert to and from Date through epoch milliseconds where older APIs need one.

Temporal ships enabled in Node 26 and in current Chrome and Firefox. Node 22 and 24 run this program with temporal-polyfill 1.0.8 (node --import temporal-polyfill/global); TypeScript 6.0+ types it with lib "esnext.temporal".

Without Temporal: Date.parse reads a date-time without an offset as local time, returns NaN for invalid input, and in V8 rolls 2026-02-30 over to 2 March. Check the shape with a regex such as /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/ and check that new Date(Date.UTC(year, month - 1, day)).getUTCDate() gives the same day back before trusting it.

Date.prototype.toISOString always prints milliseconds (.000Z) and throws a RangeError on an Invalid Date.

Convert between UTC, local time and time zones: Temporal.ZonedDateTime, time.LoadLocation, jiff, zoned_time

TypeScript

Temporal.ZonedDateTime is the standard type for a time in an IANA zone: an exact instant plus the zone, with its daylight-saving rules. instant.toZonedDateTimeISO("America/New_York") views an instant there, ZonedDateTime.from("2026-03-09T09:00[America/New_York]") builds a wall time in the zone, and .offset shows the offset that applies. add({ days: 1 }) is calendar arithmetic that keeps the wall-clock time across a DST change, while add({ hours: 24 }) is exact time. A wall time in a DST gap is moved forward by default; disambiguation: "reject" throws instead. Unknown zones throw a RangeError.

Complete program

Complete program for Node 26+ or a current browser; its assertions hold in any local zone. On Node 22/24 use the Intl approach in the notes, or load temporal-polyfill.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import assert from 'node:assert/strict';

// An Instant viewed in an IANA zone is a ZonedDateTime, with that zone's DST rules.
const winter = Temporal.Instant.from('2026-01-15T17:00:00Z');
const summer = Temporal.Instant.from('2026-07-15T17:00:00Z');
const nyWinter = winter.toZonedDateTimeISO('America/New_York');
assert.equal(nyWinter.offset, '-05:00');
assert.equal(summer.toZonedDateTimeISO('America/New_York').offset, '-04:00'); // DST
assert.equal(winter.toZonedDateTimeISO('Asia/Kolkata').toPlainTime().toString(), '22:30:00');
console.log(nyWinter.toString()); // 2026-01-15T12:00:00-05:00[America/New_York]

// Build a wall time in a zone: 09:00 in New York, whatever the offset is that day.
const meeting = Temporal.ZonedDateTime.from('2026-03-09T09:00[America/New_York]');
assert.equal(meeting.toInstant().toString(), '2026-03-09T13:00:00Z'); // DST began 8 March

// DST-safe "add one day": a calendar day keeps 09:00 local; 24 hours does not.
const saturday = Temporal.ZonedDateTime.from('2026-03-07T09:00[America/New_York]');
const sunday = saturday.add({ days: 1 });
assert.equal(sunday.hour, 9);
assert.equal(saturday.until(sunday, { largestUnit: 'hours' }).hours, 23);
assert.equal(saturday.add({ hours: 24 }).hour, 10);

// 02:30 on 8 March does not exist there: 'compatible' (the default) moves it forward.
const gap = '2026-03-08T02:30[America/New_York]';
assert.equal(Temporal.ZonedDateTime.from(gap).hour, 3);
assert.throws(() => Temporal.ZonedDateTime.from(gap, { disambiguation: 'reject' }), RangeError);

// Display text comes from ICU and changes between versions: show it, don't compare it.
console.log(nyWinter.toLocaleString('en-US', { timeZoneName: 'short' }));
assert.throws(() => winter.toZonedDateTimeISO('Mars/Olympus'), RangeError);
console.log('local zone:', Temporal.Now.timeZoneId());

In practice: store instants in UTC and the user's IANA zone name (not an offset) alongside, do "same time tomorrow" arithmetic on a ZonedDateTime, and format for people with toLocaleString.

Temporal ships enabled in Node 26 and in current Chrome and Firefox. Node 22 and 24 run this program with temporal-polyfill 1.0.8 (node --import temporal-polyfill/global); TypeScript 6.0+ types it with lib "esnext.temporal".

Without Temporal, a Date has only UTC and the local zone. new Intl.DateTimeFormat("en-GB", { timeZone: "America/New_York", timeZoneName: "longOffset" }).format(date) shows an instant in another zone, but building a wall time in that zone needs a library such as date-fns-tz or Luxon.

Display text (toLocaleString, Intl) comes from ICU and CLDR and changes between releases: Node 24 writes the UTC long offset as "GMT+00:00" where Node 22 wrote "GMT". Assert on offset and fields, not on formatted strings.

Node bundles its own time zone database, so zone rules update with Node releases, not with the OS. The local zone comes from TZ or the OS; servers usually run in UTC.

Generate reproducible random numbers: seeded PRNGs, rand.NewPCG, StdRng, std::mt19937

TypeScript

Math.random cannot be seeded, so its output cannot be replayed. For tests, simulations and procedural content, use a small seeded PRNG such as mulberry32 (32-bit state, a few lines, good statistical quality for this use) and derive everything from it: integers in a range, shuffles (Fisher-Yates), choices.

Complete program

Complete program. Set TEST_SEED to replay a different sequence.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import assert from 'node:assert/strict';

// Math.random cannot be seeded. For repeatable runs, use a small seeded PRNG.
// mulberry32: 32-bit state, fast, good enough for tests and simulations (not for secrets).
function mulberry32(seed: number): () => number {
  let state = seed >>> 0;
  return () => {
    state = (state + 0x6d2b79f5) >>> 0;
    let t = state;
    t = Math.imul(t ^ (t >>> 15), t | 1);
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
    return ((t ^ (t >>> 14)) >>> 0) / 2 ** 32; // [0, 1)
  };
}

function intBetween(next: () => number, min: number, max: number): number {
  return min + Math.floor(next() * (max - min + 1)); // inclusive range
}

function shuffle<T>(items: readonly T[], next: () => number): T[] {
  const result = [...items];
  for (let i = result.length - 1; i > 0; i--) {
    const j = Math.floor(next() * (i + 1)); // Fisher-Yates
    [result[i], result[j]] = [result[j], result[i]];
  }
  return result;
}

// Same seed, same sequence: a failing test can be replayed exactly.
const seed = Number(process.env.TEST_SEED ?? 42);
const a = mulberry32(seed);
const b = mulberry32(seed);
const rollsA = Array.from({ length: 5 }, () => intBetween(a, 1, 6));
const rollsB = Array.from({ length: 5 }, () => intBetween(b, 1, 6));
assert.deepEqual(rollsA, rollsB);

const order = shuffle(['ann', 'bo', 'cy', 'di'], mulberry32(seed));
assert.deepEqual(order, shuffle(['ann', 'bo', 'cy', 'di'], mulberry32(seed)));
console.log(`seed=${seed} rolls=${rollsA.join(',')} order=${order.join(',')}`);

In practice: read the seed from an environment variable or test parameter, print it when a test fails, and pass the generator into the code under test instead of calling Math.random inside it. Property-testing libraries such as fast-check do this for you and report the failing seed.

mulberry32 has a period of 2^32; for long simulations use a larger-state generator such as xoshiro128** or sfc32.

Math.floor(next() * n) has a tiny bias for large n; it is negligible for tests but not for anything that decides money or fairness.

Seeded generators are predictable by design: never use them for tokens or passwords.

Generate secure random tokens: crypto.getRandomValues, crypto/rand, getrandom, OS CSPRNGs

TypeScript

Use the operating system's cryptographically secure generator, never Math.random. crypto.getRandomValues fills a typed array (Web Crypto, global in Node and browsers), crypto.randomUUID returns a version 4 UUID with 122 random bits, and node:crypto adds randomBytes and randomInt (an unbiased integer in a range).

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import assert from 'node:assert/strict';
import { randomBytes, randomInt, timingSafeEqual } from 'node:crypto';

// Web Crypto (a global in Node and browsers): fill a typed array from the OS CSPRNG.
const bytes = crypto.getRandomValues(new Uint8Array(16));
assert.equal(bytes.length, 16);

// A random (version 4) UUID: 122 random bits.
const id = crypto.randomUUID();
assert.match(id, /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);

// A session or reset token: 32 bytes (256 bits), URL-safe text.
const token = randomBytes(32).toString('base64url');
assert.equal(token.length, 43);

// An unbiased integer in [0, 1_000_000), e.g. a one-time code. Never use Math.random here.
const code = String(randomInt(1_000_000)).padStart(6, '0');
assert.match(code, /^\d{6}$/);

// Compare secrets in constant time (equal lengths required).
const presented = Buffer.from(token);
assert.ok(timingSafeEqual(presented, Buffer.from(token)));

console.log({ id, tokenLength: token.length, code });

In practice: make tokens from at least 16 bytes, preferably 32, encoded with base64url or hex; store only a hash of long-lived tokens; and compare presented secrets with timingSafeEqual so the comparison time does not leak where they differ.

getRandomValues accepts at most 65,536 bytes per call and only integer typed arrays.

randomUUID in browsers requires a secure context (HTTPS or localhost).

timingSafeEqual throws if the buffers differ in length; hash both sides first (for example SHA-256) when lengths can differ.