예제
실용적인 예제와 라이브 데모.
예제를 선택하면 라이브 미리보기와 소스 코드를 나란히 표시하는 전체 화면이 열립니다.
예제를 선택하면 라이브 미리보기와 소스 코드를 나란히 표시하는 전체 화면이 열립니다.
엔진은 평범한 JavaScript입니다. 배열을 바꾸고 단계마다 yield하는 제너레이터가 전부입니다. 플레이어는 next()와 update()를 호출하고, 막대는 같은 객체를 쓰는 list()이므로 교환할 때 움직이는 요소는 두 개뿐입니다.
// app.ts: the player. The state is a handful of plain variables; the UI reads // them through functions. next() is the only place the engine runs, and the // one update() in it is what refreshes the bars, the counters and the status. import "nuclo"; import { ALGORITHMS, type Item, type Step } from "./algorithms.ts"; import { s } from "./styles.ts"; const SIZE = 24; let start: number[] = Array.from({ length: SIZE }, (_, i) => ((i * 7) % SIZE) + 1); let items: Item[] = []; let algorithm: keyof typeof ALGORITHMS = "Bubble"; let run: Generator<Step, void> | null = null; let step: Step | null = null; // the last thing the algorithm did let compares = 0; let swaps = 0; let playing = false; let speed = 30; // steps per second let timer: ReturnType<typeof setTimeout> | undefined; function reset() { stop(); items = start.map((value) => ({ value, sorted: false })); run = null; step = null; compares = swaps = 0; update(); } function shuffle() { for (let i = start.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [start[i], start[j]] = [start[j], start[i]]; } reset(); } // One step: the generator mutates `items`, we note what it did, then update(). function next() { run ??= ALGORITHMS[algorithm](items); const result = run.next(); if (result.done) { stop(); step = null; } else { step = result.value; if (step.kind === "swap") swaps++; else compares++; } update(); } function play() { playing = true; tick(); } function tick() { next(); if (playing) timer = setTimeout(tick, 1000 / speed); } function stop() { playing = false; clearTimeout(timer); } reset(); const isActive = (item: Item) => step !== null && (step.a === item || step.b === item); const status = () => { if (!step) return items.every((item) => item.sorted) ? "Sorted." : "Press Play or Step."; return step.kind === "swap" ? `Swapped ${step.a.value} and ${step.b.value}` : `Compared ${step.a.value} with ${step.b.value}`; }; export function SortingStepper() { return div( s.app, on("destroy", stop), div( s.toolbar, select( s.select, { value: () => algorithm, "aria-label": "Algorithm" }, { onChange: (e) => { algorithm = e.currentTarget.value as keyof typeof ALGORITHMS; reset(); } }, ...Object.keys(ALGORITHMS).map((name) => option({ value: name }, name)), ), button(s.btn, s.primary, () => (playing ? "Pause" : "Play"), { onClick: () => { if (playing) { stop(); update(); } else play(); } }), button(s.btn, "Step", { disabled: () => playing, onClick: next }), button(s.btn, "Reset", { onClick: reset }), button(s.btn, "Shuffle", { onClick: shuffle }), label( s.speed, "Speed", input({ type: "range", min: "1", max: "120", value: () => String(speed) }, { onInput: (e) => { speed = Number(e.currentTarget.value); update(); } }), span(() => `${speed}/s`), ), ), // Items are tracked by identity: a swap moves two existing bars, it never // rebuilds them. The height is static; only the class is read again. div( s.bars, list( () => items, (item) => div( s.bar, { style: { height: `${(item.value / SIZE) * 100}%` } }, { class: () => cx(s.bar, isActive(item) ? (step!.kind === "swap" ? s.swap : s.compare) : item.sorted ? s.sorted : null).className }, span(s.value, String(item.value)), ), ), ), div( s.status, span(() => `${compares} comparisons · ${swaps} swaps`), span(status), ), div( s.legend, span(s.key, span(s.dot, s.compare), "Comparing"), span(s.key, span(s.dot, s.swap), "Swapping"), span(s.key, span(s.dot, s.sorted), "In place"), ), ); }
// algorithms.ts: the engine. Plain generators over a plain array; nothing here // knows about the DOM or about nuclo. Each one mutates `items` in place and // yields after every comparison or swap, so whoever drives it (a UI, a test) // can stop between any two steps and look at the array as it is right now. export interface Item { value: number; sorted: boolean; // set by the algorithm once the item is in its final place } export type Step = | { kind: "compare"; a: Item; b: Item } | { kind: "swap"; a: Item; b: Item }; export type Algorithm = (items: Item[]) => Generator<Step, void>; function* greater(items: Item[], i: number, j: number): Generator<Step, boolean> { yield { kind: "compare", a: items[i], b: items[j] }; return items[i].value > items[j].value; } function* swap(items: Item[], i: number, j: number): Generator<Step, void> { [items[i], items[j]] = [items[j], items[i]]; yield { kind: "swap", a: items[i], b: items[j] }; } export function* bubbleSort(items: Item[]): Generator<Step, void> { for (let end = items.length - 1; end > 0; end--) { for (let i = 0; i < end; i++) { if (yield* greater(items, i, i + 1)) yield* swap(items, i, i + 1); } items[end].sorted = true; } items[0].sorted = true; } export function* insertionSort(items: Item[]): Generator<Step, void> { for (let i = 1; i < items.length; i++) { for (let j = i; j > 0 && (yield* greater(items, j - 1, j)); j--) { yield* swap(items, j - 1, j); } } for (const item of items) item.sorted = true; } export function* selectionSort(items: Item[]): Generator<Step, void> { for (let i = 0; i < items.length; i++) { let min = i; for (let j = i + 1; j < items.length; j++) { if (yield* greater(items, min, j)) min = j; } if (min !== i) yield* swap(items, i, min); items[i].sorted = true; } } export function* quickSort(items: Item[], lo = 0, hi = items.length - 1): Generator<Step, void> { if (lo > hi) return; let p = lo; // everything before p is smaller than the pivot, items[hi] for (let i = lo; i < hi; i++) { if (yield* greater(items, hi, i)) { if (i !== p) yield* swap(items, i, p); p++; } } if (p !== hi) yield* swap(items, p, hi); items[p].sorted = true; yield* quickSort(items, lo, p - 1); yield* quickSort(items, p + 1, hi); } export const ALGORITHMS = { Bubble: bubbleSort, Insertion: insertionSort, Selection: selectionSort, Quick: quickSort, } satisfies Record<string, Algorithm>;
import "nuclo"; const mono = "ui-monospace, monospace"; const control = { height: "34px", padding: "0 12px", borderRadius: "8px", border: "1px solid var(--c-border-light)", backgroundColor: "var(--c-bg)", color: "var(--c-text)", fontFamily: "inherit", fontSize: "0.875rem" }; export const s = { app: css("sorting-app", { display: "flex", flexDirection: "column", gap: "14px", width: "100%", height: "100%", minHeight: "360px" }), toolbar: css("sorting-toolbar", { display: "flex", flexWrap: "wrap", alignItems: "center", gap: "8px" }), select: css("sorting-select", { ...control, paddingRight: "28px" }), btn: css("sorting-btn", { ...control, fontWeight: "600", hover: { backgroundColor: "var(--c-bg-secondary)" }, "&:disabled": { opacity: "0.45", cursor: "default" } }), primary: css("sorting-primary", { minWidth: "72px", backgroundColor: "var(--c-primary-dark)", borderColor: "transparent", color: "#fff", hover: { backgroundColor: "var(--c-primary-dark)", filter: "brightness(0.92)" } }), speed: css("sorting-speed", { display: "flex", alignItems: "center", gap: "8px", marginLeft: "auto", fontSize: "0.8125rem", color: "var(--c-text-dim)", "& input": { width: "120px", accentColor: "var(--c-primary)" }, "& span": { fontFamily: mono, fontSize: "0.75rem", minWidth: "40px" }, "@media (max-width: 599px)": { flexBasis: "100%", marginLeft: "0", "& input": { flex: "1", width: "auto" } } }), bars: css("sorting-bars", { display: "flex", alignItems: "flex-end", gap: "3px", flex: "1", minHeight: "0", padding: "12px 0 0", borderBottom: "1px solid var(--c-border)" }), bar: css("sorting-bar", { position: "relative", flex: "1", minWidth: "0", borderRadius: "4px 4px 0 0", backgroundColor: "color-mix(in srgb, var(--c-text-muted) 34%, transparent)", transition: "background-color 0.12s ease" }), compare: css("sorting-compare", { backgroundColor: "var(--c-accent-cool)" }), swap: css("sorting-swap", { backgroundColor: "var(--c-primary)" }), sorted: css("sorting-sorted", { backgroundColor: "#22c55e", opacity: "0.75" }), legend: css("sorting-legend", { display: "flex", flexWrap: "wrap", gap: "4px 14px", fontSize: "0.75rem", color: "var(--c-text-dim)" }), key: css("sorting-key", { display: "inline-flex", alignItems: "center", gap: "6px" }), dot: css("sorting-dot", { width: "10px", height: "10px", borderRadius: "3px" }), value: css("sorting-value", { position: "absolute", top: "-18px", left: "0", right: "0", textAlign: "center", fontFamily: mono, fontSize: "0.625rem", color: "var(--c-text-muted)", "@media (max-width: 600px)": { display: "none" } }), status: css("sorting-status", { display: "flex", flexWrap: "wrap", justifyContent: "space-between", gap: "4px 12px", fontFamily: mono, fontSize: "0.75rem", color: "var(--c-text-dim)", "& span:last-child": { color: "var(--c-text)" } }), };