Files

788 lines
34 KiB
TypeScript

import type { VarietyPack } from "../../variety/pack.ts";
import type { SavedWord } from "../saved/types.ts";
import { due } from "../saved/review.ts";
import { allItems } from "./generate.ts";
import { EMPTY_MODEL, ladderOf, pressureOf, type LearnerModel } from "./model.ts";
import { DEFAULT_DIFFICULTY, fadedOut, levelCost, targetLevel, type Difficulty } from "./difficulty.ts";
import type { Level } from "../vocabulary/distance.ts";
import { NO_MEMORY, dueOrder, urgency, type Memory } from "./memory.ts";
import { SESSION_SIZE, type PracticeItem } from "./types.ts";
import type { Random } from "./random.ts";
import { KIND_BY_ID } from "./kinds/registry.ts";
/**
* What one sitting asks, and in what order.
*
* THE LEARNER'S OWN WORDS COME FIRST, AND ONLY WHEN THEY ARE DUE.
*
* A word is due on the schedule in `review.ts`, and practice must not override
* it: asking a word early because the session needed filling would spend the
* spacing effect the whole schedule exists to produce, and asking it late is
* what the schedule is for. So due words are taken in order, and the pack's
* items fill whatever is left.
*
* That ordering is also the honest one for a new learner. Someone who has kept
* nothing yet gets a session entirely of pack items — real, checkable, and
* available on day one — rather than an empty screen telling them to come back
* when they have saved something.
*
* RANDOM ONLY WHERE THE ORDER WAS ARBITRARY.
*
* Due before new, struggling before fine, least-recently-asked first: those
* stay facts about the learner. Between questions they leave tied — which, for
* a new learner, is nearly all of them — the order used to be alphabetical,
* so everybody met the same sitting. A seeded `random` (see `random.ts`)
* breaks those ties instead: tests pass a seed, resuming uses stored ids.
*/
export function buildSession({
pack,
saved,
now,
seen = [],
size = SESSION_SIZE,
}: {
pack: VarietyPack;
saved: readonly SavedWord[];
/** Passed in, never read from the clock here — so tests are not tests of today. */
now: Date;
/** Item ids already asked, most recent last. */
seen?: readonly string[];
size?: number;
}): PracticeItem[] {
return orderSession({ items: allItems(pack, saved), saved, now, seen, size });
}
/**
* The same session, from items that have already been generated.
*
* WHY A SECOND ENTRY POINT EXISTS, since one is otherwise a smell.
*
* The two halves of a session come from two places that cannot meet on one
* side of the wire. The pack's items are the same for everybody and belong on
* the server, where the pack already lives — shipping `VarietyPack` to the
* browser to regenerate them would send every rule's prose and every grammar
* topic's explanation in order to build eight questions out of them. The
* learner's own words are in their browser's storage and have never been sent
* anywhere, which is the point of §7 and not a thing to relax for an exercise
* page.
*
* So the page generates the pack half on the server, the client generates the
* recall half from storage, and this orders the two together. The ordering —
* due first, then a balanced mix, then interleaved — is the part that must not
* fork, and now cannot.
*/
export function orderSession(options: PlanOptions): PracticeItem[] {
return planSession(options).items;
}
/**
* HOW MUCH OF A SITTING IS NEW, while there is anything new to ask.
*
* WHAT THIS FIXES, with the numbers that found it. Every answer is due again
* a day later (`REVIEW_STEPS` starts at 1), and due questions were seated
* before anything new, without limit. So a learner who practised once a day
* met, in ten sittings of eight, 24 different questions in 80 seats: half the
* sittings held nothing new at all, and four seats in five were questions
* already seen. That is the schedule working and the product feeling like a
* loop. The owner's report, 2026-11-25: "the same exact exercises over and
* over again".
*
* So the sitting is SHARED: at least half its seats go to questions never
* answered, as long as the scope still has some; the rest go to what is due,
* most overdue first. A due question that finds no seat stays due and leads
* the next sitting — reviews are delayed by a sitting, never dropped.
*
* Half is OURS, not a finding. The spacing literature says reviews must come
* back; it does not say they must fill the room.
*/
export const NEW_SHARE = 0.5;
/**
* How much of a sitting on the learner's own situations comes from the
* situations NEXT to them (`adjacent.ts`). A quarter: enough that the chosen
* scenes still own the sitting, and that it does not close in on the same
* hundred and fifty questions.
*/
export const BEYOND_SHARE = 0.25;
/**
* How far above the level aimed at a new question may be: one band. A sitting
* is "your level, with a stretch" — which also keeps the kinds that have
* nothing on level 1 (sound-rule pairs, grammar) in a beginner's sitting.
* Never below: see `levelCost`.
*/
export const STRETCH = 1;
/**
* How many past sittings a question stays out for once it has been shown and
* left unanswered (a skip, or a sitting closed half way). An answered question
* has a due date and waits for it; this covers the ones with no date.
*/
export const RECENT_SITTINGS = 3;
/** Why each question is in the sitting, and what the scope has left. */
export type Plan = {
items: PracticeItem[];
/** Ids here because their day has come (kept words included). */
due: string[];
/** Ids never answered before, from the scope itself. */
fresh: string[];
/** Ids never answered before, from next to the scope. */
beyond: string[];
/** Ids asked before their day, because the caller asked for that (`rest: "fill"`). */
early: string[];
/**
* For a review asked in another form: the seated question's id to the id of
* the question whose card was due. A review asked as itself is not listed.
*/
reviewOf: Record<string, string>;
/** Questions of the scope never answered and not in this sitting: what is left to meet. */
left: number;
/** Due questions that found no seat this time. They lead the next sitting. */
waiting: number;
/** The level band the new questions were drawn for (`difficulty.ts`). */
target: Level;
};
export type PlanOptions = {
items: readonly PracticeItem[];
saved: readonly SavedWord[];
now: Date;
seen?: readonly string[];
size?: number;
/**
* Words this sitting promised to ask — «learn these ten» on /vocabulary.
* Each gets a seat before the mix is filled, and the sitting grows to hold
* them all: eight seats for ten named words broke the promise on its face.
*/
cover?: readonly string[];
/**
* What this learner keeps getting wrong. Empty by default — a new learner
* has no model and gets the plain ordering.
*/
model?: LearnerModel;
/**
* When each question is due again (`memory.ts`). Empty by default, which
* makes every item "new".
*/
memory?: Memory;
/**
* Where the order was arbitrary — between questions equally urgent, equally
* hard and equally fresh, and between kinds the same — this decides instead
* of the alphabet (`random.ts`). Omitted, the old deterministic order.
*/
random?: Random;
/** The learner's own setting for how hard the new questions are (`difficulty.ts`). */
difficulty?: Difficulty;
/**
* Questions from NEXT to the scope: a share of the new seats (`BEYOND_SHARE`),
* and the first place a sitting looks when its own scope has nothing new.
*/
beyond?: readonly PracticeItem[];
/**
* What to do when neither a due nor a new question is left: `skip` leaves
* the seat empty — the caller says the scope is used up and offers to widen
* it — and `fill` asks questions before their day, soonest first, which is
* what "again anyway" means.
*/
rest?: "skip" | "fill";
/** Ids that must not be seated: what a sitting in progress already holds. */
without?: readonly string[];
/** Only new questions — for swapping the rest of a sitting to another level. */
newOnly?: boolean;
};
/**
* One thing a question is ABOUT: a word, a line of a scene, a rule. Two
* questions about the same thing in one sitting give each other's answer away
* («Stimmt das?» on a line, then building the same line), and are also the
* sameness the learner reported. One per sitting, while there is a choice.
*/
export function subjectOf(item: PracticeItem): string {
const source = item.source;
switch (source.kind) {
case "word":
return `word:${source.word}`;
case "situation":
return source.line === undefined ? `item:${item.id}` : `line:${source.scene}:${source.line}`;
case "rule":
return `rule:${source.rule}`;
default:
return `item:${item.id}`;
}
}
/**
* The sitting, and why each question is in it.
*
* `orderSession` above is this without the reasons; the session screen uses
* the reasons to say what the sitting is before it starts and what was new at
* the end.
*/
/** Questions answered before a typed one may be asked: two sittings. */
export const WRITE_AFTER = 16;
export function planSession({
items,
saved,
now,
seen = [],
size = SESSION_SIZE,
model = EMPTY_MODEL,
memory = NO_MEMORY,
cover = [],
random,
difficulty = DEFAULT_DIFFICULTY,
beyond = [],
rest = "skip",
without = [],
newOnly = false,
}: PlanOptions): Plan {
const dueIds = new Set(due([...saved], now).map((word) => `recall:${word.target.trim().toLocaleLowerCase()}`));
const barred = new Set(without);
const own = new Set(items.map((item) => item.id));
const outside = beyond.filter((item) => !own.has(item.id));
const isOutside = new Set(outside.map((item) => item.id));
const isDueRecall = (item: PracticeItem) => item.kind === "recall" && dueIds.has(item.id);
// A word that is NOT due is not asked at all. It is not filler: showing it
// early is the one thing the schedule is there to prevent.
const eligible = [...items, ...outside].filter(
(item) => !barred.has(item.id) && (item.kind !== "recall" || isDueRecall(item)),
);
// TAPPING FIRST. A question that has to be typed is not put to somebody in
// their first sittings: measured on 2026-11-28, a brand-new learner met a
// typed translation in 55% of first sittings and as the very first question
// in 7%. Typing is the harder way to take a turn and a choice, never the
// price of entry. A sitting scoped to typed questions alone still gets them.
const typed = (item: PracticeItem) => KIND_BY_ID.get(item.kind)?.answering === "write";
// Experience is what was shown lately OR what has a card: either says "not new here".
const early = Math.max(seen.length, Object.keys(memory).length) < WRITE_AFTER;
const tappable = eligible.filter((item) => !typed(item));
const candidates = early && tappable.length > 0 ? tappable : eligible;
// Held back, not gone: still part of what the scope has left to show.
const heldBack = candidates === eligible ? [] : eligible.filter(typed);
const seenAt = new Map(seen.map((id, i) => [id, i]));
const freshness = (item: PracticeItem) => (seenAt.has(item.id) ? seenAt.get(item.id)! : -1);
const recent = new Set(seen.slice(-RECENT_SITTINGS * size));
// Subjects this learner has met: anything with a card, or shown lately.
const touched = new Set<string>();
for (const item of [...items, ...outside]) {
if (memory[item.id] !== undefined || seenAt.has(item.id)) touched.add(subjectOf(item));
}
/**
* Pressure first, then recency — and the order of those two is the whole of
* "the system should be smarter".
*
* Recency alone made a topic somebody has missed four times out of four
* exactly as likely to come up as one they have never got wrong. Sorting by
* what the learner keeps missing puts `isch gsi` in front of them until it
* stops being missed, which is how a form becomes a reflex rather than a
* thing they once read.
*
* IT IS BANDED, NOT RAW, and that matters. A continuous sort on pressure
* would let one bad area own every sitting: the same eight questions, in the
* same order, until answered correctly — which is both unpleasant and the
* opposite of the interleaving the session is built on. Rounding to a few
* bands means "clearly struggling" beats "fine", while everything inside a
* band is still ordered by what has been asked least recently. Variety is
* preserved; the weight is on the weak half.
*
* A learner with no model has every pressure at 0, so this collapses to the
* recency ordering exactly — which is what makes it safe to turn on for
* everybody from the first answer.
*/
const band = (item: PracticeItem) => Math.round(pressureOf(model, item) * 4);
const target = targetLevel(model, difficulty);
// One draw per question and per kind, made once, so the sort stays a
// consistent order rather than a different coin on every comparison.
const lot = new Map<string, number>();
const draw = (key: string) => {
if (!random) return 0;
let value = lot.get(key);
if (value === undefined) {
value = random();
lot.set(key, value);
}
return value;
};
/**
* WHEN. A question whose day has come is a review; one never answered is
* new; one answered and not due yet is resting, and is not asked at all
* unless the caller says "again anyway" (`memory.ts`) — asking it early
* spends the spacing. A question shown lately and left unanswered rests too.
*/
type State = "due" | "new" | "resting";
const stateOf = (item: PracticeItem): State => {
if (isDueRecall(item)) return "due";
const when = urgency(memory, item.id, now);
// «Like German», never missed, and the learner is past that level: it
// has done its work (`fadedOut`).
if (when !== 1 && fadedOut(item, memory[item.id], target)) return "resting";
if (when === 0) return "due";
if (when === 2) return "resting";
return recent.has(item.id) ? "resting" : "new";
};
const rank = (a: PracticeItem, b: PracticeItem) => {
const dueGap = dueOrder(memory, a.id, b.id);
if (dueGap !== 0) return dueGap;
const pressureGap = band(b) - band(a);
if (pressureGap !== 0) return pressureGap;
// Recognise a line first, produce it once it is recognised (`ladderOf`).
const ladderGap = ladderOf(model, a) - ladderOf(model, b);
if (ladderGap !== 0) return ladderGap;
// On the level aimed at before off it (`levelCost`).
const levelGap = levelCost(a, target) - levelCost(b, target);
if (levelGap !== 0) return levelGap;
// A subject not met yet before one already met (`touched`): with fifteen
// forms per word, the next new question was often the same word again.
const metGap = (touched.has(subjectOf(a)) ? 1 : 0) - (touched.has(subjectOf(b)) ? 1 : 0);
if (metGap !== 0) return metGap;
// Whatever has been asked least recently. Never-seen items (-1) come before
// anything seen, oldest-seen before newest.
const freshGap = freshness(a) - freshness(b);
if (freshGap !== 0) return freshGap;
// Between two cards, the word heard more often (`CardItem.order`).
if (a.kind === "card" && b.kind === "card" && a.order !== b.order) return a.order - b.order;
// Then luck, when the sitting was given a seed; then a stable tiebreak,
// so the same inputs (and the same seed) give the same session.
const luck = draw(a.id) - draw(b.id);
if (luck !== 0) return luck;
return a.id.localeCompare(b.id);
};
/**
* PICK A MIX, THEN ORDER IT — not the other way round.
*
* Sorting everything and taking the first eight was the obvious version and
* it produced eight cloze items in a row: the tiebreak is alphabetical, and
* "cloze" sorts before "pair". Interleaving afterwards could not fix it,
* because by then the eight were all one kind. Selection has to be the thing
* that balances. So every group below is kept BY KIND, and seats are dealt
* to the kinds in turn.
*/
type Buckets = Map<string, PracticeItem[]>;
const bucketsOf = (group: readonly PracticeItem[]): Buckets => {
const buckets: Buckets = new Map();
for (const item of group) {
const bucket = buckets.get(item.kind) ?? [];
bucket.push(item);
buckets.set(item.kind, bucket);
}
for (const bucket of buckets.values()) bucket.sort(rank);
return buckets;
};
const dueRecalls = newOnly ? [] : candidates.filter(isDueRecall).sort(rank);
const others = candidates.filter((item) => !isDueRecall(item));
/**
* A REVIEW COMES BACK IN ANOTHER FORM.
*
* Simulated on 2026-11-28, a learner who practised daily and got everything
* right met 52 different questions in 96: half of every sitting was the
* identical question again, same form, same four options. Reported in the
* owner's words as "the same shit over and over". The pack has 1,498
* subjects asked in up to fifteen forms, so the repeat was a choice.
*
* What is due is the SUBJECT (a word, a line, a rule). So where the scope
* has a question about the same subject in a different form that has never
* been answered, that one takes the review's seat: the word comes back on
* its day, as a gap instead of a choice. Its answer is written to the card
* that was due (`recordAnswer`, "stand-in"), so the schedule does not fork.
* With no such sibling the question itself is asked, as before.
*/
const dueNow = newOnly ? [] : others.filter((item) => stateOf(item) === "due").sort(rank);
const freshNow = others.filter((item) => !isOutside.has(item.id) && stateOf(item) === "new");
const standIn = new Map<string, PracticeItem>();
const taken = new Set<string>();
{
const bySubject = new Map<string, PracticeItem[]>();
for (const item of freshNow) {
const subject = subjectOf(item);
if (subject.startsWith("item:")) continue;
const list = bySubject.get(subject) ?? [];
list.push(item);
bySubject.set(subject, list);
}
for (const due of dueNow) {
const sibling = (bySubject.get(subjectOf(due)) ?? [])
.filter((item) => item.kind !== due.kind && !taken.has(item.id))
.sort(rank)[0];
if (!sibling) continue;
standIn.set(due.id, sibling);
taken.add(sibling.id);
}
}
const reviews = bucketsOf(dueNow.map((item) => standIn.get(item.id) ?? item));
const fresh = bucketsOf(freshNow.filter((item) => !taken.has(item.id)));
const adjacent = bucketsOf(others.filter((item) => isOutside.has(item.id) && stateOf(item) === "new"));
const resting = bucketsOf(
rest === "fill" && !newOnly ? others.filter((item) => !isOutside.has(item.id) && stateOf(item) === "resting") : [],
);
const count = (buckets: Buckets) => [...buckets.values()].reduce((n, bucket) => n + bucket.length, 0);
const freshInScope = count(fresh);
// The order the kinds take turns in: fixed for the same inputs, and still
// MOVING between sittings. It was alphabetical, and with more kinds than
// seats the first eight names took the eight seats every time — `translate`
// never appeared in a mixed sitting at all. Now the kind asked LEAST
// RECENTLY sits first. Item freshness cannot do this on its own: every kind
// has an unseen item at its head for weeks, so they would all tie.
const kindOf = new Map(candidates.map((item) => [item.id, item.kind]));
const lastAsked = new Map<string, number>();
for (const [at, id] of seen.entries()) {
const kind = kindOf.get(id);
if (kind) lastAsked.set(kind, at);
}
const turnsOf = (buckets: Buckets) =>
[...buckets.keys()].filter((kind) => buckets.get(kind)!.length > 0).sort((a, b) => {
// A kind the model says is weak goes first (its head item's band).
const pressureGap = band(buckets.get(b)![0]!) - band(buckets.get(a)![0]!);
if (pressureGap !== 0) return pressureGap;
const recencyGap = (lastAsked.get(a) ?? -1) - (lastAsked.get(b) ?? -1);
if (recencyGap !== 0) return recencyGap;
const luck = draw(`kind:${a}`) - draw(`kind:${b}`);
if (luck !== 0) return luck;
return a.localeCompare(b);
});
const picked: PracticeItem[] = [];
const subjects = new Set<string>();
const why = { due: [] as string[], fresh: [] as string[], beyond: [] as string[], early: [] as string[] };
const seat = (item: PracticeItem, reason: keyof typeof why) => {
picked.push(item);
subjects.add(subjectOf(item));
why[reason].push(item.id);
};
/**
* Deal up to `upTo` seats from one group, the kinds taking turns. First
* only questions about something this sitting has not touched (`subjectOf`);
* a second pass relaxes that, because a short scope is better asked twice
* about one line than not asked.
*
* `onLevel` is for NEW questions: in each round only the kinds whose next
* question is on the level aimed at, or one band above it (`STRETCH`), take
* a seat. Without it the kinds simply took turns, and a kind with nothing
* on the learner's level (the clock times are all level 3) handed a
* beginner its hardest question, while a learner past level 1 kept being
* dealt «like German» ones. A review is asked when it is due, whatever its
* level.
*
* And the stretch stays a stretch: while a kind still has a question on the
* nearest level, at most half of what one deal seats is above it. Which
* kinds come first is luck (`turnsOf`), and with more kinds that have
* nothing on level 1 than kinds that do, luck alone could hand a beginner a
* sitting that is mostly one band too high.
*/
const deal = (buckets: Buckets, reason: keyof typeof why, upTo: number, onLevel = false) => {
const kinds = turnsOf(buckets);
const stretchAtMost = Math.floor(Math.max(0, upTo - picked.length) / 2);
let stretched = 0;
for (const distinct of [true, false]) {
let moved = true;
while (picked.length < upTo && moved) {
moved = false;
const next = (kind: string) => {
const bucket = buckets.get(kind) ?? [];
return distinct ? bucket.findIndex((item) => !subjects.has(subjectOf(item))) : bucket.length > 0 ? 0 : -1;
};
const costs = onLevel
? kinds.map((kind) => (next(kind) === -1 ? Infinity : levelCost(buckets.get(kind)![next(kind)]!, target)))
: [];
const nearest = Math.min(...costs);
for (const [turn, kind] of kinds.entries()) {
if (picked.length >= upTo) break;
if (onLevel && costs[turn]! > nearest + STRETCH) continue;
const stretch = onLevel && costs[turn]! > nearest;
if (stretch && stretched >= stretchAtMost) continue;
const at = next(kind);
if (at === -1) continue;
seat(buckets.get(kind)!.splice(at, 1)[0]!, reason);
if (stretch) stretched += 1;
moved = true;
}
}
}
};
// Due words lead: they are the learner's own, and the only items with a
// deadline on the word itself.
for (const word of dueRecalls.slice(0, size)) seat(word, "due");
// Then one question per promised word, of whichever kind the sitting has
// least of so far, so ten named words do not become ten cards in a row.
const used = (kind: string) => picked.filter((item) => item.kind === kind).length;
for (const word of cover) {
const options = [reviews, fresh, resting]
.flatMap((buckets) => [...buckets.values()])
.map((bucket) => bucket.find((item) => item.source.kind === "word" && item.source.word === word))
.filter((item): item is PracticeItem => item !== undefined)
.sort((a, b) => used(a.kind) - used(b.kind) || rank(a, b));
const choice = options[0];
if (!choice) continue;
const state = stateOf(choice);
const home = state === "due" ? reviews : state === "new" ? fresh : resting;
const bucket = home.get(choice.kind)!;
bucket.splice(bucket.indexOf(choice), 1);
if (bucket.length === 0) home.delete(choice.kind);
seat(choice, state === "due" ? "due" : state === "new" ? "fresh" : "early");
}
const seats = Math.max(size, picked.length);
// THE SHARE (`NEW_SHARE`): seats held back for new questions, as many as
// there are new questions to put in them.
const newSeats = Math.min(count(fresh) + count(adjacent), Math.max(1, Math.round(seats * NEW_SHARE)));
deal(reviews, "due", seats - newSeats);
// New questions: the scope's own, less the share from next to it; then the
// neighbours; then whichever of the two still has something.
const outsideSeats = Math.min(count(adjacent), Math.round(seats * BEYOND_SHARE));
deal(fresh, "fresh", seats - outsideSeats, true);
deal(adjacent, "beyond", seats, true);
deal(fresh, "fresh", seats, true);
// Nothing new anywhere: the reviews that were held back take the room.
deal(reviews, "due", seats);
// And only on request, questions before their day — soonest first.
deal(resting, "early", seats);
return {
items: tapFirst(interleave(picked), seen.length === 0 && Object.keys(memory).length === 0 && dueRecalls.length === 0),
...why,
reviewOf: Object.fromEntries(
[...standIn.entries()].filter(([, seated]) => why.due.includes(seated.id)).map(([due, seated]) => [seated.id, due]),
),
left: freshInScope - why.fresh.length + heldBack.filter((item) => !isOutside.has(item.id) && stateOf(item) === "new").length,
waiting: count(reviews) + Math.max(0, dueRecalls.length - size),
target,
};
}
/**
* Swap the NEW questions still ahead in a sitting for others — what "too
* easy?" does half way through.
*
* Only questions not yet reached, and only the new ones: a review is here
* because its day came, and a missed question waiting for its second attempt
* is here because it was missed; neither is a matter of level. Each new one
* ahead takes the next replacement, in order; with fewer replacements than
* places, the rest stay as they were.
*/
export function swapFresh({
queue,
at,
fresh,
replacements,
}: {
queue: readonly PracticeItem[];
/** The question on screen. Everything after it may be swapped. */
at: number;
/** Ids that were new when the sitting was planned. */
fresh: readonly string[];
replacements: readonly PracticeItem[];
}): PracticeItem[] {
const isNew = new Set(fresh);
const reached = new Set(queue.slice(0, at + 1).map((item) => item.id));
const next = [...replacements];
return queue.map((item, i) => {
if (i <= at || !isNew.has(item.id) || reached.has(item.id)) return item;
return next.shift() ?? item;
});
}
/**
* Keep two items of the same kind from sitting next to each other where that
* can be avoided.
*
* Not decoration. Eight multiple-choice questions in a row is the shape that
* makes a person stop reading the options and start pattern-matching the
* layout — and the variety is the part of "enjoyable" this module can actually
* deliver without inventing a score.
*
* Best-effort by construction: when the session is all one kind there is
* nothing to interleave, and it returns the order it was given rather than
* pretending otherwise.
*/
/**
* The very first question somebody meets is one they answer with a tap.
*
* Measured on 2026-11-29 over 300 first sittings: 16% opened on a card, a
* question with nothing to press («say it aloud or in your head, then
* reveal»). For somebody who arrived a minute ago from a link that is the
* least clear way in: no choices, no sign of what a right answer looks like,
* and a button that gives it away. Cards stay in the sitting, just not first.
*/
function tapFirst(items: PracticeItem[], brandNew: boolean): PracticeItem[] {
if (!brandNew || items.length === 0) return items;
const tapping = (item: PracticeItem) => KIND_BY_ID.get(item.kind)?.answering === "tap";
if (tapping(items[0]!)) return items;
const at = items.findIndex(tapping);
if (at === -1) return items;
return [items[at]!, ...items.slice(0, at), ...items.slice(at + 1)];
}
function interleave(items: PracticeItem[]): PracticeItem[] {
const out: PracticeItem[] = [];
const rest = [...items];
while (rest.length > 0) {
const previous = out[out.length - 1];
const next = rest.findIndex((item) => item.kind !== previous?.kind);
out.push(...rest.splice(next === -1 ? 0 : next, 1));
}
return out;
}
/**
* How far ahead a missed item comes back, within the same sitting.
*
* Three, which is a compromise between two things the evidence pulls apart.
* Rawson & Dunlosky (2011) find the durable gain comes from retrieving a thing
* CORRECTLY more than once, spaced — not from being shown the answer and
* moving on — and the cheapest place to get the first correct retrieval is
* before the learner closes the page. But immediately re-asking the item you
* just revealed tests short-term memory and nothing else, so there has to be
* something in between. Three items is roughly a minute here: far enough that
* the answer is not still on screen, near enough that the session does not end
* first.
*
* It is a judgement, not a finding, and it is written down as one. The
* literature gives the direction and does not give the number.
*/
export const RELEARN_GAP = 3;
/**
* Put a missed item back into the queue, once.
*
* WHAT THIS FIXES. A session used to reveal the answer and move on, which
* makes the whole sitting a test with feedback and never a second chance to
* produce the thing. Butler & Roediger (2008) is the sharper version of the
* problem for the multiple-choice items in particular: choosing a wrong option
* can leave the learner with the wrong option, and feedback is what turns a
* test that can teach errors into one that corrects them. Feedback plus a
* second attempt is strictly more than feedback.
*
* ONCE PER ITEM, and `asked` is what makes that true rather than nearly true.
*
* The first version guarded on "is it already in the queue", which reads
* correctly and is wrong: by the time a requeued item is answered again it has
* left the queue to become the current question, so missing it a second time
* put it back a second time. Found by driving a whole session wrong on
* purpose — eight questions became thirteen and would have kept going. An
* unbounded sitting punishes exactly the learner who is finding it hard, which
* is the opposite of the intention.
*
* So the rule is stated on what actually decides it: an item the learner has
* already answered once in this sitting is on its second attempt, and a second
* attempt is the last. The worst case is a session of twice the size, which is
* bounded and survivable.
*
* Pure: it takes the queue and returns the queue. The page holds the position;
* this decides the order.
*/
export function requeue({
remaining,
item,
asked = [],
gap = RELEARN_GAP,
}: {
/** The items still to be asked, in order, NOT including the current one. */
remaining: readonly PracticeItem[];
/** The one just answered wrong. */
item: PracticeItem;
/** Ids already answered in this sitting, BEFORE the answer being recorded. */
asked?: readonly string[];
gap?: number;
}): PracticeItem[] {
// Second attempt — it has had its extra go.
if (asked.includes(item.id)) return [...remaining];
// Belt to those braces: a duplicate already waiting is the same defect seen
// from the queue's side.
if (remaining.some((queued) => queued.id === item.id)) return [...remaining];
const at = Math.min(gap, remaining.length);
return [...remaining.slice(0, at), item, ...remaining.slice(at)];
}
/**
* Where a sitting stands, with a total that does not move.
*
* WHAT THIS FIXES. The counter read "1/8", then "2/9", then "4/10": a missed
* question is put back into the queue (`requeue`), and the screen counted the
* queue. So the finish line moved away every time the learner got something
* wrong — shown, again, to exactly the person finding it hard — and nobody
* could tell how long the sitting they had started actually was.
*
* The PLAN is the distinct questions in the queue; a requeued miss is the same
* question a second time and does not add to it. So:
*
* total the questions planned — fixed for the whole sitting
* n which of them the learner is on (a second attempt keeps the
* number of the last new question reached)
* done how many of them have had their first answer — the bar
* repeats second attempts still to come, the current one included; shown
* beside the counter as its own small figure, never added to it
*
* Pure, and read from the queue alone, so a resumed sitting (`resume.ts`
* stores exactly these ids) says the same thing it said before it was left.
*/
export function sittingProgress(
ids: readonly string[],
at: number,
): { n: number; done: number; total: number; repeats: number } {
const total = new Set(ids).size;
const here = Math.max(0, Math.min(at, ids.length));
const before = new Set(ids.slice(0, here));
const reached = new Set(ids.slice(0, here + 1));
// An id whose earlier copy has been passed is a second attempt.
let repeats = 0;
const seen = new Set(before);
for (const id of ids.slice(here)) {
if (seen.has(id)) repeats++;
seen.add(id);
}
return { n: Math.max(1, Math.min(reached.size, total)), done: before.size, total, repeats };
}
/**
* What to say at the end, without inventing a score.
*
* Counts of what happened, which are true, and nothing derived from them. No
* percentage, because eight items cannot support one; no streak, because §8
* forbids measuring consumption; no "level", because the product's own metric
* is how much of an unfamiliar speaker you understand and this is not that.
*
* PER QUESTION, NOT PER ANSWER. A missed question comes back for a second
* attempt (`requeue`), so one question can leave two outcomes. Counted per
* answer, a sitting where seven questions were each missed twice said
* "15 asked, 14 coming back" — twice the real work, shown to exactly the
* learner who was struggling — and "first time" counted a right answer on the
* second attempt. So: `asked` is distinct questions, `right` is questions whose
* FIRST answer was right, `again` is questions missed at least once.
*/
export function summarise(outcomes: readonly { id: string; outcome: string }[]): {
asked: number;
right: number;
/** Items the learner asked to see again — a choice, not a failure. */
again: number;
} {
const first = new Map<string, string>();
const missed = new Set<string>();
for (const { id, outcome } of outcomes) {
if (!first.has(id)) first.set(id, outcome);
if (outcome === "wrong") missed.add(id);
}
return {
asked: first.size,
right: [...first.values()].filter((outcome) => outcome === "right").length,
again: missed.size,
};
}