# Test · Code
Each block exercises all Prism token categories: comments, keywords, strings, numbers, functions, classes, properties, operators, punctuation.
---
## Python
```python
# ── Ionian Navigation System ──────────────────────────────────────────────────
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Iterator
import math
KNOTS_TO_KMH: float = 1.852
MAX_WAYPOINTS: int = 24
TIDE_OFFSET: int = 0x3F # hex literal
FLAGS: int = 0b1010 # binary literal
EARTH_NM: float = 3_440.065
IONIAN_ISLANDS: tuple[str, ...] = (
"Κέρκυρα", "Λευκάδα", "Κεφαλονιά", "Ιθάκη", "Ζάκυνθος"
)
BearingError = type("BearingError", (ValueError,), {})
def validate_bearing(deg: float) -> float:
"""Normalise a bearing to [0, 360)."""
if not (0.0 <= deg < 360.0):
deg = deg % 360.0
return round(deg, 2)
@dataclass
class Position:
lat: float
lon: float
def distance_to(self, other: Position) -> float:
"""Haversine distance in nautical miles."""
φ1, φ2 = math.radians(self.lat), math.radians(other.lat)
dφ = math.radians(other.lat - self.lat)
dλ = math.radians(other.lon - self.lon)
a = (math.sin(dφ / 2) ** 2
+ math.cos(φ1) * math.cos(φ2) * math.sin(dλ / 2) ** 2)
return 2 * math.asin(math.sqrt(a)) * EARTH_NM
@dataclass
class Voyage:
origin: str
destination: str
speed_kn: float = 6.5
waypoints: list[str] = field(default_factory=list)
def sail(self, island: str, bearing: float = 0.0) -> None:
if island not in IONIAN_ISLANDS:
raise ValueError(f"Unknown island: {island!r}")
self.waypoints.append(island)
def legs(self) -> Iterator[tuple[str, str]]:
route = [self.origin, *self.waypoints, self.destination]
yield from zip(route, route[1:])
@property
def complete(self) -> bool:
return bool(self.waypoints) and self.waypoints[-1] == self.destination
odyssey = Voyage(origin="Τροία", destination="Ιθάκη", speed_kn=5.0)
try:
for island, bearing in [("Κέρκυρα", 195.5), ("Ιθάκη", 88.0)]:
odyssey.sail(island, bearing)
except (ValueError, OverflowError) as exc:
print(f"Navigation error: {exc}")
speeds = [KNOTS_TO_KMH * odyssey.speed_kn * h for h in range(1, 5)]
fmt_leg = lambda a, b: f"{a} → {b}"
route = ", ".join(fmt_leg(a, b) for a, b in odyssey.legs())
print(f"Route: {route} Complete: {odyssey.complete!r}")
```
---
## JavaScript (ES2022)
```javascript
// Dragon Catalogue — async fetch with error boundaries
const API_BASE = 'https://api.tenebrous-dragon.example/v2';
/** @typedef {{ id: string, name: string, cr: number, habitat: string[] }} DragonEntry */
class DragonCatalogue {
#cache = new Map();
#abortController = null;
constructor(baseUrl = API_BASE) {
this.baseUrl = baseUrl;
this.#cache.clear();
}
async fetchAll(signal) {
const url = `${this.baseUrl}/dragons?limit=100`;
const res = await fetch(url, { signal });
if (!res.ok) throw new Error(`HTTP ${res.status}: ${res.statusText}`);
return /** @type {DragonEntry[]} */ (await res.json());
}
async getByHabitat(habitat) {
if (this.#cache.has(habitat)) return this.#cache.get(habitat);
this.#abortController?.abort();
this.#abortController = new AbortController();
try {
const all = await this.fetchAll(this.#abortController.signal);
const filtered = all.filter(d => d.habitat.includes(habitat));
this.#cache.set(habitat, filtered);
return filtered;
} catch (err) {
if (err.name !== 'AbortError') console.error('Fetch failed:', err);
return [];
}
}
*[Symbol.iterator]() {
for (const [key, value] of this.#cache) {
yield { habitat: key, entries: value };
}
}
}
// Destructuring, rest/spread, optional chaining, nullish coalescing
const { name = 'Unknown', cr = 0, habitat: [primary = 'unknown'] = [] } = {};
const dragons = [
{ name: 'Sapphire', cr: 15, tags: ['gem', 'psionic'] },
{ name: 'Bronze', cr: 18, tags: ['metallic', 'coastal'] },
];
const sorted = dragons
.filter(d => d.cr >= 15)
.sort((a, b) => b.cr - a.cr)
.map(({ name, cr, tags }) => ({ name, cr, primary: tags[0] ?? 'none' }));
const catalogue = new DragonCatalogue();
const coastal = await catalogue.getByHabitat('coastal');
console.log(`Coastal dragons: ${coastal.length ?? 0}`);
```
---
## TypeScript
```typescript
// ── Typed Bestiary with generics, decorators, mapped types ────────────────────
type DragonSize = 'Wyrmling' | 'Young' | 'Adult' | 'Ancient' | 'Greatwyrm';
type Alignment = `${'Lawful' | 'Neutral' | 'Chaotic'} ${'Good' | 'Neutral' | 'Evil'}`;
interface CreatureStats {
readonly hp: number;
readonly ac: number;
readonly cr: number;
speed: Partial<Record<'walk' | 'fly' | 'swim', number>>;
}
interface DragonEntry extends CreatureStats {
name: string;
colour: string;
size: DragonSize;
align: Alignment;
breath: string;
habitat: string[];
}
type PartialEntry = Partial<DragonEntry>;
type RequiredEntry = Required<DragonEntry>;
type DragonKeys = keyof DragonEntry;
// Generic repository
class Repository<T extends { name: string }> {
private readonly store = new Map<string, T>();
add(item: T): this {
this.store.set(item.name, item);
return this;
}
get(name: string): T | undefined {
return this.store.get(name);
}
filter<K extends keyof T>(key: K, value: T[K]): T[] {
return [...this.store.values()].filter(item => item[key] === value);
}
*[Symbol.iterator](): IterableIterator<T> {
yield* this.store.values();
}
}
// Decorator factory
function LogMethod(label: string) {
return function (_target: object, key: string, descriptor: PropertyDescriptor) {
const original = descriptor.value as (...args: unknown[]) => unknown;
descriptor.value = function (...args: unknown[]) {
console.log(`[${label}] ${key}(${args.join(', ')})`);
return original.apply(this, args);
};
return descriptor;
};
}
class BestiaryService {
constructor(private readonly repo: Repository<DragonEntry>) {}
@LogMethod('Bestiary')
lookup(name: string): DragonEntry | undefined {
return this.repo.get(name);
}
bySize(size: DragonSize): DragonEntry[] {
return this.repo.filter('size', size);
}
}
const repo = new Repository<DragonEntry>();
repo
.add({ name: 'Sapphire', colour: 'blue', size: 'Ancient', align: 'Lawful Neutral',
hp: 297, ac: 20, cr: 22, breath: 'Psychic', habitat: ['Underdark'],
speed: { walk: 40, fly: 80 } })
.add({ name: 'Bronze', colour: 'bronze', size: 'Adult', align: 'Lawful Good',
hp: 212, ac: 18, cr: 15, breath: 'Lightning', habitat: ['Coastal'],
speed: { walk: 40, fly: 80, swim: 40 } });
const service = new BestiaryService(repo);
const ancient = service.bySize('Ancient');
console.log(ancient.map(d => `${d.name} (CR ${d.cr})`));
```
---
## Bash
```bash
#!/usr/bin/env bash
# vault-backup.sh -- Backup Obsidian vaults to iCloud
set -euo pipefail
IFS=