From dcb2242442fffb9a664f8ad81b5c658fe6a7c816 Mon Sep 17 00:00:00 2001 From: CJ Green <44074998+okaycj@users.noreply.github.com> Date: Thu, 3 Oct 2024 15:31:11 -0400 Subject: [PATCH] Added error for undefined types in jsPsych timeline. --- packages/lookit-initjspsych/src/errors.ts | 24 +++++++++++++++++++++++ packages/lookit-initjspsych/src/index.ts | 6 +++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/packages/lookit-initjspsych/src/errors.ts b/packages/lookit-initjspsych/src/errors.ts index 449b887b..05c60be0 100644 --- a/packages/lookit-initjspsych/src/errors.ts +++ b/packages/lookit-initjspsych/src/errors.ts @@ -1,3 +1,14 @@ +/** + * Needed to tell user that their nth trial was undefined. + * https://stackoverflow.com/a/39466341 + * + * @param n - Number needing suffix + * @returns Number with ordinal suffix + */ +const nth = (n: number) => { + return `${n}${["st", "nd", "rd"][((((n + 90) % 100) - 10) % 10) - 1] || "th"}`; +}; + /** Error when experiment data doesn't contain values on finish. */ export class SequenceExpDataError extends Error { /** Error when experiment data doesn't contain values on finish. */ @@ -6,3 +17,16 @@ export class SequenceExpDataError extends Error { this.name = "SequenceExpDataError"; } } +/** When a trial is accidentally undefined. */ +export class UndefinedTypeError extends Error { + /** + * Inform user that their nth trial is undefined. + * + * @param idx - Index of timeline where trial type is undefined + */ + public constructor(idx: number) { + super( + `${nth(idx + 1)} trial has an undefined type. Maybe the type name is misspelled.`, + ); + } +} diff --git a/packages/lookit-initjspsych/src/index.ts b/packages/lookit-initjspsych/src/index.ts index ab2a17e6..d42b60cd 100644 --- a/packages/lookit-initjspsych/src/index.ts +++ b/packages/lookit-initjspsych/src/index.ts @@ -1,4 +1,5 @@ import { initJsPsych as origInitJsPsych } from "jspsych"; +import { UndefinedTypeError } from "./errors"; import { JsPsychOptions, Timeline } from "./types"; import { on_data_update, on_finish } from "./utils"; @@ -39,7 +40,10 @@ const lookitInitJsPsych = (responseUuid: string) => { */ jsPsych.run = function (timeline) { // check timeline here... - timeline.map((t: Timeline) => { + timeline.map((t: Timeline, idx: number) => { + if (!t.type) { + throw new UndefinedTypeError(idx); + } addChsData(t); });