Files

72 lines
3.0 KiB
TypeScript

import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import { touch, TOUCH, UNTOUCHED, type TouchReply, type TouchState } from '../src/touch/touch.js';
/** Touches at these moments, from no touch at all; the replies in order. */
function replies(times: readonly number[], from: TouchState = UNTOUCHED): { replies: TouchReply['kind'][]; state: TouchState; all: TouchReply[] } {
let state = from;
const all: TouchReply[] = [];
for (const t of times) {
const next = touch(state, t);
all.push(next.reply);
state = next.state;
}
return { replies: all.map((r) => r.kind), state, all };
}
const T0 = 1_000_000;
describe('a touch (thorns.md)', () => {
it('is answered fondly, and only the first of a visit makes her blush', () => {
const r = replies([T0, T0 + 5000, T0 + 10_000]);
expect(r.all).toEqual([{ kind: 'fond', blush: true }, { kind: 'fond', blush: false }, { kind: 'fond', blush: false }]);
});
it('three within two seconds: thorns, then she rests, then all is as before', () => {
const r = replies([T0, T0 + 600, T0 + 1200, T0 + 1500, T0 + 1200 + TOUCH.restMs - 1, T0 + 1200 + TOUCH.restMs]);
expect(r.replies).toEqual(['fond', 'fond', 'thorns', 'nothing', 'nothing', 'fond']);
});
it('three touches spanning exactly two seconds are not a rush', () => {
expect(replies([T0, T0 + 1000, T0 + 2000]).replies).toEqual(['fond', 'fond', 'fond']);
});
it('touches closer than 250 ms to the one before are one touch: a tremor is never fussing', () => {
const burst = (at: number): number[] => [at, at + 60, at + 120, at + 180];
expect(replies([...burst(T0), ...burst(T0 + 1100)]).replies).toEqual(['fond', 'nothing', 'nothing', 'nothing', 'fond', 'nothing', 'nothing', 'nothing']);
});
it('a clock moved back never makes her rest longer than the rest time', () => {
const rushed = replies([T0, T0 + 500, T0 + 1000]);
expect(rushed.replies.at(-1)).toBe('thorns');
expect(touch(rushed.state, T0 - 3_600_000).reply.kind).toBe('fond');
});
it('property: touches a second or more apart are never a rush', () => {
fc.assert(
fc.property(fc.array(fc.integer({ min: 1000, max: 60_000 }), { minLength: 1, maxLength: 40 }), (gaps) => {
let t = T0;
const times = gaps.map((g) => (t += g));
expect(replies(times).replies.every((k) => k === 'fond')).toBe(true);
})
);
});
it('property: whatever the taps, she keeps no more than a rush of them, and blushes at most once', () => {
fc.assert(
fc.property(fc.array(fc.integer({ min: 0, max: 3000 }), { maxLength: 60 }), (gaps) => {
let t = T0;
let state = UNTOUCHED;
let blushes = 0;
for (const g of gaps) {
const next = touch(state, (t += g));
if (next.reply.kind === 'fond' && next.reply.blush) blushes++;
state = next.state;
expect(state.recent.length).toBeLessThan(TOUCH.rushCount);
}
expect(blushes).toBeLessThanOrEqual(1);
})
);
});
});