@adriansteffan/reactive 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { W as P, b as x, E } from "./mod-DRCLdWzq.js";
1
+ import { W as P, b as x, E } from "./mod-BPE3lXMa.js";
2
2
  function m(w) {
3
3
  const e = w.split("/").filter((t) => t !== "."), r = [];
4
4
  return e.forEach((t) => {
@@ -1,4 +1,4 @@
1
- import { W as e } from "./mod-DRCLdWzq.js";
1
+ import { W as e } from "./mod-BPE3lXMa.js";
2
2
  class s extends e {
3
3
  async enable() {
4
4
  console.log("Immersive mode is only available on Android");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adriansteffan/reactive",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "dev": "vite",
@@ -11,7 +11,7 @@ import type { CSSProperties } from 'react';
11
11
  import { BaseComponentProps, shuffle } from '../mod';
12
12
  import { registerSimulation } from '../utils/simulation';
13
13
  import { registerFlattener } from '../utils/upload';
14
- import { uniform } from '../utils/distributions';
14
+ import { simulateDDMTrial, mapDDMChoice } from '../utils/ddm';
15
15
 
16
16
  registerFlattener('RandomDotKinematogram', 'rdk');
17
17
 
@@ -48,39 +48,49 @@ const RDK_DEFAULTS = {
48
48
  };
49
49
 
50
50
  registerSimulation('RandomDotKinematogram', (trialProps, _experimentState, simulators, participant) => {
51
- const result = simulators.respond(trialProps, participant);
52
- const fixation = trialProps.fixationTime ?? RDK_DEFAULTS.fixationTime;
53
- const trialDuration = trialProps.duration ?? RDK_DEFAULTS.duration;
54
- const responseEndsTrial = trialProps.responseEndsTrial ?? RDK_DEFAULTS.responseEndsTrial;
55
- const rt = result.value.rt;
56
- // If the participant responded and responseEndsTrial is true, the trial ends at the response.
57
- // Otherwise, the full duration plays out.
51
+ const merged: any = { ...RDK_DEFAULTS, ...trialProps };
52
+ const result = simulators.respond(merged, participant);
53
+ const { rt, response } = result.value;
54
+
55
+ const fixation = merged.fixationTime ?? RDK_DEFAULTS.fixationTime;
56
+ const trialDuration = merged.duration ?? RDK_DEFAULTS.duration;
57
+ const responseEndsTrial = merged.responseEndsTrial ?? RDK_DEFAULTS.responseEndsTrial;
58
58
  const elapsed = (responseEndsTrial && rt != null) ? rt : trialDuration;
59
+
60
+ const correctKeys = Array.isArray(merged.correctResponse)
61
+ ? merged.correctResponse.map((c: string) => c.toLowerCase())
62
+ : merged.correctResponse ? [merged.correctResponse.toLowerCase()] : null;
63
+
59
64
  return {
60
- responseData: result.value,
65
+ responseData: {
66
+ ...merged,
67
+ rt,
68
+ response,
69
+ correct: response && correctKeys ? correctKeys.includes(response.toLowerCase()) : null,
70
+ framesDisplayed: 0,
71
+ measuredRefreshRate: null,
72
+ },
61
73
  participantState: result.participantState,
62
74
  duration: fixation + elapsed,
63
75
  };
64
76
  }, {
65
77
  respond: (trialProps: any, participant: any) => {
66
- const merged = { ...RDK_DEFAULTS, ...trialProps };
67
- const rawRt = uniform(200, 800);
68
- const maxRt = merged.duration ?? RDK_DEFAULTS.duration;
69
- const responded = merged.validKeys.length > 0 && rawRt <= maxRt;
70
- const key = responded ? merged.validKeys[Math.floor(uniform(0, merged.validKeys.length))] : null;
71
- const rt = responded ? rawRt : null;
72
- const correctKeys = Array.isArray(merged.correctResponse)
73
- ? merged.correctResponse.map((c: string) => c.toLowerCase())
74
- : merged.correctResponse ? [merged.correctResponse.toLowerCase()] : null;
78
+ const ddm = simulateDDMTrial({
79
+ driftRate: 0.00074 * (trialProps.coherence ?? RDK_DEFAULTS.coherence),
80
+ boundaries: 0.0555,
81
+ startingPoint: 0,
82
+ noiseLevel: 0.00316,
83
+ sensoryDelay: { type: 'uniform', min: 150, max: 250 },
84
+ motorDelay: { type: 'uniform', min: 130, max: 210 },
85
+ timeLimit: trialProps.duration ?? RDK_DEFAULTS.duration,
86
+ stimOffset: trialProps.stimulusDuration ?? trialProps.duration ?? RDK_DEFAULTS.duration,
87
+ postStimStrategy: { type: 'continue' },
88
+ });
89
+
90
+ const key = mapDDMChoice(ddm.choice, trialProps.validKeys, trialProps.correctResponse);
91
+
75
92
  return {
76
- value: {
77
- ...merged,
78
- rt,
79
- response: key,
80
- correct: key && correctKeys ? correctKeys.includes(key) : null,
81
- framesDisplayed: 0,
82
- measuredRefreshRate: null,
83
- },
93
+ value: { rt: key ? ddm.rt : null, response: key },
84
94
  participantState: participant,
85
95
  };
86
96
  },
package/src/mod.tsx CHANGED
@@ -8,6 +8,8 @@ export * from './utils/simulation';
8
8
  export { registerFlattener, arrayFlattener } from './utils/upload';
9
9
  export { normal, poisson, uniform, seedDistributions, sobol, halton, sampleParticipants } from './utils/distributions';
10
10
  export type { DimensionSpec, UniformSpec, NormalSpec, PoissonSpec, SamplingMethod } from './utils/distributions';
11
+ export { simulateDDMTrial, mapDDMChoice } from './utils/ddm';
12
+ export type { DDMTrialParams, DDMTrialResult, ParameterDef, NormalDist, UniformDist, BoundaryDef, CollapseDef, PostStimStrategyDef, ContinueStrategy, CollapseStrategy, SnapshotStrategy } from './utils/ddm';
11
13
  export * from './components';
12
14
 
13
15
  export * from 'react-toastify';
@@ -128,7 +128,8 @@ export function getParam<T extends ParamType>(
128
128
  };
129
129
 
130
130
  // First, check for the parameter in the base64-encoded JSON
131
- const encodedJson = new URLSearchParams(window.location.search).get('_b');
131
+ const searchParams = typeof window !== 'undefined' ? new URLSearchParams(window.location.search) : new URLSearchParams();
132
+ const encodedJson = searchParams.get('_b');
132
133
  if (encodedJson) {
133
134
  try {
134
135
  const jsonString = atob(encodedJson);
@@ -144,7 +145,7 @@ export function getParam<T extends ParamType>(
144
145
  }
145
146
 
146
147
  // Next, check for the parameter directly in the URL
147
- const value = new URLSearchParams(window.location.search).get(name);
148
+ const value = searchParams.get(name);
148
149
  if (value === undefined || value === null) {
149
150
  // If no value found, register default value
150
151
  return defaultValue;
@@ -0,0 +1,233 @@
1
+ import { describe, it, expect, beforeEach } from 'vitest';
2
+ import { simulateDDMTrial, mapDDMChoice } from './ddm';
3
+ import { seedDistributions } from './distributions';
4
+
5
+ beforeEach(() => {
6
+ seedDistributions(42);
7
+ });
8
+
9
+ const baseParams = {
10
+ driftRate: 0.003,
11
+ boundaries: 0.1 as const,
12
+ startingPoint: 0,
13
+ noiseLevel: 0.003,
14
+ timeLimit: 2000,
15
+ stimOffset: 2000,
16
+ postStimStrategy: { type: 'continue' as const },
17
+ };
18
+
19
+ describe('simulateDDMTrial', () => {
20
+ it('returns a valid result shape', () => {
21
+ const result = simulateDDMTrial(baseParams);
22
+ expect([0, 1, null]).toContain(result.choice);
23
+ expect(result.rt).toBeGreaterThan(0);
24
+ expect(typeof result.finalEvidence).toBe('number');
25
+ expect(result.isContaminated).toBe(false);
26
+ });
27
+
28
+ it('is reproducible with the same seed', () => {
29
+ seedDistributions(99);
30
+ const a = simulateDDMTrial(baseParams);
31
+ seedDistributions(99);
32
+ const b = simulateDDMTrial(baseParams);
33
+ expect(a).toEqual(b);
34
+ });
35
+
36
+ it('rt includes sensory and motor delays', () => {
37
+ const result = simulateDDMTrial({
38
+ ...baseParams,
39
+ driftRate: 1, // very high drift for instant decision
40
+ sensoryDelay: 100,
41
+ motorDelay: 50,
42
+ });
43
+ expect(result.rt).toBeGreaterThanOrEqual(150);
44
+ });
45
+
46
+ it('clamps sensory and motor delays to >= 0', () => {
47
+ const result = simulateDDMTrial({
48
+ ...baseParams,
49
+ driftRate: 1,
50
+ sensoryDelay: { type: 'normal', mean: -1000, sd: 1 },
51
+ motorDelay: { type: 'normal', mean: -1000, sd: 1 },
52
+ });
53
+ expect(result.rt).toBeGreaterThanOrEqual(0);
54
+ });
55
+
56
+ it('clamps noise level to >= 0', () => {
57
+ // Should not throw even with a negative noise param
58
+ const result = simulateDDMTrial({
59
+ ...baseParams,
60
+ noiseLevel: { type: 'normal', mean: -10, sd: 0.1 },
61
+ });
62
+ expect(result).toBeDefined();
63
+ });
64
+
65
+ it('returns null choice on timeout', () => {
66
+ const result = simulateDDMTrial({
67
+ ...baseParams,
68
+ driftRate: 0,
69
+ noiseLevel: 0, // no noise, no drift — never reaches boundary
70
+ timeLimit: 100,
71
+ });
72
+ expect(result.choice).toBeNull();
73
+ expect(result.rt).toBe(100);
74
+ });
75
+
76
+ it('supports asymmetric boundaries', () => {
77
+ const result = simulateDDMTrial({
78
+ ...baseParams,
79
+ boundaries: [-0.05, 0.2], // lower closer, upper farther
80
+ driftRate: 0,
81
+ noiseLevel: 0.01,
82
+ });
83
+ expect([0, 1, null]).toContain(result.choice);
84
+ });
85
+
86
+ it('contamination returns isContaminated with valid rt', () => {
87
+ const result = simulateDDMTrial({ ...baseParams, contaminationRate: 1.0 });
88
+ expect(result.isContaminated).toBe(true);
89
+ expect(result.rt).toBeGreaterThanOrEqual(0);
90
+ expect(result.rt).toBeLessThanOrEqual(baseParams.timeLimit);
91
+ });
92
+
93
+ it('contamination sets finalEvidence to startingPoint', () => {
94
+ const result = simulateDDMTrial({
95
+ ...baseParams,
96
+ startingPoint: 0.05,
97
+ contaminationRate: 1.0,
98
+ });
99
+ expect(result.isContaminated).toBe(true);
100
+ expect(result.finalEvidence).toBe(0.05);
101
+ });
102
+ });
103
+
104
+ describe('snapshot strategy', () => {
105
+ it('forces choice at stimOffset based on boundary proximity', () => {
106
+ const result = simulateDDMTrial({
107
+ ...baseParams,
108
+ driftRate: 0.01, // positive drift, evidence moves toward upper
109
+ stimOffset: 50,
110
+ postStimStrategy: { type: 'snapshot' },
111
+ });
112
+ expect([0, 1]).toContain(result.choice);
113
+ expect(result.isContaminated).toBe(false);
114
+ });
115
+
116
+ it('rt reflects stimOffset timing, not timeLimit', () => {
117
+ const result = simulateDDMTrial({
118
+ ...baseParams,
119
+ driftRate: 0.0001, // slow drift, won't hit boundary before stimOffset
120
+ noiseLevel: 0.0001,
121
+ sensoryDelay: 0,
122
+ motorDelay: 100,
123
+ stimOffset: 200,
124
+ timeLimit: 5000,
125
+ postStimStrategy: { type: 'snapshot' },
126
+ });
127
+ // rt should be around stimOffset + motorDelay, not timeLimit
128
+ expect(result.rt).toBeLessThan(5000);
129
+ expect(result.rt).toBeGreaterThanOrEqual(200);
130
+ });
131
+ });
132
+
133
+ describe('continue strategy', () => {
134
+ it('defaults to zero drift after stimOffset', () => {
135
+ // With zero drift and no noise after stimOffset, evidence should freeze
136
+ const result = simulateDDMTrial({
137
+ ...baseParams,
138
+ driftRate: 0,
139
+ noiseLevel: 0,
140
+ stimOffset: 10,
141
+ timeLimit: 100,
142
+ postStimStrategy: { type: 'continue' },
143
+ });
144
+ expect(result.choice).toBeNull(); // no drift, no noise — timeout
145
+ });
146
+
147
+ });
148
+
149
+ describe('collapse strategy', () => {
150
+ it('eventually forces a decision', () => {
151
+ const result = simulateDDMTrial({
152
+ ...baseParams,
153
+ driftRate: 0,
154
+ noiseLevel: 0.001,
155
+ stimOffset: 0,
156
+ timeLimit: 10000,
157
+ postStimStrategy: {
158
+ type: 'collapse',
159
+ collapseDef: { rate: 0.001 },
160
+ },
161
+ });
162
+ // Boundaries collapse, must eventually reach evidence
163
+ expect([0, 1]).toContain(result.choice);
164
+ });
165
+
166
+ it('respects collapse delay', () => {
167
+ const fast = simulateDDMTrial({
168
+ ...baseParams,
169
+ driftRate: 0,
170
+ noiseLevel: 0.0001,
171
+ stimOffset: 0,
172
+ timeLimit: 10000,
173
+ postStimStrategy: {
174
+ type: 'collapse',
175
+ collapseDef: { rate: 0.001, delay: 0 },
176
+ },
177
+ });
178
+ const delayed = simulateDDMTrial({
179
+ ...baseParams,
180
+ driftRate: 0,
181
+ noiseLevel: 0.0001,
182
+ stimOffset: 0,
183
+ timeLimit: 10000,
184
+ postStimStrategy: {
185
+ type: 'collapse',
186
+ collapseDef: { rate: 0.001, delay: 500 },
187
+ },
188
+ });
189
+ // Delayed collapse should take longer (or at least not be faster)
190
+ expect(delayed.rt).toBeGreaterThanOrEqual(fast.rt);
191
+ });
192
+ });
193
+
194
+ describe('mapDDMChoice', () => {
195
+ it('returns null for null choice', () => {
196
+ expect(mapDDMChoice(null, ['a', 'b'])).toBeNull();
197
+ });
198
+
199
+ it('returns null for empty validKeys', () => {
200
+ expect(mapDDMChoice(1, [])).toBeNull();
201
+ });
202
+
203
+ it('maps choice 1 to correct key', () => {
204
+ const key = mapDDMChoice(1, ['a', 'b'], 'a');
205
+ expect(key).toBe('a');
206
+ });
207
+
208
+ it('maps choice 0 to incorrect key', () => {
209
+ const key = mapDDMChoice(0, ['a', 'b'], 'a');
210
+ expect(key).toBe('b');
211
+ });
212
+
213
+ it('handles case-insensitive correctResponse', () => {
214
+ const key = mapDDMChoice(1, ['A', 'b'], 'a');
215
+ expect(key?.toLowerCase()).toBe('a');
216
+ });
217
+
218
+ it('handles array correctResponse', () => {
219
+ const key = mapDDMChoice(1, ['a', 'b', 'c'], ['a', 'b']);
220
+ expect(['a', 'b']).toContain(key);
221
+ });
222
+
223
+ it('returns random key when no correctResponse', () => {
224
+ const key = mapDDMChoice(1, ['a', 'b']);
225
+ expect(['a', 'b']).toContain(key);
226
+ });
227
+
228
+ it('falls back to any key when no matching keys for choice', () => {
229
+ // choice 0 (incorrect), but all keys are correct — no wrong keys available
230
+ const key = mapDDMChoice(0, ['a'], 'a');
231
+ expect(key).toBe('a');
232
+ });
233
+ });
@@ -0,0 +1,230 @@
1
+ import { normal, uniform } from './distributions';
2
+
3
+ // --- Distribution & Parameter Types ---
4
+
5
+ export type NormalDist = { type: 'normal'; mean: number; sd: number };
6
+ export type UniformDist = { type: 'uniform'; min: number; max: number };
7
+ export type ParameterDef = number | NormalDist | UniformDist;
8
+
9
+ export type BoundaryDef =
10
+ | number // Symmetric: upper is +b, lower is -b
11
+ | [number, number]; // Asymmetric: [lowerBound, upperBound]
12
+
13
+ export type CollapseDef = {
14
+ rate: number; // Speed at which boundaries shrink per ms
15
+ delay?: number; // Pause in ms (from phase start) before collapse begins
16
+ };
17
+
18
+ // --- Post-Stimulus Strategy Types ---
19
+
20
+ export type ContinueStrategy = {
21
+ type: 'continue';
22
+ residualDrift?: number; // Drift rate after stimOffset (Default: 0)
23
+ noiseMultiplier?: number; // Multiplier for noiseLevel (Default: 1)
24
+ };
25
+
26
+ export type CollapseStrategy = {
27
+ type: 'collapse';
28
+ collapseDef: CollapseDef; // Takes over boundary dynamics after stimOffset
29
+ };
30
+
31
+ export type SnapshotStrategy = {
32
+ type: 'snapshot'; // Immediate forced choice at stimOffset
33
+ };
34
+
35
+ export type PostStimStrategyDef = ContinueStrategy | CollapseStrategy | SnapshotStrategy;
36
+
37
+ // --- Main Configuration ---
38
+
39
+ export interface DDMTrialParams {
40
+ // Core cognitive parameters (support distributions for inter-trial variability)
41
+ driftRate: ParameterDef;
42
+ boundaries: BoundaryDef;
43
+ startingPoint: ParameterDef;
44
+ noiseLevel: ParameterDef;
45
+
46
+ // Timing parameters
47
+ sensoryDelay?: ParameterDef; // Dead time before accumulation (ms)
48
+ motorDelay?: ParameterDef; // Dead time for physical execution (ms)
49
+ timeLimit: number; // Maximum allowed trial duration (ms)
50
+ stimOffset: number; // Timestamp when stimulus vanishes (ms)
51
+ dt?: number; // Resolution in ms (Default: 1)
52
+
53
+ // Global behaviors
54
+ contaminationRate?: number; // Probability (0-1) of a random guess
55
+ stimulusCollapse?: CollapseDef; // Boundary dynamics DURING stimulus visibility
56
+
57
+ // Post-stimulus behavior
58
+ postStimStrategy: PostStimStrategyDef;
59
+ }
60
+
61
+ // --- Result ---
62
+
63
+ export interface DDMTrialResult {
64
+ choice: 0 | 1 | null;
65
+ rt: number; // Total reaction time including delays (ms)
66
+ finalEvidence: number; // Accumulator value at trial end
67
+ isContaminated: boolean; // True if trial was a random lapse
68
+ }
69
+
70
+ // --- Helpers ---
71
+
72
+ function resolveParam(def: ParameterDef): number {
73
+ if (typeof def === 'number') return def;
74
+ if (def.type === 'normal') return normal(def.mean, def.sd);
75
+ return uniform(def.min, def.max);
76
+ }
77
+
78
+ function resolveParamClamped(def: ParameterDef): number {
79
+ return Math.max(0, resolveParam(def));
80
+ }
81
+
82
+ // --- Simulation ---
83
+
84
+ export function simulateDDMTrial(params: DDMTrialParams): DDMTrialResult {
85
+ const dt = params.dt ?? 1;
86
+ const sqrtDt = Math.sqrt(dt);
87
+
88
+ // A1. Resolve starting point
89
+ const startingPoint = resolveParam(params.startingPoint);
90
+
91
+ // A2. Contamination check
92
+ if (params.contaminationRate && uniform(0, 1) < params.contaminationRate) {
93
+ return {
94
+ choice: uniform(0, 1) < 0.5 ? 0 : 1,
95
+ rt: uniform(0, params.timeLimit),
96
+ finalEvidence: startingPoint,
97
+ isContaminated: true,
98
+ };
99
+ }
100
+
101
+ // A3. Resolve remaining distributions for this trial
102
+ const baseDrift = resolveParam(params.driftRate);
103
+ const baseNoise = Math.max(0, resolveParam(params.noiseLevel));
104
+ const sensoryDelay = params.sensoryDelay != null ? resolveParamClamped(params.sensoryDelay) : 0;
105
+ const motorDelay = params.motorDelay != null ? resolveParamClamped(params.motorDelay) : 0;
106
+
107
+ // A4. Resolve boundaries
108
+ let currentUpper: number;
109
+ let currentLower: number;
110
+ if (Array.isArray(params.boundaries)) {
111
+ currentLower = params.boundaries[0];
112
+ currentUpper = params.boundaries[1];
113
+ } else {
114
+ currentUpper = params.boundaries;
115
+ currentLower = -params.boundaries;
116
+ }
117
+
118
+ // A5. Fast-forward clock past sensory delay
119
+ let time = sensoryDelay;
120
+ let evidence = startingPoint;
121
+ let boundaryHit = false;
122
+ let choice: 0 | 1 | null = null;
123
+
124
+ // B. Simulation loop
125
+ while (time < params.timeLimit) {
126
+ time += dt;
127
+
128
+ let currentDrift = baseDrift;
129
+ let currentNoise = baseNoise;
130
+
131
+ if (time <= params.stimOffset) {
132
+ // Phase 1: Stimulus visible
133
+ if (params.stimulusCollapse) {
134
+ const elapsed = time - sensoryDelay;
135
+ if (elapsed > (params.stimulusCollapse.delay ?? 0)) {
136
+ currentUpper -= params.stimulusCollapse.rate * dt;
137
+ currentLower += params.stimulusCollapse.rate * dt;
138
+ }
139
+ }
140
+ } else {
141
+ // Phase 2: Post-stimulus
142
+ const strategy = params.postStimStrategy;
143
+ if (strategy.type === 'snapshot') {
144
+ const distToUpper = Math.abs(evidence - currentUpper);
145
+ const distToLower = Math.abs(evidence - currentLower);
146
+ return {
147
+ choice: distToUpper <= distToLower ? 1 : 0,
148
+ rt: time + motorDelay,
149
+ finalEvidence: evidence,
150
+ isContaminated: false,
151
+ };
152
+ } else if (strategy.type === 'continue') {
153
+ currentDrift = strategy.residualDrift ?? 0;
154
+ currentNoise = baseNoise * (strategy.noiseMultiplier ?? 1);
155
+ } else {
156
+ // collapse
157
+ currentDrift = 0;
158
+ const elapsed = time - params.stimOffset;
159
+ if (elapsed > (strategy.collapseDef.delay ?? 0)) {
160
+ currentUpper -= strategy.collapseDef.rate * dt;
161
+ currentLower += strategy.collapseDef.rate * dt;
162
+ }
163
+ }
164
+ }
165
+
166
+ // B3. Check if evidence crossed or was passed by a boundary
167
+ if (evidence >= currentUpper) {
168
+ choice = 1;
169
+ boundaryHit = true;
170
+ break;
171
+ }
172
+ if (evidence <= currentLower) {
173
+ choice = 0;
174
+ boundaryHit = true;
175
+ break;
176
+ }
177
+
178
+ // B4. Step evidence
179
+ evidence += currentDrift * dt + currentNoise * sqrtDt * normal(0, 1);
180
+
181
+ // B5. Check thresholds after stepping
182
+ if (evidence >= currentUpper) {
183
+ choice = 1;
184
+ boundaryHit = true;
185
+ break;
186
+ }
187
+ if (evidence <= currentLower) {
188
+ choice = 0;
189
+ boundaryHit = true;
190
+ break;
191
+ }
192
+ }
193
+
194
+ // C. Finalize output
195
+ let rt: number;
196
+ if (boundaryHit) {
197
+ rt = time + motorDelay;
198
+ } else {
199
+ // timeLimit reached; no decision made
200
+ rt = params.timeLimit;
201
+ choice = null;
202
+ }
203
+
204
+ return { choice, rt, finalEvidence: evidence, isContaminated: false };
205
+ }
206
+
207
+ export function mapDDMChoice(
208
+ choice: 0 | 1 | null,
209
+ validKeys: string[],
210
+ correctResponse?: string | string[],
211
+ ): string | null {
212
+ if (choice == null || validKeys.length === 0) return null;
213
+ const correctKeys = Array.isArray(correctResponse)
214
+ ? correctResponse.map((k) => k.toLowerCase())
215
+ : correctResponse ? [correctResponse.toLowerCase()] : null;
216
+
217
+ if (!correctKeys) {
218
+ return validKeys[Math.floor(uniform(0, validKeys.length))];
219
+ }
220
+
221
+ if (choice === 1) {
222
+ const matches = validKeys.filter((k) => correctKeys.includes(k.toLowerCase()));
223
+ if (matches.length > 0) return matches[Math.floor(uniform(0, matches.length))];
224
+ } else {
225
+ const wrong = validKeys.filter((k) => !correctKeys.includes(k.toLowerCase()));
226
+ if (wrong.length > 0) return wrong[Math.floor(uniform(0, wrong.length))];
227
+ }
228
+
229
+ return validKeys[Math.floor(uniform(0, validKeys.length))];
230
+ }