tests/sims/queues.test.ts
The automated tests for the /simulators/queue-stack simulator. They run the model on its own, outside the browser, and compare it with a reference that doesn't depend on the model being right. They run on every change to the simulator's code.
- Queue, stack, deque and two-stack queue behave like a plain array doing the same operations.
- Array doubling copies fewer than 2n elements, and a two-stack queue moves each element once.
- M/M/1: mean time in system is 1/(μ − λ) for both FIFO and LIFO, within 5%.
// /simulators/queue-stack
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { create, apply, contents, count, simulateLoad, type Kind, type Op } from '../../src/lib/sims/queues.ts';
import { checker } from './check.ts';
test('queue, stack, deque and two-stack queue behave like a plain array doing the same operations', () => {
const { ok, done } = checker();
let seed = 5;
const rnd = () => (seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648;
for (const kind of ['queue', 'stack', 'deque', 'twostack'] as Kind[]) {
for (let trial = 0; trial < 100; trial++) {
const d = create(kind);
const ref: number[] = [];
let v = 1;
for (let k = 0; k < 300; k++) {
const x = rnd();
const op: Op = kind === 'deque' ? (['pushBack', 'pushFront', 'popFront', 'popBack'] as Op[])[Math.floor(x * 4)] : x < 0.55 ? 'pushBack' : kind === 'stack' ? 'popBack' : 'popFront';
const r = apply(d, op, v);
let exp: number | null = null;
if (op === 'pushBack') ref.push(v);
else if (op === 'pushFront') ref.unshift(v);
else if (op === 'popFront') exp = ref.length ? ref.shift()! : null;
else exp = ref.length ? ref.pop()! : null;
if (op.startsWith('push')) v++;
else ok(r.removed === exp, `${kind} removed ${r.removed}, expected ${exp}`);
const want = kind === 'stack' ? [...ref].reverse() : ref;
ok(JSON.stringify(contents(d)) === JSON.stringify(want), `${kind} contents differ`);
ok(count(d) === ref.length, `${kind} count differs`);
}
}
}
done();
});
test('array doubling copies fewer than 2n elements, and a two-stack queue moves each element once', () => {
for (const n of [10, 1000, 100000]) {
const d = create('stack');
for (let i = 0; i < n; i++) apply(d, 'pushBack', i);
assert.ok(d.total.copies < 2 * n, `${d.total.copies} copies for ${n} pushes`);
const q = create('twostack');
for (let i = 0; i < n; i++) apply(q, 'pushBack', i);
for (let i = 0; i < n; i++) apply(q, 'popFront', 0);
assert.equal(q.total.moves, n);
}
});
test('M/M/1: mean time in system is 1/(μ − λ) for both FIFO and LIFO, within 5%', () => {
for (const load of [0.5, 0.8]) {
const th = 1 / (1 - load);
for (const disc of ['fifo', 'lifo'] as const) {
const r = simulateLoad(disc, { load, n: 300000, noDeadline: true, seed: 3 });
assert.ok(Math.abs(r.meanAll - th) / th < 0.05, `${disc} at load ${load}: ${r.meanAll} vs ${th}`);
}
}
});
Shared helpers: tests/sims/check.ts. The model under test is imported from src/lib/sims/.