summaryrefslogtreecommitdiff
path: root/web/test/line
diff options
context:
space:
mode:
authorJoel Klinghed <the_jk@spawned.biz>2026-11-16 22:19:39 +0100
committerJoel Klinghed <the_jk@spawned.biz>2026-11-16 22:19:39 +0100
commit94e2850fb73005f3fb30af8489905e5cdfb6fac5 (patch)
tree1aea8e7e6683af770f0c57c0fb654003778c9f16 /web/test/line
parent4f50f2008f4d7c2a635f7f26861fcfc7f7504423 (diff)
Phase 4: cards and decks (M4)
Full card play in the browser: ability-line rendering, monster ability decks, the full modifier-deck (AMD) suite, and the loot deck — all server commands, faithful to the reference flows and layout. Web (Svelte 5): - Line renderer + in-game translations: $lib/game/line/ renders the reference line_builder output (emphasis, range markers, element styling); gameI18n.ts loads the /i18n/ in-game ability-text tables (the client-side TranslationService equivalent) - Card components: stat cards, monster ability cards (OG + FH styles, rendered lines, element/flying tokens), modifier cards (gfx resolver incl. P<n> perk graphics), loot cards (party-size value rules, owner, enhancements) - Monster ability decks: AbilityCardSlot in each monster row (front of the current card while active in playTurns, else the back with the draw-pile count); AbilityCardsMenu (reveal top cards, draw extra, extra shuffle, activate/inactivate, drag-reorder, remove); card zoom - Modifier decks: ModifierDeckWidget (tap to draw, face-up revealed top card, empty-box class icon for the current character's own deck, discard stack); ModifierDeckHeader (bad omen, corrosive spew, ±1/−2/+0, imbue 1/2, reveal with the Cassandra 8-button cap, save/don't-save revealed cards, removed count, Hail perk, CS sanctuary/party cards, faction icons, bless/curse and the empower/enfeeble counters); ModifierDeckMenu (draw-pile drag-reorder + send-to-bottom/shuffle/remove, discard remove/return-top, removed pile with return, faction grid with gray-out, perks menu with the Frosthaven opt-in); card zoom - Loot deck: LootDeckWidget (player-gated draw, current-character icon, discard stack, hidden when both piles empty); LootCardsMenu (set owner, per-character loot totals, add card, enhance with the reference material/herb/coin splits, special cards 1418/1419, return top/bottom) - Bottom DeckArea: loot deck left; the Character Decks toggle with the reference open-state cycling (oneOpen/allOpen/noOpen per round state; one-deck view for the current character during playTurns); ally deck behind shouldShowAlliesDeck; global deck - Pure helper modules ported from the reference: rules.ts (FH card styling, inactive-for-rule, ally-deck gate, deck resolution), modifierDeck.ts (pile derivations, faction cards), perks.ts (active perk set, card-text tokens, descriptions, add/remove gating), cards/lootCard.ts (values + per-character totals) - App wiring: campaign data loaded on currentCampaign change (guarded against out-of-order fetches); ability/AMD/loot menus and zooms driven by live-derived state so open menus track pile changes; Escape closes every dialog Server: - /i18n/ static mount: the in-game ability-text translation files the card renderer resolves (the reference TranslationService data) - Loot deck JSON gains pools (pool card ids per pool — the client derives card gfx from pool key + index and reads the enhancements map; ids only, since pool cards are the same live instances that mutate in the piles) - Modifier deck JSON gains removables (the counter totals the header reads) plus load-time round-trip for saves written before the field existed Docs: - PLAN.md: Phase 3 and Phase 4 marked complete (corrected the 'character ability decks' mislabel — ability decks are monster-only), progress log entries for M3 and M4 svelte-check 0 errors; web tests 177/177; build OK; dart analyze 0 errors; dart test 592/592; scripts/ci.sh green.
Diffstat (limited to 'web/test/line')
-rw-r--r--web/test/line/frosthavenConverter.test.ts156
-rw-r--r--web/test/line/lineParser.test.ts169
-rw-r--r--web/test/line/statApplier.test.ts100
-rw-r--r--web/test/line/statCalculator.test.ts41
4 files changed, 466 insertions, 0 deletions
diff --git a/web/test/line/frosthavenConverter.test.ts b/web/test/line/frosthavenConverter.test.ts
new file mode 100644
index 0000000..89101b3
--- /dev/null
+++ b/web/test/line/frosthavenConverter.test.ts
@@ -0,0 +1,156 @@
+import { describe, it, expect } from 'vitest';
+import {
+ expandEmbeddedNewlines,
+ convertLinesToFH,
+ shouldOverflow
+} from '$lib/game/line/frosthavenConverter';
+
+const conv = (lines: string[], applyStats = false) =>
+ convertLinesToFH(lines, applyStats);
+
+describe('expandEmbeddedNewlines', () => {
+ it('passes through lines without a newline', () =>
+ expect(expandEmbeddedNewlines(['Move 3'])).toEqual(['Move 3']));
+ it('splits on \\n', () =>
+ expect(expandEmbeddedNewlines(['a\nb'])).toEqual(['a', 'b']));
+ it('propagates a ^ prefix to continuation lines', () =>
+ expect(expandEmbeddedNewlines(['^a\nb'])).toEqual(['^a', '^b']));
+ it('propagates a ^^ prefix', () =>
+ expect(expandEmbeddedNewlines(['^^a\nb'])).toEqual(['^^a', '^^b']));
+});
+
+describe('convertLinesToFH — keyword replacements', () => {
+ it('"Affect" → "%target%"', () =>
+ expect(conv(['Affect 2'])).toContain('%target% 2'));
+ it('"damage" → "%damage%"', () =>
+ expect(conv(['Deal damage here'])[0]).toContain('%damage%'));
+ it('"damaged" is not doubled', () =>
+ expect(conv(['damaged item'])[0]).toBe('damaged item'));
+ it('"Target" → "%target%"', () => expect(conv(['Target 2'])[0]).toBe('%target% 2'));
+ it('Affect pipeline leaves no "Affect"', () => {
+ const result = conv(['Affect all', 'Affect']);
+ for (const line of result) expect(line).not.toContain('Affect');
+ expect(result[0]).toContain('%target%');
+ });
+ it('collapses "% " to "%"', () => expect(conv(['50% health'])[0]).toBe('50%health'));
+ it('preserves plain lines', () => expect(conv(['Move 3'])).toContain('Move 3'));
+});
+
+describe('convertLinesToFH — applyStats flag', () => {
+ it('applyStats=false collapses " + "', () => expect(conv(['3 + 1'])[0]).toBe('3+1'));
+ it('applyStats=false collapses " - "', () => expect(conv(['3 - 1'])[0]).toBe('3-1'));
+ it('applyStats=true preserves " + "', () =>
+ expect(conv(['3 + 1'], true)[0]).toBe('3 + 1'));
+ it('applyStats=true preserves " - "', () =>
+ expect(conv(['3 - 1'], true)[0]).toBe('3 - 1'));
+});
+
+describe('convertLinesToFH — [newLine]', () => {
+ it('converts to an empty string', () => expect(conv(['text', '[newLine]'])).toContain(''));
+});
+
+describe('convertLinesToFH — * lines', () => {
+ it('* line passes through', () =>
+ expect(conv(['*Move 3', '^%poison%']).some((l) => l.startsWith('*'))).toBe(true));
+ it('* after a real subline adds [subLineEnd]', () =>
+ expect(conv(['Move 3', '^%poison%', '*Attack'])).toContain('[subLineEnd]'));
+ it('no trailing [subLineEnd] after a leading *', () =>
+ expect(conv(['*Move 3']).at(-1)).not.toBe('[subLineEnd]'));
+});
+
+describe('convertLinesToFH — subline markers', () => {
+ it('^%token% after a normal line inserts ![subLineStart]', () =>
+ expect(conv(['Move 3', '^%poison%'])).toContain('![subLineStart]'));
+ it('trailing [subLineEnd] when open at end', () =>
+ expect(conv(['Move 3', '^%poison%']).at(-1)).toBe('[subLineEnd]'));
+ it('^ line matching the subline pattern gets a ! prefix', () =>
+ expect(conv(['Move 3', '^%poison%']).some((l) => l.startsWith('!^'))).toBe(true));
+ it('^%target% after a normal line triggers a subline', () =>
+ expect(conv(['Attack 3', '^%target% 2'])).toContain('![subLineStart]'));
+ it('^Self after a normal line triggers a subline', () =>
+ expect(conv(['Heal 2', '^Self'])).toContain('![subLineStart]'));
+ it('^All attacks does NOT trigger a subline', () =>
+ expect(conv(['Move 3', '^All attacks on you'])).not.toContain('![subLineStart]'));
+ it('second ^ inside a subline is also prefixed', () => {
+ const exclam = conv(['Move 3', '^%poison%', '^%wound%']).filter(
+ (l) => l.startsWith('!') && l.includes('%')
+ );
+ expect(exclam.length).toBeGreaterThanOrEqual(2);
+ });
+ it('empty list returns empty list', () => expect(conv([])).toEqual([]));
+ it('single non-special line has no markers', () => {
+ const result = conv(['Move 3']);
+ expect(result).not.toContain('[subLineStart]');
+ expect(result).not.toContain('![subLineStart]');
+ expect(result).not.toContain('[subLineEnd]');
+ });
+});
+
+describe('convertLinesToFH — element use / conditional', () => {
+ it('[r] before a %use line does not crash', () =>
+ expect(conv(['Attack 2', '[r]', '%use%', '^%poison%', '[/r]'])).not.toEqual([]));
+ it('[/r] resets the conditional flag', () =>
+ expect(
+ conv(['[r]', '%use%', '%fire%', '[/r]', 'Move 3', '^%poison%'])
+ ).toContain('![subLineStart]'));
+});
+
+describe('convertLinesToFH — advanced subline patterns', () => {
+ it('^Normal starts a subline', () =>
+ expect(conv(['Attack 3', '^Normal attack'])).toContain('![subLineStart]'));
+ it('^all starts a subline', () =>
+ expect(conv(['Attack 3', '^all enemies'])).toContain('![subLineStart]'));
+ it('^All (not "attacks" / "targets") starts a subline', () =>
+ expect(conv(['Attack 3', '^All adjacent enemies'])).toContain('![subLineStart]'));
+ it('^All targets does not start a subline', () =>
+ expect(conv(['Move 3', '^All targets suffer'])).not.toContain('![subLineStart]'));
+ it('isSubLine clears after a non-subline ^ line', () => {
+ const result = conv(['Move 3', '^All attacks on you', 'Attack 2']);
+ expect(result).not.toContain('![subLineStart]');
+ expect(result).not.toContain('[subLineEnd]');
+ });
+ it('a new main line closes an open subline', () =>
+ expect(conv(['Move 3', '^%poison%', 'Attack 2'])).toContain('[subLineEnd]'));
+});
+
+describe('shouldOverflow', () => {
+ const overflowTokens = [
+ 'pierce',
+ 'brittle',
+ 'curse',
+ 'enfeeble',
+ 'bless',
+ 'invisible',
+ 'strengthen',
+ 'bane',
+ 'push',
+ 'pull',
+ 'poison',
+ 'wound',
+ 'infect',
+ 'chill',
+ 'disarm',
+ 'immobilize',
+ 'stun',
+ 'impair',
+ 'safeguard',
+ 'muddle'
+ ];
+ it('returns true for known FH condition tokens', () => {
+ for (const token of overflowTokens)
+ expect(shouldOverflow(true, token)).toBe(true);
+ });
+ it('returns false for non-FH style', () => {
+ for (const token of overflowTokens)
+ expect(shouldOverflow(false, token)).toBe(false);
+ });
+ it('returns false for non-overflow tokens', () => {
+ expect(shouldOverflow(true, 'attack')).toBe(false);
+ expect(shouldOverflow(true, 'move')).toBe(false);
+ expect(shouldOverflow(true, '')).toBe(false);
+ });
+ it('matches tokens containing poison / wound', () => {
+ expect(shouldOverflow(true, 'acid-poison')).toBe(true);
+ expect(shouldOverflow(true, 'wound-infect')).toBe(true);
+ });
+});
diff --git a/web/test/line/lineParser.test.ts b/web/test/line/lineParser.test.ts
new file mode 100644
index 0000000..ad95240
--- /dev/null
+++ b/web/test/line/lineParser.test.ts
@@ -0,0 +1,169 @@
+import { describe, it, expect } from 'vitest';
+import { parseLines } from '$lib/game/line/lineParser';
+import type {
+ ColumnNode,
+ LineBuildOptions,
+ Node,
+ RowNode,
+ SubLineNode
+} from '$lib/game/line/types';
+import type { StatMonster } from '$lib/game/line/statApplier';
+
+function opts(partial: Partial<LineBuildOptions> = {}): LineBuildOptions {
+ return {
+ left: false,
+ applyStats: false,
+ applyAll: false,
+ align: 'center',
+ frosthavenStyle: false,
+ scale: 1,
+ monster: null,
+ ...partial
+ };
+}
+
+/** The single top-level row of a one-line card. */
+function topRow(col: ColumnNode): RowNode {
+ const first = col.children[0];
+ if (!first || first.kind !== 'row')
+ throw new Error(`expected a top row, got ${first?.kind}`);
+ return first;
+}
+
+function texts(node: Node): string[] {
+ if (node.kind === 'text') return [node.text];
+ if ('children' in node) return node.children.flatMap(texts);
+ return [];
+}
+
+const zealot = (standeeTypes: number[] = [1]): StatMonster => ({
+ level: {
+ normal: { attack: 2, move: 2 },
+ elite: { attack: 3, move: 2 }
+ },
+ standeeTypes: standeeTypes as never,
+ isActive: false
+});
+
+describe('parseLines — plain text', () => {
+ it('a single line becomes one row of one text segment', () => {
+ const col = parseLines(['Move 3'], opts());
+ expect(col.children).toHaveLength(1);
+ const row = topRow(col);
+ expect(row.children.map((n) => n.kind)).toEqual(['text']);
+ expect((row.children[0] as { text: string }).text).toBe('Move 3');
+ });
+ it('multiple lines become multiple rows', () => {
+ const col = parseLines(['Move 3', 'Attack 2'], opts());
+ expect(col.children.map((n) => n.kind)).toEqual(['row', 'row']);
+ });
+});
+
+describe('parseLines — tokens', () => {
+ it('GH style shows the translated label beside the icon', () => {
+ const row = topRow(parseLines(['%attack% 2'], opts()));
+ expect(row.children.map((n) => n.kind)).toEqual(['text', 'token', 'text']);
+ expect((row.children[0] as { text: string }).text).toBe('Attack');
+ expect((row.children[1] as { token: string }).token).toBe('attack');
+ });
+ it('FH style renders the token icon-only (no label)', () => {
+ const row = topRow(parseLines(['%attack% 2'], opts({ frosthavenStyle: true })));
+ expect(row.children.map((n) => n.kind)).toEqual(['token', 'text']);
+ });
+ it('a standalone token yields just the icon', () => {
+ const row = topRow(parseLines(['%poison%'], opts({ frosthavenStyle: true })));
+ expect(row.children.map((n) => n.kind)).toEqual(['token']);
+ expect((row.children[0] as { overflow: boolean }).overflow).toBe(true);
+ });
+});
+
+describe('parseLines — sub-lines (FH)', () => {
+ it('boxes a ^%token% sub-line to the right of the main line', () => {
+ const col = parseLines(['Move 3', '^%poison%'], opts({ frosthavenStyle: true }));
+ const row = topRow(col);
+ expect(row.children.map((n) => n.kind)).toEqual(['row', 'subline']);
+ const sub = row.children[1] as SubLineNode;
+ expect(sub.children.map((n) => n.kind)).toEqual(['row']);
+ expect((sub.children[0] as RowNode).children.map((n) => n.kind)).toEqual([
+ 'token'
+ ]);
+ });
+ it('consecutive ^ sub-line tokens share one row (no line break)', () => {
+ const col = parseLines(
+ ['Move 3', '^%poison%', '^%wound%'],
+ opts({ frosthavenStyle: true })
+ );
+ const row = topRow(col);
+ const sub = row.children[1] as SubLineNode;
+ expect(sub.children.map((n) => n.kind)).toEqual(['row']);
+ expect((sub.children[0] as RowNode).children.map((n) => n.kind)).toEqual([
+ 'token',
+ 'token'
+ ]);
+ });
+});
+
+describe('parseLines — element images & dividers', () => {
+ it('a ¤ element line becomes an image node', () => {
+ const col = parseLines(['¤fire'], opts({ frosthavenStyle: true }));
+ expect(col.children.map((n) => n.kind)).toEqual(['image']);
+ expect((col.children[0] as { element: boolean }).element).toBe(true);
+ });
+ it('a *.... line becomes a divider in FH style', () => {
+ const col = parseLines(['*....'], opts({ frosthavenStyle: true }));
+ expect(col.children.map((n) => n.kind)).toEqual(['divider']);
+ expect((col.children[0] as { thin: boolean }).thin).toBe(false);
+ });
+});
+
+describe('parseLines — columns', () => {
+ it('[c]…[/c] groups its lines into a column node', () => {
+ const col = parseLines(['[c]', 'A', 'B', '[/c]'], opts());
+ expect(col.children.map((n) => n.kind)).toEqual(['column']);
+ const inner = col.children[0] as { children: Node[] };
+ expect(inner.children.map((n) => n.kind)).toEqual(['row', 'row']);
+ expect(texts(inner.children[0] as Node)).toEqual(['A']);
+ });
+});
+
+describe('parseLines — element use / conditional', () => {
+ it('an element+%use% block in a row becomes a conditional box', () => {
+ const col = parseLines(
+ ['[r]', '%fire%%use%', '[/r]'],
+ opts({ frosthavenStyle: true })
+ );
+ expect(col.children.map((n) => n.kind)).toEqual(['conditional']);
+ const cond = col.children[0] as {
+ elementUse: boolean;
+ children: Node[];
+ };
+ expect(cond.elementUse).toBe(true);
+ // The [r] group wraps its inner line in a row (faithful to the
+ // reference's Row(children: widgetsInRow)).
+ const group = cond.children[0] as RowNode;
+ const inner = group.children[0] as RowNode;
+ expect(inner.children.map((n) => n.kind)).toEqual(['elementUse', 'text']);
+ });
+});
+
+describe('parseLines — elite stat split', () => {
+ it('splits %attack% into a normal and an elite row', () => {
+ const col = parseLines(
+ ['%attack% +0'],
+ opts({ applyStats: true, applyAll: false, monster: zealot([0, 1]) })
+ );
+ const all = texts(col).join(' ');
+ // normal (2) and elite (3) values both present.
+ expect(all).toContain('2');
+ expect(all).toContain('3');
+ });
+ it('a lone elite standee shows only the elite value', () => {
+ const col = parseLines(
+ ['%attack% +0'],
+ opts({ applyStats: true, applyAll: false, monster: zealot([1]) })
+ );
+ const row = topRow(col);
+ const styles = row.children.map((n) => (n as { style?: string }).style ?? '');
+ expect(styles.some((s) => s.startsWith('elite'))).toBe(true);
+ });
+});
diff --git a/web/test/line/statApplier.test.ts b/web/test/line/statApplier.test.ts
new file mode 100644
index 0000000..087a6f2
--- /dev/null
+++ b/web/test/line/statApplier.test.ts
@@ -0,0 +1,100 @@
+import { describe, it, expect } from 'vitest';
+import {
+ applyMonsterStats,
+ type MonsterType,
+ type StatMonster
+} from '$lib/game/line/statApplier';
+
+// Zealot level 1 (the reference test monster): normal attack=2 move=2,
+// elite attack=3 move=2, no range, no attributes.
+function zealot(standeeTypes: MonsterType[] = []): StatMonster {
+ return {
+ level: {
+ normal: { health: 4, move: 2, attack: 2 },
+ elite: { health: 7, move: 2, attack: 3 }
+ },
+ standeeTypes,
+ isActive: false
+ };
+}
+
+// Black Sludge level 1: both normal and elite carry "%shield% 1".
+function blackSludge(standeeTypes: MonsterType[] = []): StatMonster {
+ return {
+ level: {
+ normal: { health: 4, move: 1, attack: 2, attributes: ['%shield% 1'] },
+ elite: { health: 8, move: 1, attack: 2, attributes: ['%shield% 1'] }
+ },
+ standeeTypes,
+ isActive: false
+ };
+}
+
+const elite = (s: string[]) => s.find((x) => x.startsWith('!'));
+
+describe('applyMonsterStats — plain text', () => {
+ it('returns a line with no formula unchanged', () =>
+ expect(applyMonsterStats('Move 3', '', zealot(), false)).toEqual(['Move 3']));
+ it('returns a bare token unchanged', () =>
+ expect(applyMonsterStats('%attack%', '', zealot(), false)).toEqual(['%attack%']));
+ it('treats a single digit as plain text', () =>
+ expect(applyMonsterStats('3', '', zealot(), false)).toEqual(['3']));
+});
+
+describe('applyMonsterStats — no standees, forceShowAll=false', () => {
+ it('leaves "%attack% +0" unchanged (no standees, no force)', () =>
+ expect(applyMonsterStats('%attack% +0', '', zealot(), false)).toEqual(['%attack% +0']));
+ it('leaves "%move% +1" unchanged', () =>
+ expect(applyMonsterStats('%move% +1', '', zealot(), false)).toEqual(['%move% +1']));
+});
+
+describe('applyMonsterStats — forceShowAll attack', () => {
+ it('splits "%attack% +0" into more than one result', () =>
+ expect(applyMonsterStats('%attack% +0', '', zealot(), true).length).toBeGreaterThan(1));
+ it('normal result holds the normal attack value', () =>
+ expect(applyMonsterStats('%attack% +0', '', zealot(), true)[0]).toContain('2'));
+ it('elite result holds the elite attack value', () =>
+ expect(elite(applyMonsterStats('%attack% +0', '', zealot(), true))).toContain('3'));
+ it('"%attack% +1" adds 1 to both', () => {
+ const r = applyMonsterStats('%attack% +1', '', zealot(), true);
+ expect(r[0]).toContain('3');
+ expect(elite(r)).toContain('4');
+ });
+ it('"%attack% -1" subtracts 1 from both', () => {
+ const r = applyMonsterStats('%attack% -1', '', zealot(), true);
+ expect(r[0]).toContain('1');
+ expect(elite(r)).toContain('2');
+ });
+});
+
+describe('applyMonsterStats — forceShowAll move', () => {
+ it('"%move% +0" yields the move value', () =>
+ expect(applyMonsterStats('%move% +0', '', zealot(), true)[0]).toContain('2'));
+ it('"%move% +2" yields move + 2', () =>
+ expect(applyMonsterStats('%move% +2', '', zealot(), true)[0]).toContain('4'));
+});
+
+describe('applyMonsterStats — with standees', () => {
+ it('a normal standee shows only the normal stat', () => {
+ const r = applyMonsterStats('%attack% +0', '', zealot([0]), false);
+ expect(r[0]).toContain('2');
+ expect(r.every((s) => !s.includes('3'))).toBe(true);
+ });
+ it('an elite standee splits into both stats', () => {
+ const r = applyMonsterStats('%attack% +0', '', zealot([1]), false);
+ expect(r.length).toBeGreaterThan(1);
+ expect(r.some((s) => s.includes('3'))).toBe(true);
+ });
+});
+
+describe('applyMonsterStats — standalone formula', () => {
+ it('evaluates a C+L formula (level 1, no characters → 3)', () =>
+ expect(applyMonsterStats('C+L health', '', zealot(), false)[0]).toContain('3'));
+ it('evaluates a 3+ digit plain number in place', () =>
+ expect(applyMonsterStats('100 damage', '', zealot(), false)[0]).toContain('100'));
+});
+
+describe('applyMonsterStats — shield token', () => {
+ it('yields the shield value from the attribute', () =>
+ expect(applyMonsterStats('%shield% +0', '', blackSludge(), true)[0]).toContain('1'));
+});
diff --git a/web/test/line/statCalculator.test.ts b/web/test/line/statCalculator.test.ts
new file mode 100644
index 0000000..022d8df
--- /dev/null
+++ b/web/test/line/statCalculator.test.ts
@@ -0,0 +1,41 @@
+import { describe, it, expect } from 'vitest';
+import { evalFormula, calculateFormula } from '$lib/game/line/statCalculator';
+
+describe('evalFormula', () => {
+ it('parses a plain integer', () => expect(evalFormula('5')).toBe(5));
+ it('parses addition', () => expect(evalFormula('3+2')).toBe(5));
+ it('parses subtraction', () => expect(evalFormula('7-3')).toBe(4));
+ it('multiplies with *', () => expect(evalFormula('3*4')).toBe(12));
+ it('multiplies with x', () => expect(evalFormula('3x4')).toBe(12));
+ it('divides with / (ceil)', () => expect(evalFormula('7/2')).toBe(4));
+ it('divides with d (floor)', () => expect(evalFormula('7d2')).toBe(3));
+ it('honours parentheses', () => expect(evalFormula('(2+3)*4')).toBe(20));
+ it('handles unary minus', () => expect(evalFormula('0-5')).toBe(-5));
+ it('returns null for non-numeric', () => expect(evalFormula('abc')).toBeNull());
+ it('returns null for trailing junk', () =>
+ expect(evalFormula('5extra')).toBeNull());
+ it('condition less-than true → 1', () => expect(evalFormula('2<3')).toBe(1));
+ it('condition less-than false → 0', () => expect(evalFormula('3<2')).toBe(0));
+ it('condition greater-than true → 1', () =>
+ expect(evalFormula('5>4')).toBe(1));
+ it('condition greater-than false → 0', () =>
+ expect(evalFormula('1>2')).toBe(0));
+ it('condition equals true → 1', () => expect(evalFormula('4=4')).toBe(1));
+ it('condition equals false → 0', () => expect(evalFormula('4=5')).toBe(0));
+ it('exact ceil division', () => expect(evalFormula('6/2')).toBe(3));
+ it('exact floor division', () => expect(evalFormula('6d2')).toBe(3));
+ it('precedence: * before +', () => expect(evalFormula('2+3*4')).toBe(14));
+});
+
+describe('calculateFormula', () => {
+ it('substitutes C, clamped to a minimum of 2', () =>
+ expect(calculateFormula('C')).toBe(2));
+ it('substitutes C with the real count when ≥ 2', () =>
+ expect(calculateFormula('C', { characterCount: 3 })).toBe(3));
+ it('substitutes L with the level', () =>
+ expect(calculateFormula('L', { level: 4 })).toBe(4));
+ it('combines C and L', () =>
+ expect(calculateFormula('C+L', { level: 3 })).toBe(5));
+ it('returns null for an invalid formula', () =>
+ expect(calculateFormula('??')).toBeNull());
+});