All files / src question.ts

100% Statements 12/12
100% Branches 8/8
100% Functions 4/4
100% Lines 8/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 774x   29x         4x                     4x                                                 42x                                               4x       8x     21x    
import { z } from 'zod'
 
const uid = () => String(Math.random()).substring(2)
 
/**
 * Zod validation schema for {@link Choice}
 */
export const ChoiceSchema = z.strictObject({
  id: z.string().optional(),
  answer: z.string(),
  isCorrect: z.boolean(),
})
 
export type Choice = z.infer<typeof ChoiceSchema>
 
/**
 * Zod validation schema for {@link Question}
 */
export const QuestionSchema = z.strictObject({
  id: z.string().optional(),
  question: z.string(),
  choices: z.array(ChoiceSchema),
})
 
export type Question = z.infer<typeof QuestionSchema>
 
type CreateChoiceParams = Partial<Choice>
type CreateQuestionParams = Partial<Omit<Question, 'choices'> & { choices: CreateChoiceParams[] }>
 
/**
 * Create a Choice object with the given parameters.
 * If no parameters are given, default values will be used.
 * The parameters include an ID, answer, and a boolean that indicates whether or not the choice is correct.
 * The default value of isCorrect is false.
 *
 * @example ```ts
 * const myChoice = createChoice({
 *   answer: 'The answer is 42',
 *   isCorrect: true,
 * });
 * console.log(myChoice); // Output: { id: '<random uuid>', answer: 'The answer is 42', isCorrect: true }
 * ```
 */
export const createChoice = ({ id = uid(), answer = '', isCorrect = false }: CreateChoiceParams = {}): Choice => ({
  id,
  answer,
  isCorrect,
})
 
/**
 * Create a Question object with the given parameters.
 * If no parameters are given, default values will be used.
 * The parameters include an ID, question, and an array of Choice object.
 * The default awswer is an empty choice which is marked as default correct answer.
 *
 * @example ```ts
 * const myQuestion = createQuestion({
 *   question: 'What is the answer to the ultimate question of life, the universe, and everything?',
 *   choices: [
 *     { answer: 'I dunno', isCorrect: true },
 *     { answer: '12', isCorrect: false },
 *     { answer: '21', isCorrect: false },
 *   ],
 * })
 * console.log(myQuestion);
 * ```
 */
export const createQuestion = ({
  id = uid(),
  question = '',
  choices = [createChoice({ isCorrect: true })],
}: CreateQuestionParams = {}): Question => ({
  id,
  question,
  choices: choices.map((c) => createChoice(c)),
})