Skip to content

Commit

Permalink
Added error for undefined types in jsPsych timeline.
Browse files Browse the repository at this point in the history
  • Loading branch information
okaycj committed Oct 3, 2024
1 parent 98b188a commit dcb2242
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
24 changes: 24 additions & 0 deletions packages/lookit-initjspsych/src/errors.ts
Original file line number Diff line number Diff line change
@@ -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. */
Expand All @@ -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.`,
);
}
}
6 changes: 5 additions & 1 deletion packages/lookit-initjspsych/src/index.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -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);
});

Expand Down

0 comments on commit dcb2242

Please sign in to comment.