@khanacademy/perseus-score 2.3.7 → 3.0.0

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.
package/dist/es/index.js DELETED
@@ -1,2274 +0,0 @@
1
- import _extends from '@babel/runtime/helpers/extends';
2
- import * as KAS from '@khanacademy/kas';
3
- import { KhanMath, number, geometry, angles, coefficients } from '@khanacademy/kmath';
4
- import { PerseusError, Errors, getDecimalSeparator, GrapherUtil, approximateDeepEqual, approximateEqual, deepClone, getMatrixSize, getWidgetIdsFromContent, getUpgradedWidgetOptions } from '@khanacademy/perseus-core';
5
- import _ from 'underscore';
6
-
7
- const MISSING_PERCENT_ERROR = "MISSING_PERCENT_ERROR";
8
- const NEEDS_TO_BE_SIMPLIFIED_ERROR = "NEEDS_TO_BE_SIMPLIFIED_ERROR";
9
- const APPROXIMATED_PI_ERROR = "APPROXIMATED_PI_ERROR";
10
- const EXTRA_SYMBOLS_ERROR = "EXTRA_SYMBOLS_ERROR";
11
- const WRONG_CASE_ERROR = "WRONG_CASE_ERROR";
12
- const WRONG_LETTER_ERROR = "WRONG_LETTER_ERROR";
13
- const MULTIPLICATION_SIGN_ERROR = "MULTIPLICATION_SIGN_ERROR";
14
- const INVALID_SELECTION_ERROR = "INVALID_SELECTION_ERROR";
15
- const CHOOSE_CORRECT_NUM_ERROR = "CHOOSE_CORRECT_NUM_ERROR";
16
- const NOT_NONE_ABOVE_ERROR = "NOT_NONE_ABOVE_ERROR";
17
- const FILL_ALL_CELLS_ERROR = "FILL_ALL_CELLS_ERROR";
18
- const ErrorCodes = {
19
- MISSING_PERCENT_ERROR,
20
- NEEDS_TO_BE_SIMPLIFIED_ERROR,
21
- APPROXIMATED_PI_ERROR,
22
- EXTRA_SYMBOLS_ERROR,
23
- WRONG_CASE_ERROR,
24
- WRONG_LETTER_ERROR,
25
- MULTIPLICATION_SIGN_ERROR,
26
- INVALID_SELECTION_ERROR,
27
- CHOOSE_CORRECT_NUM_ERROR,
28
- NOT_NONE_ABOVE_ERROR,
29
- FILL_ALL_CELLS_ERROR
30
- };
31
-
32
- const MAXERROR_EPSILON = Math.pow(2, -42);
33
-
34
- // TOOD(kevinb): Figure out how this relates to KEScore in
35
- // perseus-all-package/types.js and see if there's a way to
36
- // unify these types.
37
-
38
- /**
39
- * Answer types
40
- *
41
- * Utility for creating answerable questions displayed in exercises
42
- *
43
- * Different answer types produce different kinds of input displays, and do
44
- * different kinds of checking on the solutions.
45
- *
46
- * Each of the objects contain two functions, setup and createValidator.
47
- *
48
- * The setup function takes a solutionarea and solution, and performs setup
49
- * within the solutionarea, and then returns an object which contains:
50
- *
51
- * answer: a function which, when called, will retrieve the current answer from
52
- * the solutionarea, which can then be validated using the validator
53
- * function
54
- * validator: a function returned from the createValidator function (defined
55
- * below)
56
- * solution: the correct answer to the problem
57
- * showGuess: a function which, when given a guess, shows the guess within the
58
- * provided solutionarea
59
- * showGuessCustom: a function which displays parts of a guess that are not
60
- * within the solutionarea; currently only used for custom
61
- * answers
62
- *
63
- * The createValidator function only takes a solution, and it returns a
64
- * function which can be used to validate an answer.
65
- *
66
- * The resulting validator function returns:
67
- * - true: if the answer is fully correct
68
- * - false: if the answer is incorrect
69
- * - "" (the empty string): if no answer has been provided (e.g. the answer box
70
- * is left unfilled)
71
- * - a string: if there is some slight error
72
- *
73
- * In most cases, setup and createValidator don't really need the solution DOM
74
- * element so we have setupFunctional and createValidatorFunctional for them
75
- * which take only $solution.text() and $solution.data(). This makes it easier
76
- * to reuse specific answer types.
77
- *
78
- * TODO(alpert): Think of a less-absurd name for createValidatorFunctional.
79
- *
80
- */
81
- const KhanAnswerTypes = {
82
- /*
83
- * predicate answer type
84
- *
85
- * performs simple predicate-based checking of a numeric solution, with
86
- * different kinds of number formats
87
- *
88
- * Uses the data-forms option on the solution to choose which number formats
89
- * are acceptable. Available data-forms:
90
- *
91
- * - integer: 3
92
- * - proper: 3/5
93
- * - improper: 5/3
94
- * - pi: 3 pi
95
- * - log: log(5)
96
- * - percent: 15%
97
- * - mixed: 1 1/3
98
- * - decimal: 1.7
99
- *
100
- * The solution should be a predicate of the form:
101
- *
102
- * function(guess, maxError) {
103
- * return abs(guess - 3) < maxError;
104
- * }
105
- *
106
- */
107
- predicate: {
108
- defaultForms: "integer, proper, improper, mixed, decimal",
109
- createValidatorFunctional: function (predicate, options) {
110
- // Extract the options from the given solution object
111
- options = _.extend({
112
- simplify: "required",
113
- ratio: false,
114
- forms: KhanAnswerTypes.predicate.defaultForms
115
- }, options);
116
- let acceptableForms;
117
- // this is maintaining backwards compatibility
118
- // TODO(merlob) fix all places that depend on this, then delete
119
- if (!_.isArray(options.forms)) {
120
- acceptableForms = options.forms.split(/\s*,\s*/);
121
- } else {
122
- acceptableForms = options.forms;
123
- }
124
-
125
- // TODO(jack): remove options.inexact in favor of options.maxError
126
- if (options.inexact === undefined) {
127
- // If we aren't allowing inexact, ensure that we don't have a
128
- // large maxError as well.
129
- options.maxError = 0;
130
- }
131
- // Allow a small tolerance on maxError, to avoid numerical
132
- // representation issues (2.3 should be correct for a solution of
133
- // 2.45 with maxError=0.15).
134
- options.maxError = +options.maxError + MAXERROR_EPSILON;
135
-
136
- // If percent is an acceptable form, make sure it's the last one
137
- // in the list so we don't prematurely complain about not having
138
- // a percent sign when the user entered the correct answer in a
139
- // different form (such as a decimal or fraction)
140
- if (_.contains(acceptableForms, "percent")) {
141
- acceptableForms = _.without(acceptableForms, "percent");
142
- acceptableForms.push("percent");
143
- }
144
-
145
- // Take text looking like a fraction, and turn it into a number
146
- const fractionTransformer = function fractionTransformer(text) {
147
- text = text
148
- // Replace unicode minus sign with hyphen
149
- .replace(/\u2212/, "-")
150
- // Remove space after +, -
151
- .replace(/([+-])\s+/g, "$1")
152
- // Remove leading/trailing whitespace
153
- .replace(/(^\s*)|(\s*$)/gi, "");
154
-
155
- // Extract numerator and denominator
156
- const match = text.match(/^([+-]?\d+)\s*\/\s*([+-]?\d+)$/);
157
- // Fractions are represented as "-\frac{numerator}{denominator}"
158
- // in Mobile device input instead of "numerator/denominator" as
159
- // in web-browser.
160
- const mobileDeviceMatch = text.match(/^([+-]?)\\frac\{([+-]?\d+)\}\{([+-]?\d+)\}$/);
161
- const parsedInt = parseInt(text, 10);
162
- if (match || mobileDeviceMatch) {
163
- let num;
164
- let denom;
165
- let simplified = true;
166
- if (match) {
167
- num = parseFloat(match[1]);
168
- denom = parseFloat(match[2]);
169
- } else {
170
- num = parseFloat(mobileDeviceMatch[2]);
171
- if (mobileDeviceMatch[1] === "-") {
172
- if (num < 0) {
173
- simplified = false;
174
- }
175
- num = -num;
176
- }
177
- denom = parseFloat(mobileDeviceMatch[3]);
178
- }
179
- simplified = simplified && denom > 0 && (options.ratio || denom !== 1) && KhanMath.getGCD(num, denom) === 1;
180
- return [{
181
- value: num / denom,
182
- exact: simplified
183
- }];
184
- }
185
- if (!isNaN(parsedInt) && "" + parsedInt === text) {
186
- return [{
187
- value: parsedInt,
188
- exact: true
189
- }];
190
- }
191
- return [];
192
- };
193
-
194
- /*
195
- * Different forms of numbers
196
- *
197
- * Each function returns a list of objects of the form:
198
- *
199
- * {
200
- * value: numerical value,
201
- * exact: true/false
202
- * }
203
- */
204
- const forms = {
205
- // integer, which is encompassed by decimal
206
- integer: function (text) {
207
- // Compare the decimal form to the decimal form rounded to
208
- // an integer. Only accept if the user actually entered an
209
- // integer.
210
- const decimal = forms.decimal(text);
211
- const rounded = forms.decimal(text, 1);
212
- if (decimal[0].value != null && decimal[0].value === rounded[0].value || decimal[1].value != null && decimal[1].value === rounded[1].value) {
213
- return decimal;
214
- }
215
- return [];
216
- },
217
- // A proper fraction
218
- proper: function (text) {
219
- const transformed = fractionTransformer(text);
220
- return transformed.flatMap(o => {
221
- // All fractions that are less than 1
222
- if (Math.abs(o.value) < 1) {
223
- return [o];
224
- }
225
- return [];
226
- });
227
- },
228
- // an improper fraction
229
- improper: function (text) {
230
- // As our answer keys are always in simplest form, we need
231
- // to check for the existence of a fraction in the input before
232
- // validating the answer. If no fraction is found, we consider
233
- // the answer to be incorrect.
234
- const fractionExists = text.includes("/") || text.match(/\\(d?frac)/);
235
- if (!fractionExists) {
236
- return [];
237
- }
238
- const transformed = fractionTransformer(text);
239
- return transformed.flatMap(o => {
240
- // All fractions that are greater than 1
241
- if (Math.abs(o.value) >= 1) {
242
- return [o];
243
- }
244
- return [];
245
- });
246
- },
247
- // pi-like numbers
248
- pi: function (text) {
249
- let match;
250
- let possibilities = [];
251
-
252
- // Replace unicode minus sign with hyphen
253
- text = text.replace(/\u2212/, "-");
254
-
255
- // - pi
256
- // (Note: we also support \pi (for TeX), p, tau (and \tau,
257
- // and t), pau.)
258
- if (match = text.match(/^([+-]?)\s*(\\?pi|p|\u03c0|\\?tau|t|\u03c4|pau)$/i)) {
259
- possibilities = [{
260
- value: parseFloat(match[1] + "1"),
261
- exact: true
262
- }];
263
-
264
- // 5 / 6 pi
265
- } else if (match = text.match(/^([+-]?\s*\d+\s*(?:\/\s*[+-]?\s*\d+)?)\s*\*?\s*(\\?pi|p|\u03c0|\\?tau|t|\u03c4|pau)$/i)) {
266
- possibilities = fractionTransformer(match[1]);
267
-
268
- // 4 5 / 6 pi
269
- } else if (match = text.match(/^([+-]?)\s*(\d+)\s*([+-]?\d+)\s*\/\s*([+-]?\d+)\s*\*?\s*(\\?pi|p|\u03c0|\\?tau|t|\u03c4|pau)$/i)) {
270
- const sign = parseFloat(match[1] + "1");
271
- const integ = parseFloat(match[2]);
272
- const num = parseFloat(match[3]);
273
- const denom = parseFloat(match[4]);
274
- const simplified = num < denom && KhanMath.getGCD(num, denom) === 1;
275
- possibilities = [{
276
- value: sign * (integ + num / denom),
277
- exact: simplified
278
- }];
279
-
280
- // 5 pi / 6
281
- } else if (match = text.match(/^([+-]?\s*\d+)\s*\*?\s*(\\?pi|p|\u03c0|\\?tau|t|\u03c4|pau)\s*(?:\/\s*([+-]?\s*\d+))?$/i)) {
282
- possibilities = fractionTransformer(match[1] + "/" + match[3]);
283
-
284
- // - pi / 4
285
- } else if (match = text.match(/^([+-]?)\s*\*?\s*(\\?pi|p|\u03c0|\\?tau|t|\u03c4|pau)\s*(?:\/\s*([+-]?\d+))?$/i)) {
286
- possibilities = fractionTransformer(match[1] + "1/" + match[3]);
287
-
288
- // 0
289
- } else if (text === "0") {
290
- possibilities = [{
291
- value: 0,
292
- exact: true
293
- }];
294
-
295
- // 0.5 pi (fallback)
296
- } else if (match = text.match(/^(.+)\s*\*?\s*(\\?pi|p|\u03c0|\\?tau|t|\u03c4|pau)$/i)) {
297
- possibilities = forms.decimal(match[1]);
298
- } else {
299
- possibilities = _.reduce(KhanAnswerTypes.predicate.defaultForms.split(/\s*,\s*/), function (memo, form) {
300
- return memo.concat(forms[form](text));
301
- }, []);
302
-
303
- // If the answer is a floating point number that's
304
- // near a multiple of pi, mark is as being possibly
305
- // an approximation of pi. We actually check if
306
- // it's a plausible approximation of pi/12, since
307
- // sometimes the correct answer is like pi/3 or pi/4.
308
- // We also say it's a pi-approximation if it involves
309
- // x/7 (since 22/7 is an approximation of pi.)
310
- // Never mark an integer as being an approximation
311
- // of pi.
312
- let approximatesPi = false;
313
- const number = parseFloat(text);
314
- if (!isNaN(number) && number !== parseInt(text)) {
315
- const piMult = Math.PI / 12;
316
- const roundedNumber = piMult * Math.round(number / piMult);
317
- if (Math.abs(number - roundedNumber) < 0.01) {
318
- approximatesPi = true;
319
- }
320
- } else if (text.match(/\/\s*7/)) {
321
- approximatesPi = true;
322
- }
323
- if (approximatesPi) {
324
- _.each(possibilities, function (possibility) {
325
- possibility.piApprox = true;
326
- });
327
- }
328
- return possibilities;
329
- }
330
- let multiplier = Math.PI;
331
- if (text.match(/\\?tau|t|\u03c4/)) {
332
- multiplier = Math.PI * 2;
333
- }
334
-
335
- // We're taking an early stand along side xkcd in the
336
- // inevitable ti vs. pau debate... http://xkcd.com/1292
337
- if (text.match(/pau/)) {
338
- multiplier = Math.PI * 1.5;
339
- }
340
- possibilities.forEach(possibility => {
341
- possibility.value *= multiplier;
342
- });
343
- return possibilities;
344
- },
345
- // Converts '' to 1 and '-' to -1 so you can write "[___] x"
346
- // and accept sane things
347
- coefficient: function (text) {
348
- let possibilities = [];
349
-
350
- // Replace unicode minus sign with hyphen
351
- text = text.replace(/\u2212/, "-");
352
- if (text === "") {
353
- possibilities = [{
354
- value: 1,
355
- exact: true
356
- }];
357
- } else if (text === "-") {
358
- possibilities = [{
359
- value: -1,
360
- exact: true
361
- }];
362
- }
363
- return possibilities;
364
- },
365
- // simple log(c) form
366
- log: function (text) {
367
- let match;
368
- let possibilities = [];
369
-
370
- // Replace unicode minus sign with hyphen
371
- text = text.replace(/\u2212/, "-");
372
- text = text.replace(/[ \(\)]/g, "");
373
- if (match = text.match(/^log\s*(\S+)\s*$/i)) {
374
- // @ts-expect-error - TS2322 - Type '{ value: number | undefined; exact: boolean; }[]' is not assignable to type 'never[]'.
375
- possibilities = forms.decimal(match[1]);
376
- } else if (text === "0") {
377
- // @ts-expect-error - TS2322 - Type 'number' is not assignable to type 'never'. | TS2322 - Type 'boolean' is not assignable to type 'never'.
378
- possibilities = [{
379
- value: 0,
380
- exact: true
381
- }];
382
- }
383
- return possibilities;
384
- },
385
- // Numbers with percent signs
386
- percent: function (text) {
387
- text = String(text).trim();
388
- // store whether or not there is a percent sign
389
- let hasPercentSign = false;
390
- if (text.indexOf("%") === text.length - 1) {
391
- text = text.substring(0, text.length - 1).trim();
392
- hasPercentSign = true;
393
- }
394
- const transformed = forms.decimal(text);
395
- transformed.forEach(t => {
396
- t.exact = hasPercentSign;
397
- // @ts-expect-error - TS2532 - Object is possibly 'undefined'.
398
- t.value = t.value / 100;
399
- });
400
- return transformed;
401
- },
402
- // Mixed numbers, like 1 3/4
403
- mixed: function (text) {
404
- const match = text
405
- // Replace unicode minus sign with hyphen
406
- .replace(/\u2212/, "-")
407
- // Remove space after +, -
408
- .replace(/([+-])\s+/g, "$1")
409
- // Extract integer, numerator and denominator
410
- .match(/^([+-]?)(\d+)\s+(\d+)\s*\/\s*(\d+)$/);
411
- if (match) {
412
- const sign = parseFloat(match[1] + "1");
413
- const integ = parseFloat(match[2]);
414
- const num = parseFloat(match[3]);
415
- const denom = parseFloat(match[4]);
416
- const simplified = num < denom && KhanMath.getGCD(num, denom) === 1;
417
- return [{
418
- value: sign * (integ + num / denom),
419
- exact: simplified
420
- }];
421
- }
422
- return [];
423
- },
424
- // Decimal numbers -- compare entered text rounded to
425
- // 'precision' Reciprical of the precision against the correct
426
- // answer. We round to 1/1e10 by default, which is healthily
427
- // less than machine epsilon but should be more than any real
428
- // decimal answer would use. (The 'integer' answer type uses
429
- // precision == 1.)
430
- decimal: function (text, precision = 1e10) {
431
- const normal = function normal(text) {
432
- text = String(text).trim();
433
- const match = text
434
- // Replace unicode minus sign with hyphen
435
- .replace(/\u2212/, "-")
436
- // Remove space after +, -
437
- .replace(/([+-])\s+/g, "$1")
438
- // Extract integer, numerator and denominator. If
439
- // commas or spaces are used, they must be in the
440
- // "correct" places
441
- .match(/^([+-]?(?:\d{1,3}(?:[, ]?\d{3})*\.?|\d{0,3}(?:[, ]?\d{3})*\.(?:\d{3}[, ]?)*\d{1,3}))$/);
442
-
443
- // You can't start a number with `0,`, to prevent us
444
- // interpeting '0.342' as correct for '342'
445
- const badLeadingZero = text.match(/^0[0,]*,/);
446
- if (match && !badLeadingZero) {
447
- let x = parseFloat(match[1].replace(/[, ]/g, ""));
448
- if (options.inexact === undefined) {
449
- x = Math.round(x * precision) / precision;
450
- }
451
- return x;
452
- }
453
- };
454
- const commas = function commas(text) {
455
- text = text.replace(/([\.,])/g, function (_, c) {
456
- return c === "." ? "," : ".";
457
- });
458
- return normal(text);
459
- };
460
- return [{
461
- value: normal(text),
462
- exact: true
463
- }, {
464
- value: commas(text),
465
- exact: true
466
- }];
467
- }
468
- };
469
-
470
- // validator function
471
- return function (guess) {
472
- // The fallback variable is used in place of the answer, if no
473
- // answer is provided (i.e. the field is left blank)
474
- const fallback = options.fallback != null ? "" + options.fallback : "";
475
- guess = String(guess).trim() || fallback;
476
- const score = {
477
- empty: guess === "",
478
- correct: false,
479
- message: null,
480
- guess: guess
481
- };
482
-
483
- // iterate over all the acceptable forms, and if one of the
484
- // answers is correct, return true
485
- acceptableForms.forEach(form => {
486
- const transformed = forms[form](guess);
487
- for (let j = 0, l = transformed.length; j < l; j++) {
488
- const val = transformed[j].value;
489
- const exact = transformed[j].exact;
490
- const piApprox = transformed[j].piApprox;
491
- // If a string was returned, and it exactly matches,
492
- // return true
493
- if (predicate(val, options.maxError)) {
494
- // If the exact correct number was returned,
495
- // return true
496
- if (exact || options.simplify === "optional") {
497
- score.correct = true;
498
- score.message = options.message || null;
499
- // If the answer is correct, don't say it's
500
- // empty. This happens, for example, with the
501
- // coefficient type where guess === "" but is
502
- // interpreted as "1" which is correct.
503
- score.empty = false;
504
- } else if (form === "percent") {
505
- // Otherwise, an error was returned
506
- score.empty = true;
507
- score.message = ErrorCodes.MISSING_PERCENT_ERROR;
508
- } else {
509
- if (options.simplify !== "enforced") {
510
- score.empty = true;
511
- }
512
- score.message = ErrorCodes.NEEDS_TO_BE_SIMPLIFIED_ERROR;
513
- }
514
- // The return false below stops the looping of the
515
- // callback since predicate check succeeded.
516
- // No more forms to look to verify the user guess.
517
- return false;
518
- }
519
- if (piApprox && predicate(val, Math.abs(val * 0.001))) {
520
- score.empty = true;
521
- score.message = ErrorCodes.APPROXIMATED_PI_ERROR;
522
- }
523
- }
524
- });
525
- if (score.correct === false) {
526
- let interpretedGuess = false;
527
- _.each(forms, function (form) {
528
- const anyAreNaN = _.any(form(guess), function (t) {
529
- return t.value != null && !_.isNaN(t.value);
530
- });
531
- if (anyAreNaN) {
532
- interpretedGuess = true;
533
- }
534
- });
535
- if (!interpretedGuess) {
536
- score.empty = true;
537
- score.message = ErrorCodes.EXTRA_SYMBOLS_ERROR;
538
- return score;
539
- }
540
- }
541
- return score;
542
- };
543
- }
544
- },
545
- /*
546
- * number answer type
547
- *
548
- * wraps the predicate answer type to performs simple number-based checking
549
- * of a solution
550
- */
551
- number: {
552
- convertToPredicate: function (correctAnswer, options) {
553
- const correctFloat = parseFloat(correctAnswer);
554
- return [function (guess, maxError) {
555
- return Math.abs(guess - correctFloat) < maxError;
556
- }, _extends({}, options, {
557
- type: "predicate"
558
- })];
559
- },
560
- createValidatorFunctional: function (correctAnswer, options) {
561
- return KhanAnswerTypes.predicate.createValidatorFunctional(...KhanAnswerTypes.number.convertToPredicate(correctAnswer, options));
562
- }
563
- },
564
- /*
565
- * The expression answer type parses a given expression or equation
566
- * and semantically compares it to the solution. In addition, instant
567
- * feedback is provided by rendering the last answer that fully parsed.
568
- *
569
- * Parsing options:
570
- * functions (e.g. data-functions="f g h")
571
- * A space or comma separated list of single-letter variables that
572
- * should be interpreted as functions. Case sensitive. "e" and "i"
573
- * are reserved.
574
- *
575
- * no functions specified: f(x+y) == fx + fy
576
- * with "f" as a function: f(x+y) != fx + fy
577
- *
578
- * Comparison options:
579
- * same-form (e.g. data-same-form)
580
- * If present, the answer must match the solution's structure in
581
- * addition to evaluating the same. Commutativity and excess negation
582
- * are ignored, but all other changes will trigger a rejection. Useful
583
- * for requiring a particular form of an equation, or if the answer
584
- * must be factored.
585
- *
586
- * example question: Factor x^2 + x - 2
587
- * example solution: (x-1)(x+2)
588
- * accepted answers: (x-1)(x+2), (x+2)(x-1), ---(-x-2)(-1+x), etc.
589
- * rejected answers: x^2+x-2, x*x+x-2, x(x+1)-2, (x-1)(x+2)^1, etc.
590
- * rejection message: Your answer is not in the correct form
591
- *
592
- * simplify (e.g. data-simplify)
593
- * If present, the answer must be fully expanded and simplified. Use
594
- * carefully - simplification is hard and there may be bugs, or you
595
- * might not agree on the definition of "simplified" used. You will
596
- * get an error if the provided solution is not itself fully expanded
597
- * and simplified.
598
- *
599
- * example question: Simplify ((n*x^5)^5) / (n^(-2)*x^2)^-3
600
- * example solution: x^31 / n
601
- * accepted answers: x^31 / n, x^31 / n^1, x^31 * n^(-1), etc.
602
- * rejected answers: (x^25 * n^5) / (x^(-6) * n^6), etc.
603
- * rejection message: Your answer is not fully expanded and simplified
604
- *
605
- * Rendering options:
606
- * times (e.g. data-times)
607
- * If present, explicit multiplication (such as between numbers) will
608
- * be rendered with a cross/x symbol (TeX: \times) instead of the usual
609
- * center dot (TeX: \cdot).
610
- *
611
- * normal rendering: 2 * 3^x -> 2 \cdot 3^{x}
612
- * but with "times": 2 * 3^x -> 2 \times 3^{x}
613
- */
614
- expression: {
615
- parseSolution: function (solutionString, options) {
616
- let solution = KAS.parse(solutionString, options);
617
- if (!solution.parsed) {
618
- throw new PerseusError("The provided solution (" + solutionString + ") didn't parse.", Errors.InvalidInput);
619
- } else if (options.simplified && !solution.expr.isSimplified()) {
620
- throw new PerseusError("The provided solution (" + solutionString + ") isn't fully expanded and simplified.", Errors.InvalidInput);
621
- } else {
622
- solution = solution.expr;
623
- }
624
- return solution;
625
- },
626
- createValidatorFunctional: function (solution, options) {
627
- return function (guess) {
628
- const score = {
629
- empty: false,
630
- correct: false,
631
- message: null,
632
- guess: guess,
633
- // Setting `ungraded` to true indicates that if the
634
- // guess doesn't match any of the solutions, the guess
635
- // shouldn't be marked as incorrect; instead, `message`
636
- // should be shown to the user. This is different from
637
- // setting `empty` to true, since the behavior of `empty`
638
- // is that `message` only will be shown if the guess is
639
- // graded as empty for every solution.
640
- ungraded: false
641
- };
642
-
643
- // Don't bother parsing an empty input
644
- if (!guess) {
645
- // @ts-expect-error - TS2540 - Cannot assign to 'empty' because it is a read-only property.
646
- score.empty = true;
647
- return score;
648
- }
649
- const answer = KAS.parse(guess, options);
650
-
651
- // An unsuccessful parse doesn't count as wrong
652
- if (!answer.parsed) {
653
- // @ts-expect-error - TS2540 - Cannot assign to 'empty' because it is a read-only property.
654
- score.empty = true;
655
- return score;
656
- }
657
-
658
- // Solution will need to be parsed again if we're creating
659
- // this from a multiple question type
660
- if (typeof solution === "string") {
661
- solution = KhanAnswerTypes.expression.parseSolution(solution, options);
662
- }
663
- const result = KAS.compare(answer.expr, solution, options);
664
- if (result.equal) {
665
- // Correct answer
666
- // @ts-expect-error - TS2540 - Cannot assign to 'correct' because it is a read-only property.
667
- score.correct = true;
668
- } else if (result.wrongVariableNames || result.wrongVariableCase) {
669
- // We don't want to give people an error for getting the
670
- // variable names or the variable case wrong.
671
- // TODO(aasmund): This should ideally have been handled
672
- // under the `result.message` condition, but the
673
- // KAS messages currently aren't translatable.
674
- // @ts-expect-error - TS2540 - Cannot assign to 'ungraded' because it is a read-only property.
675
- score.ungraded = true;
676
- // @ts-expect-error - TS2540 - Cannot assign to 'message' because it is a read-only property.
677
- score.message = result.wrongVariableCase ? ErrorCodes.WRONG_CASE_ERROR : ErrorCodes.WRONG_LETTER_ERROR;
678
- // Don't tell the use they're "almost there" in this case, that may not be true and isn't helpful.
679
- // @ts-expect-error - TS2339 - Property 'suppressAlmostThere' does not exist on type '{ readonly empty: false; readonly correct: false; readonly message: string | null | undefined; readonly guess: any; readonly ungraded: false; }'.
680
- score.suppressAlmostThere = true;
681
- } else if (result.message) {
682
- // Nearly correct answer
683
- // TODO(aasmund): This message also isn't translatable;
684
- // need to fix that in KAS
685
- // @ts-expect-error - TS2540 - Cannot assign to 'message' because it is a read-only property.
686
- score.message = result.message;
687
- } else {
688
- // Replace x with * and see if it would have been correct
689
- // TODO(aasmund): I think this branch is effectively dead,
690
- // because the replacement will only work in situations
691
- // where the variables are wrong (except if the variable
692
- // is x, in which case the replacement won't work either),
693
- // which is handled by another branch. When we implement a
694
- // more sophisticated variable check, revive this or
695
- // remove it completely if it will never come into play.
696
- const answerX = KAS.parse(guess.replace(/[xX]/g, "*"), options);
697
- if (answerX.parsed) {
698
- const resultX = KAS.compare(answerX.expr, solution, options);
699
- if (resultX.equal) {
700
- // @ts-expect-error - TS2540 - Cannot assign to 'ungraded' because it is a read-only property.
701
- score.ungraded = true;
702
- // @ts-expect-error - TS2540 - Cannot assign to 'message' because it is a read-only property.
703
- score.message = ErrorCodes.MULTIPLICATION_SIGN_ERROR;
704
- } else if (resultX.message) {
705
- // TODO(aasmund): I18nize `score.message`
706
- // @ts-expect-error - TS2540 - Cannot assign to 'message' because it is a read-only property.
707
- score.message = resultX.message + " Also, I'm a computer. I only understand " + "multiplication if you use an " + "asterisk (*) as the multiplication " + "sign.";
708
- }
709
- }
710
- }
711
- return score;
712
- };
713
- }
714
- }
715
- };
716
-
717
- function scoreCategorizer(userInput, rubric) {
718
- let allCorrect = true;
719
- rubric.values.forEach((value, i) => {
720
- if (userInput.values[i] !== value) {
721
- allCorrect = false;
722
- }
723
- });
724
- return {
725
- type: "points",
726
- earned: allCorrect ? 1 : 0,
727
- total: 1,
728
- message: null
729
- };
730
- }
731
-
732
- /**
733
- * Checks userInput from the categorizer widget to see if the user has selected
734
- * a category for each item.
735
- * @param userInput - The user's input corresponding to an array of indices that
736
- * represent the selected category for each row/item.
737
- * @param validationData - An array of strings corresponding to each row/item
738
- * @param strings - Used to provide a validation message
739
- */
740
- function validateCategorizer(userInput, validationData) {
741
- const incomplete = validationData.items.some((_, i) => userInput.values[i] == null);
742
- if (incomplete) {
743
- return {
744
- type: "invalid",
745
- message: ErrorCodes.INVALID_SELECTION_ERROR
746
- };
747
- }
748
- return null;
749
- }
750
-
751
- function scoreCSProgram(userInput) {
752
- // The CS program can tell us whether it's correct or incorrect,
753
- // and pass an optional message
754
- if (userInput.status === "correct") {
755
- return {
756
- type: "points",
757
- earned: 1,
758
- total: 1,
759
- message: userInput.message || null
760
- };
761
- }
762
- if (userInput.status === "incorrect") {
763
- return {
764
- type: "points",
765
- earned: 0,
766
- total: 1,
767
- message: userInput.message || null
768
- };
769
- }
770
- return {
771
- type: "invalid",
772
- message: "Keep going, you're not there yet!"
773
- };
774
- }
775
-
776
- function scoreDropdown(userInput, rubric) {
777
- const correct = rubric.choices[userInput.value - 1].correct;
778
- return {
779
- type: "points",
780
- earned: correct ? 1 : 0,
781
- total: 1,
782
- message: null
783
- };
784
- }
785
-
786
- /**
787
- * Checks if the user has selected an item from the dropdown before scoring.
788
- * This is shown with a userInput value / index other than 0.
789
- */
790
- function validateDropdown(userInput) {
791
- if (userInput.value === 0) {
792
- return {
793
- type: "invalid",
794
- message: null
795
- };
796
- }
797
- return null;
798
- }
799
-
800
- /* Content creators input a list of answers which are matched from top to
801
- * bottom. The intent is that they can include spcific solutions which should
802
- * be graded as correct or incorrect (or ungraded!) first, then get more
803
- * general.
804
- *
805
- * We iterate through each answer, trying to match it with the user's input
806
- * using the following angorithm:
807
- * - Try to parse the user's input. If it doesn't parse then return "not
808
- * graded".
809
- * - For each answer:
810
- * ~ Try to validate the user's input against the answer. The answer is
811
- * expected to parse.
812
- * ~ If the user's input validates (the validator judges it "correct"), we've
813
- * matched and can stop considering answers.
814
- * - If there were no matches or the matching answer is considered "ungraded",
815
- * show the user an error. TODO(joel) - what error?
816
- * - Otherwise, pass through the resulting points and message.
817
- */
818
- function scoreExpression(userInput, rubric, locale) {
819
- const options = _.clone(rubric);
820
- _.extend(options, {
821
- decimal_separator: getDecimalSeparator(locale)
822
- });
823
- const createValidator = answer => {
824
- // We give options to KAS.parse here because it is parsing the
825
- // solution answer, not the student answer, and we don't want a
826
- // solution to work if the student is using a different language
827
- // (different from the content creation language, ie. English).
828
- const expression = KAS.parse(answer.value, rubric);
829
- // An answer may not be parsed if the expression was defined
830
- // incorrectly. For example if the answer is using a symbol defined
831
- // in the function variables list for the expression.
832
- if (!expression.parsed) {
833
- /* c8 ignore next */
834
- throw new PerseusError("Unable to parse solution answer for expression", Errors.InvalidInput, {
835
- metadata: {
836
- rubric: JSON.stringify(rubric)
837
- }
838
- });
839
- }
840
- return KhanAnswerTypes.expression.createValidatorFunctional(expression.expr, _({}).extend(options, {
841
- simplify: answer.simplify,
842
- form: answer.form
843
- }));
844
- };
845
-
846
- // Find the first answer form that matches the user's input and that
847
- // is considered correct. Also, track whether the input is
848
- // considered "empty" for all answer forms, and keep the validation
849
- // result for the first answer form for which the user's input was
850
- // considered "ungraded".
851
- // (Terminology reminder: the answer forms are provided by the
852
- // assessment items; they are not the user's input. Each one might
853
- // represent a correct answer, an incorrect one (if the exercise
854
- // creator has predicted certain common wrong answers and wants to
855
- // provide guidance via a message), or an ungraded one (same idea,
856
- // but without giving the user an incorrect mark for the question).
857
- let matchingAnswerForm;
858
- let matchMessage;
859
- let allEmpty = true;
860
- let firstUngradedResult;
861
- for (const answerForm of rubric.answerForms || []) {
862
- const validator = createValidator(answerForm);
863
- if (!validator) {
864
- continue;
865
- }
866
- const result = validator(userInput);
867
-
868
- // Short-circuit as soon as the user's input matches some answer
869
- // (independently of whether the answer is correct)
870
- if (result.correct) {
871
- matchingAnswerForm = answerForm;
872
- matchMessage = result.message || "";
873
- break;
874
- }
875
- allEmpty = allEmpty && result.empty;
876
- // If this answer form is correct and the user's input is considered
877
- // "ungraded" for it, we'll want to keep the evaluation result for
878
- // later. If the user's input doesn't match any answer forms, we'll
879
- // show the message from this validation.
880
- if (answerForm.considered === "correct" && result.ungraded && !firstUngradedResult) {
881
- firstUngradedResult = result;
882
- }
883
- }
884
-
885
- // Now check to see if we matched any answer form at all, and if
886
- // we did, whether it's considered correct, incorrect, or ungraded
887
- if (!matchingAnswerForm) {
888
- if (firstUngradedResult) {
889
- // While we didn't directly match with any answer form, we
890
- // did at some point get an "ungraded" validation result,
891
- // which might indicate e.g. a mismatch in variable casing.
892
- // We'll return "invalid", which will let the user try again
893
- // with no penalty, and the hopefully helpful validation
894
- // message.
895
- return {
896
- type: "invalid",
897
- message: firstUngradedResult.message,
898
- suppressAlmostThere: firstUngradedResult.suppressAlmostThere
899
- };
900
- }
901
- if (allEmpty) {
902
- // If everything graded as empty, it's invalid.
903
- return {
904
- type: "invalid",
905
- message: null
906
- };
907
- }
908
- // We fell through all the possibilities and we're not empty,
909
- // so the answer is considered incorrect.
910
- return {
911
- type: "points",
912
- earned: 0,
913
- total: 1
914
- };
915
- }
916
- if (matchingAnswerForm.considered === "ungraded") {
917
- return {
918
- type: "invalid",
919
- message: matchMessage
920
- };
921
- }
922
- // We matched a graded answer form, so we can now tell the user
923
- // whether their input was correct or incorrect, and hand out
924
- // points accordingly
925
- return {
926
- type: "points",
927
- earned: matchingAnswerForm.considered === "correct" ? 1 : 0,
928
- total: 1,
929
- message: matchMessage
930
- };
931
- }
932
-
933
- /**
934
- * Checks user input from the expression widget to see if it is scorable.
935
- *
936
- * Note: Most of the expression widget's validation requires the Rubric because
937
- * of its use of KhanAnswerTypes as a core part of scoring.
938
- *
939
- * @see `scoreExpression()` for more details.
940
- */
941
- function validateExpression(userInput) {
942
- if (userInput === "") {
943
- return {
944
- type: "invalid",
945
- message: null
946
- };
947
- }
948
- return null;
949
- }
950
-
951
- function getCoefficientsByType(data) {
952
- if (data.coords == null) {
953
- return undefined;
954
- }
955
- if (data.type === "exponential" || data.type === "logarithm") {
956
- const grader = GrapherUtil.functionForType(data.type);
957
- return grader.getCoefficients(data.coords, data.asymptote);
958
- } else if (data.type === "linear" || data.type === "quadratic" || data.type === "absolute_value" || data.type === "sinusoid" || data.type === "tangent") {
959
- const grader = GrapherUtil.functionForType(data.type);
960
- return grader.getCoefficients(data.coords);
961
- } else {
962
- throw new PerseusError("Invalid grapher type", Errors.InvalidInput);
963
- }
964
- }
965
- function scoreGrapher(userInput, rubric) {
966
- if (userInput.type !== rubric.correct.type) {
967
- return {
968
- type: "points",
969
- earned: 0,
970
- total: 1,
971
- message: null
972
- };
973
- }
974
-
975
- // We haven't moved the coords
976
- if (userInput.coords == null) {
977
- return {
978
- type: "invalid",
979
- message: null
980
- };
981
- }
982
-
983
- // Get new function handler for grading
984
- const grader = GrapherUtil.functionForType(userInput.type);
985
- const guessCoeffs = getCoefficientsByType(userInput);
986
- const correctCoeffs = getCoefficientsByType(rubric.correct);
987
- if (guessCoeffs == null || correctCoeffs == null) {
988
- return {
989
- type: "invalid",
990
- message: null
991
- };
992
- }
993
- if (grader.areEqual(guessCoeffs, correctCoeffs)) {
994
- return {
995
- type: "points",
996
- earned: 1,
997
- total: 1,
998
- message: null
999
- };
1000
- }
1001
- return {
1002
- type: "points",
1003
- earned: 0,
1004
- total: 1,
1005
- message: null
1006
- };
1007
- }
1008
-
1009
- // TODO: merge this with scoreCSProgram, it's the same code
1010
- function scoreIframe(userInput) {
1011
- // The iframe can tell us whether it's correct or incorrect,
1012
- // and pass an optional message
1013
- if (userInput.status === "correct") {
1014
- return {
1015
- type: "points",
1016
- earned: 1,
1017
- total: 1,
1018
- message: userInput.message || null
1019
- };
1020
- }
1021
- if (userInput.status === "incorrect") {
1022
- return {
1023
- type: "points",
1024
- earned: 0,
1025
- total: 1,
1026
- message: userInput.message || null
1027
- };
1028
- }
1029
- return {
1030
- type: "invalid",
1031
- message: "Keep going, you're not there yet!"
1032
- };
1033
- }
1034
-
1035
- const {
1036
- collinear,
1037
- canonicalSineCoefficients,
1038
- similar,
1039
- clockwise
1040
- } = geometry;
1041
- const {
1042
- getClockwiseAngle
1043
- } = angles;
1044
- const {
1045
- getSinusoidCoefficients,
1046
- getQuadraticCoefficients
1047
- } = coefficients;
1048
- function scoreInteractiveGraph(userInput, rubric) {
1049
- // None-type graphs are not graded
1050
- if (userInput.type === "none" && rubric.correct.type === "none") {
1051
- return {
1052
- type: "points",
1053
- earned: 0,
1054
- total: 0,
1055
- message: null
1056
- };
1057
- }
1058
-
1059
- // When nothing has moved, there will neither be coords nor the
1060
- // circle's center/radius fields. When those fields are absent, skip
1061
- // all these checks; just go mark the answer as empty.
1062
- const hasValue = Boolean(
1063
- // @ts-expect-error - TS2339 - Property 'coords' does not exist on type 'PerseusGraphType'.
1064
- userInput.coords ||
1065
- // @ts-expect-error - TS2339 - Property 'center' does not exist on type 'PerseusGraphType'. | TS2339 - Property 'radius' does not exist on type 'PerseusGraphType'.
1066
- userInput.center && userInput.radius);
1067
- if (userInput.type === rubric.correct.type && hasValue) {
1068
- if (userInput.type === "linear" && rubric.correct.type === "linear" && userInput.coords != null) {
1069
- const guess = userInput.coords;
1070
- const correct = rubric.correct.coords;
1071
-
1072
- // If both of the guess points are on the correct line, it's
1073
- // correct.
1074
- if (collinear(correct[0], correct[1], guess[0]) && collinear(correct[0], correct[1], guess[1])) {
1075
- return {
1076
- type: "points",
1077
- earned: 1,
1078
- total: 1,
1079
- message: null
1080
- };
1081
- }
1082
- } else if (userInput.type === "linear-system" && rubric.correct.type === "linear-system" && userInput.coords != null) {
1083
- const guess = userInput.coords;
1084
- const correct = rubric.correct.coords;
1085
- if (collinear(correct[0][0], correct[0][1], guess[0][0]) && collinear(correct[0][0], correct[0][1], guess[0][1]) && collinear(correct[1][0], correct[1][1], guess[1][0]) && collinear(correct[1][0], correct[1][1], guess[1][1]) || collinear(correct[0][0], correct[0][1], guess[1][0]) && collinear(correct[0][0], correct[0][1], guess[1][1]) && collinear(correct[1][0], correct[1][1], guess[0][0]) && collinear(correct[1][0], correct[1][1], guess[0][1])) {
1086
- return {
1087
- type: "points",
1088
- earned: 1,
1089
- total: 1,
1090
- message: null
1091
- };
1092
- }
1093
- } else if (userInput.type === "quadratic" && rubric.correct.type === "quadratic" && userInput.coords != null) {
1094
- // If the parabola coefficients match, it's correct.
1095
- const guessCoeffs = getQuadraticCoefficients(userInput.coords);
1096
- const correctCoeffs = getQuadraticCoefficients(rubric.correct.coords);
1097
- if (approximateDeepEqual(guessCoeffs, correctCoeffs)) {
1098
- return {
1099
- type: "points",
1100
- earned: 1,
1101
- total: 1,
1102
- message: null
1103
- };
1104
- }
1105
- } else if (userInput.type === "sinusoid" && rubric.correct.type === "sinusoid" && userInput.coords != null) {
1106
- const guessCoeffs = getSinusoidCoefficients(userInput.coords);
1107
- const correctCoeffs = getSinusoidCoefficients(rubric.correct.coords);
1108
- const canonicalGuessCoeffs = canonicalSineCoefficients(guessCoeffs);
1109
- const canonicalCorrectCoeffs = canonicalSineCoefficients(correctCoeffs);
1110
- // If the canonical coefficients match, it's correct.
1111
- if (approximateDeepEqual(canonicalGuessCoeffs, canonicalCorrectCoeffs)) {
1112
- return {
1113
- type: "points",
1114
- earned: 1,
1115
- total: 1,
1116
- message: null
1117
- };
1118
- }
1119
- } else if (userInput.type === "circle" && rubric.correct.type === "circle") {
1120
- if (approximateDeepEqual(userInput.center, rubric.correct.center) && approximateEqual(userInput.radius, rubric.correct.radius)) {
1121
- return {
1122
- type: "points",
1123
- earned: 1,
1124
- total: 1,
1125
- message: null
1126
- };
1127
- }
1128
- } else if (userInput.type === "point" && rubric.correct.type === "point" && userInput.coords != null) {
1129
- let correct = rubric.correct.coords;
1130
- if (correct == null) {
1131
- throw new Error("Point graph rubric has null coords");
1132
- }
1133
- const guess = userInput.coords.slice();
1134
- correct = correct.slice();
1135
- // Everything's already rounded so we shouldn't need to do an
1136
- // eq() comparison but _.isEqual(0, -0) is false, so we'll use
1137
- // eq() anyway. The sort should be fine because it'll stringify
1138
- // it and -0 converted to a string is "0"
1139
- guess == null || guess.sort();
1140
- // @ts-expect-error - TS2339 - Property 'sort' does not exist on type 'readonly Coord[]'.
1141
- correct.sort();
1142
- if (approximateDeepEqual(guess, correct)) {
1143
- return {
1144
- type: "points",
1145
- earned: 1,
1146
- total: 1,
1147
- message: null
1148
- };
1149
- }
1150
- } else if (userInput.type === "polygon" && rubric.correct.type === "polygon" && userInput.coords != null) {
1151
- const guess = userInput.coords.slice();
1152
- const correct = rubric.correct.coords.slice();
1153
- let match;
1154
- if (rubric.correct.match === "similar") {
1155
- match = similar(guess, correct, Number.POSITIVE_INFINITY);
1156
- } else if (rubric.correct.match === "congruent") {
1157
- match = similar(guess, correct, number.DEFAULT_TOLERANCE);
1158
- } else if (rubric.correct.match === "approx") {
1159
- match = similar(guess, correct, 0.1);
1160
- } else {
1161
- /* exact */
1162
- guess.sort();
1163
- correct.sort();
1164
- match = approximateDeepEqual(guess, correct);
1165
- }
1166
- if (match) {
1167
- return {
1168
- type: "points",
1169
- earned: 1,
1170
- total: 1,
1171
- message: null
1172
- };
1173
- }
1174
- } else if (userInput.type === "segment" && rubric.correct.type === "segment" && userInput.coords != null) {
1175
- let guess = deepClone(userInput.coords);
1176
- let correct = deepClone(rubric.correct.coords);
1177
- guess = _.invoke(guess, "sort").sort();
1178
- correct = _.invoke(correct, "sort").sort();
1179
- if (approximateDeepEqual(guess, correct)) {
1180
- return {
1181
- type: "points",
1182
- earned: 1,
1183
- total: 1,
1184
- message: null
1185
- };
1186
- }
1187
- } else if (userInput.type === "ray" && rubric.correct.type === "ray" && userInput.coords != null) {
1188
- const guess = userInput.coords;
1189
- const correct = rubric.correct.coords;
1190
- if (approximateDeepEqual(guess[0], correct[0]) && collinear(correct[0], correct[1], guess[1])) {
1191
- return {
1192
- type: "points",
1193
- earned: 1,
1194
- total: 1,
1195
- message: null
1196
- };
1197
- }
1198
- } else if (userInput.type === "angle" && rubric.correct.type === "angle") {
1199
- const coords = userInput.coords;
1200
- const correct = rubric.correct.coords;
1201
- const allowReflexAngles = rubric.correct.allowReflexAngles;
1202
-
1203
- // While the angle graph should always have 3 points, our types
1204
- // technically allow for null values. We'll check for that here.
1205
- // TODO: (LEMS-2857) We would like to update the type of coords
1206
- // to be non-nullable, as the graph should always have 3 points.
1207
- if (!coords) {
1208
- return {
1209
- type: "invalid",
1210
- message: null
1211
- };
1212
- }
1213
-
1214
- // We need to check both the direction of the angle and the
1215
- // whether the graph allows for reflexive angles in order to
1216
- // to determine if we need to reverse the coords for scoring.
1217
- const areClockwise = clockwise([coords[0], coords[2], coords[1]]);
1218
- const shouldReverseCoords = areClockwise && !allowReflexAngles;
1219
- const guess = shouldReverseCoords ? coords.slice().reverse() : coords;
1220
- let match;
1221
- if (rubric.correct.match === "congruent") {
1222
- const angles = _.map([guess, correct], function (coords) {
1223
- if (!coords) {
1224
- return false;
1225
- }
1226
- const angle = getClockwiseAngle(coords, allowReflexAngles);
1227
- return angle;
1228
- });
1229
- // @ts-expect-error - TS2556 - A spread argument must either have a tuple type or be passed to a rest parameter.
1230
- match = approximateEqual(...angles);
1231
- } else {
1232
- /* exact */
1233
- match = approximateDeepEqual(guess[1], correct[1]) && collinear(correct[1], correct[0], guess[0]) && collinear(correct[1], correct[2], guess[2]);
1234
- }
1235
- if (match) {
1236
- return {
1237
- type: "points",
1238
- earned: 1,
1239
- total: 1,
1240
- message: null
1241
- };
1242
- }
1243
- }
1244
- }
1245
-
1246
- // The input wasn't correct, so check if it's a blank input or if it's
1247
- // actually just wrong
1248
- if (!hasValue || _.isEqual(userInput, rubric.graph)) {
1249
- // We're where we started.
1250
- return {
1251
- type: "invalid",
1252
- message: null
1253
- };
1254
- }
1255
- return {
1256
- type: "points",
1257
- earned: 0,
1258
- total: 1,
1259
- message: null
1260
- };
1261
- }
1262
-
1263
- // Question state for marker as result of user selected answers.
1264
-
1265
- function scoreLabelImageMarker(userInput, rubric) {
1266
- const score = {
1267
- hasAnswers: false,
1268
- isCorrect: false
1269
- };
1270
- if (userInput && userInput.length > 0) {
1271
- score.hasAnswers = true;
1272
- }
1273
- if (rubric.length > 0) {
1274
- if (userInput && userInput.length === rubric.length) {
1275
- // All correct answers are selected by the user.
1276
- score.isCorrect = userInput.every(choice => rubric.includes(choice));
1277
- }
1278
- } else if (!userInput || userInput.length === 0) {
1279
- // Correct as no answers should be selected by the user.
1280
- score.isCorrect = true;
1281
- }
1282
- return score;
1283
- }
1284
- function scoreLabelImage(userInput, rubric) {
1285
- let numCorrect = 0;
1286
- for (let i = 0; i < userInput.markers.length; i++) {
1287
- const score = scoreLabelImageMarker(userInput.markers[i].selected, rubric.markers[i].answers);
1288
- if (score.isCorrect) {
1289
- numCorrect++;
1290
- }
1291
- }
1292
- return {
1293
- type: "points",
1294
- // Markers with no expected answers are graded as correct if user
1295
- // makes no answer selection.
1296
- earned: numCorrect === userInput.markers.length ? 1 : 0,
1297
- total: 1,
1298
- message: null
1299
- };
1300
- }
1301
-
1302
- function scoreMatcher(userInput, rubric) {
1303
- const correct = _.isEqual(userInput.left, rubric.left) && _.isEqual(userInput.right, rubric.right);
1304
- return {
1305
- type: "points",
1306
- earned: correct ? 1 : 0,
1307
- total: 1,
1308
- message: null
1309
- };
1310
- }
1311
-
1312
- function scoreMatrix(userInput, rubric) {
1313
- const solution = rubric.answers;
1314
- const supplied = userInput.answers;
1315
- const solutionSize = getMatrixSize(solution);
1316
- const suppliedSize = getMatrixSize(supplied);
1317
- const incorrectSize = solutionSize[0] !== suppliedSize[0] || solutionSize[1] !== suppliedSize[1];
1318
- const createValidator = KhanAnswerTypes.number.createValidatorFunctional;
1319
- let message = null;
1320
- let incorrect = false;
1321
- _(suppliedSize[0]).times(row => {
1322
- _(suppliedSize[1]).times(col => {
1323
- if (!incorrectSize) {
1324
- const validator = createValidator(
1325
- // @ts-expect-error - TS2345 - Argument of type 'number' is not assignable to parameter of type 'string'.
1326
- solution[row][col], {
1327
- simplify: true
1328
- });
1329
- const result = validator(supplied[row][col]);
1330
- if (result.message) {
1331
- // @ts-expect-error - TS2322 - Type 'string' is not assignable to type 'null'.
1332
- message = result.message;
1333
- }
1334
- if (!result.correct) {
1335
- incorrect = true;
1336
- }
1337
- }
1338
- });
1339
- });
1340
- if (incorrectSize) {
1341
- return {
1342
- type: "points",
1343
- earned: 0,
1344
- total: 1,
1345
- message: null
1346
- };
1347
- }
1348
- return {
1349
- type: "points",
1350
- earned: incorrect ? 0 : 1,
1351
- total: 1,
1352
- message: message
1353
- };
1354
- }
1355
-
1356
- /**
1357
- * Checks user input from the matrix widget to see if it is scorable.
1358
- *
1359
- * Note: The matrix widget cannot do much validation without the Scoring
1360
- * Data because of its use of KhanAnswerTypes as a core part of scoring.
1361
- *
1362
- * @see `scoreMatrix()` for more details.
1363
- */
1364
- function validateMatrix(userInput) {
1365
- const supplied = userInput.answers;
1366
- const suppliedSize = getMatrixSize(supplied);
1367
- for (let row = 0; row < suppliedSize[0]; row++) {
1368
- for (let col = 0; col < suppliedSize[1]; col++) {
1369
- if (supplied[row][col] == null || supplied[row][col].toString().length === 0) {
1370
- return {
1371
- type: "invalid",
1372
- message: ErrorCodes.FILL_ALL_CELLS_ERROR
1373
- };
1374
- }
1375
- }
1376
- }
1377
- return null;
1378
- }
1379
-
1380
- function scoreNumberLine(userInput, rubric) {
1381
- const range = rubric.range;
1382
- const start = rubric.initialX != null ? rubric.initialX : range[0];
1383
- const startRel = rubric.isInequality ? "ge" : "eq";
1384
- const correctRel = rubric.correctRel || "eq";
1385
- const correctPos = number.equal(userInput.numLinePosition, rubric.correctX || 0);
1386
- if (correctPos && correctRel === userInput.rel) {
1387
- return {
1388
- type: "points",
1389
- earned: 1,
1390
- total: 1,
1391
- message: null
1392
- };
1393
- }
1394
- if (userInput.numLinePosition === start && userInput.rel === startRel) {
1395
- // We're where we started.
1396
- return {
1397
- type: "invalid",
1398
- message: null
1399
- };
1400
- }
1401
- return {
1402
- type: "points",
1403
- earned: 0,
1404
- total: 1,
1405
- message: null
1406
- };
1407
- }
1408
-
1409
- /**
1410
- * Checks user input is within the allowed range and not the same as the initial
1411
- * state.
1412
- * @param userInput
1413
- * @see 'scoreNumberLine' for the scoring logic.
1414
- */
1415
- function validateNumberLine(userInput) {
1416
- const divisionRange = userInput.divisionRange;
1417
- const outsideAllowedRange = userInput.numDivisions > divisionRange[1] || userInput.numDivisions < divisionRange[0];
1418
-
1419
- // TODO: I don't think isTickCrtl is a thing anymore
1420
- if (userInput.isTickCrtl && outsideAllowedRange) {
1421
- return {
1422
- type: "invalid",
1423
- message: "Number of divisions is outside the allowed range."
1424
- };
1425
- }
1426
- return null;
1427
- }
1428
-
1429
- /*
1430
- * In this file, an `expression` is some portion of valid TeX enclosed in
1431
- * curly brackets.
1432
- */
1433
-
1434
- /*
1435
- * Find the index at which an expression ends, i.e., has an unmatched
1436
- * closing curly bracket. This method assumes that we start with a non-open
1437
- * bracket character and end when we've seen more left than right brackets
1438
- * (rather than assuming that we start with a bracket character and wait for
1439
- * bracket equality).
1440
- */
1441
- function findEndpoint(tex, currentIndex) {
1442
- let bracketDepth = 0;
1443
- for (let i = currentIndex, len = tex.length; i < len; i++) {
1444
- const c = tex[i];
1445
- if (c === "{") {
1446
- bracketDepth++;
1447
- } else if (c === "}") {
1448
- bracketDepth--;
1449
- }
1450
- if (bracketDepth < 0) {
1451
- return i;
1452
- }
1453
- }
1454
- // If we never see unbalanced curly brackets, default to the
1455
- // entire string
1456
- return tex.length;
1457
- }
1458
-
1459
- /*
1460
- * Parses an individual set of curly brackets into TeX.
1461
- */
1462
- function parseNextExpression(tex, currentIndex, handler) {
1463
- // Find the first '{' and grab subsequent TeX
1464
- // Ex) tex: '{3}{7}', and we want the '3'
1465
- const openBracketIndex = tex.indexOf("{", currentIndex);
1466
-
1467
- // If there is no open bracket, set the endpoint to the end of the string
1468
- // and the expression to an empty string. This helps ensure we don't
1469
- // get stuck in an infinite loop when users handtype TeX.
1470
- if (openBracketIndex === -1) {
1471
- return {
1472
- endpoint: tex.length,
1473
- expression: ""
1474
- };
1475
- }
1476
- const nextExpIndex = openBracketIndex + 1;
1477
-
1478
- // Truncate to only contain remaining TeX
1479
- const endpoint = findEndpoint(tex, nextExpIndex);
1480
- const expressionTeX = tex.substring(nextExpIndex, endpoint);
1481
- const parsedExp = walkTex(expressionTeX, handler);
1482
- return {
1483
- endpoint: endpoint,
1484
- expression: parsedExp
1485
- };
1486
- }
1487
- function getNextFracIndex(tex, currentIndex) {
1488
- const dfrac = "\\dfrac";
1489
- const frac = "\\frac";
1490
- const nextFrac = tex.indexOf(frac, currentIndex);
1491
- const nextDFrac = tex.indexOf(dfrac, currentIndex);
1492
- if (nextFrac > -1 && nextDFrac > -1) {
1493
- return Math.min(nextFrac, nextDFrac);
1494
- }
1495
- if (nextFrac > -1) {
1496
- return nextFrac;
1497
- }
1498
- if (nextDFrac > -1) {
1499
- return nextDFrac;
1500
- }
1501
- return -1;
1502
- }
1503
- function walkTex(tex, handler) {
1504
- if (!tex) {
1505
- return "";
1506
- }
1507
-
1508
- // Ex) tex: '2 \dfrac {3}{7}'
1509
- let parsedString = "";
1510
- let currentIndex = 0;
1511
- let nextFrac = getNextFracIndex(tex, currentIndex);
1512
-
1513
- // For each \dfrac, find the two expressions (wrapped in {}) and recur
1514
- while (nextFrac > -1) {
1515
- // Gather first fragment, preceding \dfrac
1516
- // Ex) parsedString: '2 '
1517
- parsedString += tex.substring(currentIndex, nextFrac);
1518
-
1519
- // Remove everything preceding \dfrac, which has been parsed
1520
- currentIndex = nextFrac;
1521
-
1522
- // Parse first expression and move index past it
1523
- // Ex) firstParsedExpression.expression: '3'
1524
- const firstParsedExpression = parseNextExpression(tex, currentIndex, handler);
1525
- currentIndex = firstParsedExpression.endpoint + 1;
1526
-
1527
- // Parse second expression
1528
- // Ex) secondParsedExpression.expression: '7'
1529
- const secondParsedExpression = parseNextExpression(tex, currentIndex, handler);
1530
- currentIndex = secondParsedExpression.endpoint + 1;
1531
-
1532
- // Add expressions to running total of parsed expressions
1533
- if (parsedString.length) {
1534
- parsedString += " ";
1535
- }
1536
-
1537
- // Apply a custom handler based on the parsed subexpressions
1538
- parsedString += handler(firstParsedExpression.expression, secondParsedExpression.expression);
1539
-
1540
- // Find next DFrac, relative to currentIndex
1541
- nextFrac = getNextFracIndex(tex, currentIndex);
1542
- }
1543
-
1544
- // Add remaining TeX, which is \dfrac-free
1545
- parsedString += tex.slice(currentIndex);
1546
- return parsedString;
1547
- }
1548
-
1549
- /*
1550
- * Parse a TeX expression into something interpretable by input-number.
1551
- * The process is concerned with: (1) parsing fractions, i.e., \dfracs; and
1552
- * (2) removing backslash-escaping from certain characters (right now, only
1553
- * percent signs).
1554
- *
1555
- * The basic algorithm for handling \dfracs splits on \dfracs and then recurs
1556
- * on the subsequent "expressions", i.e., the {} pairs that follow \dfrac. The
1557
- * recursion is to allow for nested \dfrac elements.
1558
- *
1559
- * Backslash-escapes are removed with a simple search-and-replace.
1560
- */
1561
- function parseTex(tex) {
1562
- const handler = function handler(exp1, exp2) {
1563
- return exp1 + "/" + exp2;
1564
- };
1565
- const texWithoutFracs = walkTex(tex, handler);
1566
- return texWithoutFracs.replace("\\%", "%");
1567
- }
1568
-
1569
- const answerFormButtons = [{
1570
- title: "Integers",
1571
- value: "integer",
1572
- content: "6"
1573
- }, {
1574
- title: "Decimals",
1575
- value: "decimal",
1576
- content: "0.75"
1577
- }, {
1578
- title: "Proper fractions",
1579
- value: "proper",
1580
- content: "\u2157"
1581
- }, {
1582
- title: "Improper fractions",
1583
- value: "improper",
1584
- content: "\u2077\u2044\u2084"
1585
- }, {
1586
- title: "Mixed numbers",
1587
- value: "mixed",
1588
- content: "1\u00BE"
1589
- }, {
1590
- title: "Numbers with \u03C0",
1591
- value: "pi",
1592
- content: "\u03C0"
1593
- }];
1594
-
1595
- // This function checks if the user inputted a percent value, parsing
1596
- // it as a number (and maybe scaling) so that it can be graded.
1597
- // NOTE(michaelpolyak): Unlike `KhanAnswerTypes.number.percent()` which
1598
- // can accept several input forms with or without "%", the decision
1599
- // to parse based on the presence of "%" in the input, is so that we
1600
- // don't accidently scale the user typed value before grading, CP-930.
1601
- function maybeParsePercentInput(inputValue, normalizedAnswerExpected) {
1602
- // If the input value is not a string ending with "%", then there's
1603
- // nothing more to do. The value will be graded as inputted by user.
1604
- if (!(typeof inputValue === "string" && inputValue.endsWith("%"))) {
1605
- return inputValue;
1606
- }
1607
- const value = parseFloat(inputValue.slice(0, -1));
1608
- // If the input value stripped of the "%" cannot be parsed as a
1609
- // number (the slice is not really necessary for parseFloat to work
1610
- // if the string starts with a number) then return the original
1611
- // input for grading.
1612
- if (isNaN(value)) {
1613
- return inputValue;
1614
- }
1615
-
1616
- // Next, if all correct answers are in the range of |0,1| then we
1617
- // scale the user typed value. We assume this is the correct thing
1618
- // to do since the input value ends with "%".
1619
- if (normalizedAnswerExpected) {
1620
- return value / 100;
1621
- }
1622
-
1623
- // Otherwise, we return input value (number) stripped of the "%".
1624
- return value;
1625
- }
1626
- function scoreNumericInput(userInput, rubric) {
1627
- var _matchedAnswer$messag;
1628
- const defaultAnswerForms = answerFormButtons.map(e => e["value"])
1629
- // Don't default to validating the answer as a pi answer
1630
- // if answerForm isn't set on the answer
1631
- // https://khanacademy.atlassian.net/browse/LC-691
1632
- .filter(e => e !== "pi");
1633
- const createValidator = answer => {
1634
- var _answer$answerForms;
1635
- const stringAnswer = `${answer.value}`;
1636
-
1637
- // Always validate against the provided answer forms (pi, decimal, etc.)
1638
- const validatorForms = [...((_answer$answerForms = answer.answerForms) != null ? _answer$answerForms : [])];
1639
-
1640
- // When an answer is set to strict, we validate using ONLY
1641
- // the provided answerForms. If strict is false, or if there
1642
- // were no provided answer forms, we will include all
1643
- // of the default answer forms in our validator.
1644
- if (!answer.strict || validatorForms.length === 0) {
1645
- validatorForms.push(...defaultAnswerForms);
1646
- }
1647
- return KhanAnswerTypes.number.createValidatorFunctional(stringAnswer, {
1648
- message: answer.message,
1649
- simplify: answer.status === "correct" ? answer.simplify : "optional",
1650
- inexact: true,
1651
- // TODO(merlob) backfill / delete
1652
- maxError: answer.maxError,
1653
- forms: validatorForms
1654
- });
1655
- };
1656
-
1657
- // We may have received TeX; try to parse it before grading.
1658
- // If `currentValue` is not TeX, this should be a no-op.
1659
- const currentValue = parseTex(userInput.currentValue);
1660
- const normalizedAnswerExpected = rubric.answers.filter(answer => answer.status === "correct").every(answer => answer.value != null && Math.abs(answer.value) <= 1);
1661
-
1662
- // The coefficient is an attribute of the widget
1663
- let localValue = currentValue;
1664
- if (rubric.coefficient) {
1665
- if (!localValue) {
1666
- localValue = 1;
1667
- } else if (localValue === "-") {
1668
- localValue = -1;
1669
- }
1670
- }
1671
- const matchedAnswer = rubric.answers.map(answer => {
1672
- const validateFn = createValidator(answer);
1673
- const score = validateFn(maybeParsePercentInput(localValue, normalizedAnswerExpected));
1674
- return _extends({}, answer, {
1675
- score
1676
- });
1677
- }).find(answer => {
1678
- // NOTE: "answer.score.correct" indicates a match via the validate function.
1679
- // It does NOT indicate that the answer itself is correct.
1680
- return answer.score.correct || answer.status === "correct" && answer.score.empty;
1681
- });
1682
- const result = (matchedAnswer == null ? void 0 : matchedAnswer.status) === "correct" ? matchedAnswer.score : {
1683
- empty: (matchedAnswer == null ? void 0 : matchedAnswer.status) === "ungraded",
1684
- correct: (matchedAnswer == null ? void 0 : matchedAnswer.status) === "correct",
1685
- message: (_matchedAnswer$messag = matchedAnswer == null ? void 0 : matchedAnswer.message) != null ? _matchedAnswer$messag : null,
1686
- guess: localValue
1687
- };
1688
- if (result.empty) {
1689
- return {
1690
- type: "invalid",
1691
- message: result.message
1692
- };
1693
- }
1694
- return {
1695
- type: "points",
1696
- earned: result.correct ? 1 : 0,
1697
- total: 1,
1698
- message: result.message
1699
- };
1700
- }
1701
-
1702
- function scoreOrderer(userInput, rubric) {
1703
- const correct = _.isEqual(userInput.current, rubric.correctOptions.map(option => option.content));
1704
- return {
1705
- type: "points",
1706
- earned: correct ? 1 : 0,
1707
- total: 1,
1708
- message: null
1709
- };
1710
- }
1711
-
1712
- /**
1713
- * Checks user input from the orderer widget to see if the user has started
1714
- * ordering the options, making the widget scorable.
1715
- * @param userInput
1716
- * @see `scoreOrderer` for more details.
1717
- */
1718
- function validateOrderer(userInput) {
1719
- if (userInput.current.length === 0) {
1720
- return {
1721
- type: "invalid",
1722
- message: null
1723
- };
1724
- }
1725
- return null;
1726
- }
1727
-
1728
- function scorePlotter(userInput, rubric) {
1729
- return {
1730
- type: "points",
1731
- earned: approximateDeepEqual(userInput, rubric.correct) ? 1 : 0,
1732
- total: 1,
1733
- message: null
1734
- };
1735
- }
1736
-
1737
- /**
1738
- * Checks user input to confirm it is not the same as the starting values for the graph.
1739
- * This means the user has modified the graph, and the question can be scored.
1740
- *
1741
- * @see 'scorePlotter' for more details on scoring.
1742
- */
1743
- function validatePlotter(userInput, validationData) {
1744
- if (approximateDeepEqual(userInput, validationData.starting)) {
1745
- return {
1746
- type: "invalid",
1747
- message: null
1748
- };
1749
- }
1750
- return null;
1751
- }
1752
-
1753
- function scoreRadio(userInput, rubric) {
1754
- const numSelected = userInput.choicesSelected.reduce((sum, selected) => {
1755
- return sum + (selected ? 1 : 0);
1756
- }, 0);
1757
- const numCorrect = rubric.choices.reduce((sum, currentChoice) => {
1758
- return currentChoice.correct ? sum + 1 : sum;
1759
- }, 0);
1760
- if (numCorrect > 1 && numSelected !== numCorrect) {
1761
- return {
1762
- type: "invalid",
1763
- message: ErrorCodes.CHOOSE_CORRECT_NUM_ERROR
1764
- };
1765
- // If NOTA and some other answer are checked, ...
1766
- }
1767
- const noneOfTheAboveSelected = rubric.choices.some((choice, index) => choice.isNoneOfTheAbove && userInput.choicesSelected[index]);
1768
- if (noneOfTheAboveSelected && numSelected > 1) {
1769
- return {
1770
- type: "invalid",
1771
- message: ErrorCodes.NOT_NONE_ABOVE_ERROR
1772
- };
1773
- }
1774
- const correct = userInput.choicesSelected.every((selected, i) => {
1775
- let isCorrect;
1776
- if (rubric.choices[i].isNoneOfTheAbove) {
1777
- isCorrect = rubric.choices.every((choice, j) => {
1778
- return i === j || !choice.correct;
1779
- });
1780
- } else {
1781
- isCorrect = !!rubric.choices[i].correct;
1782
- }
1783
- return isCorrect === selected;
1784
- });
1785
- return {
1786
- type: "points",
1787
- earned: correct ? 1 : 0,
1788
- total: 1,
1789
- message: null
1790
- };
1791
- }
1792
-
1793
- /**
1794
- * Checks if the user has selected at least one option. Additional validation
1795
- * is done in scoreRadio to check if the number of selected options is correct
1796
- * and if the user has selected both a correct option and the "none of the above"
1797
- * option.
1798
- * @param userInput
1799
- * @see `scoreRadio` for the additional validation logic and the scoring logic.
1800
- */
1801
- function validateRadio(userInput) {
1802
- const numSelected = userInput.choicesSelected.reduce((sum, selected) => {
1803
- return sum + (selected ? 1 : 0);
1804
- }, 0);
1805
- if (numSelected === 0) {
1806
- return {
1807
- type: "invalid",
1808
- message: null
1809
- };
1810
- }
1811
- return null;
1812
- }
1813
-
1814
- function scoreSorter(userInput, rubric) {
1815
- const correct = approximateDeepEqual(userInput.options, rubric.correct);
1816
- return {
1817
- type: "points",
1818
- earned: correct ? 1 : 0,
1819
- total: 1,
1820
- message: null
1821
- };
1822
- }
1823
-
1824
- /**
1825
- * Checks user input for the sorter widget to ensure that the user has made
1826
- * changes before attempting to score the widget.
1827
- * @param userInput
1828
- * @see 'scoreSorter' in 'packages/perseus/src/widgets/sorter/score-sorter.ts'
1829
- * for more details on how the sorter widget is scored.
1830
- */
1831
- function validateSorter(userInput) {
1832
- // If the sorter widget hasn't been changed yet, we treat it as "empty" which
1833
- // prevents the "Check" button from becoming active. We want the user
1834
- // to make a change before trying to move forward. This makes an
1835
- // assumption that the initial order isn't the correct order! However,
1836
- // this should be rare if it happens, and interacting with the list
1837
- // will enable the button, so they won't be locked out of progressing.
1838
- if (!userInput.changed) {
1839
- return {
1840
- type: "invalid",
1841
- message: null
1842
- };
1843
- }
1844
- return null;
1845
- }
1846
-
1847
- /**
1848
- * Filters the given table (modelled as a 2D array) to remove any rows that are
1849
- * completely empty.
1850
- *
1851
- * @returns A new table with only non-empty rows.
1852
- */
1853
- const filterNonEmpty = function filterNonEmpty(table) {
1854
- return table.filter(function (row) {
1855
- // Return only rows that are non-empty.
1856
- return row.some(cell => cell);
1857
- });
1858
- };
1859
-
1860
- function validateTable(userInput) {
1861
- const supplied = filterNonEmpty(userInput);
1862
- const hasEmptyCell = supplied.some(function (row) {
1863
- return row.some(function (cell) {
1864
- return cell === "";
1865
- });
1866
- });
1867
- if (hasEmptyCell || !supplied.length) {
1868
- return {
1869
- type: "invalid",
1870
- message: null
1871
- };
1872
- }
1873
- return null;
1874
- }
1875
-
1876
- function scoreTable(userInput, rubric) {
1877
- const validationResult = validateTable(userInput);
1878
- if (validationResult != null) {
1879
- return validationResult;
1880
- }
1881
- const supplied = filterNonEmpty(userInput);
1882
- const solution = filterNonEmpty(rubric.answers);
1883
- if (supplied.length !== solution.length) {
1884
- return {
1885
- type: "points",
1886
- earned: 0,
1887
- total: 1,
1888
- message: null
1889
- };
1890
- }
1891
- const createValidator = KhanAnswerTypes.number.createValidatorFunctional;
1892
- let message = null;
1893
- const allCorrect = solution.every(function (rowSolution) {
1894
- for (let i = 0; i < supplied.length; i++) {
1895
- const rowSupplied = supplied[i];
1896
- const correct = rowSupplied.every(function (cellSupplied, i) {
1897
- const cellSolution = rowSolution[i];
1898
- const validator = createValidator(cellSolution, {
1899
- simplify: true
1900
- });
1901
- const result = validator(cellSupplied);
1902
- if (result.message) {
1903
- message = result.message;
1904
- }
1905
- return result.correct;
1906
- });
1907
- if (correct) {
1908
- supplied.splice(i, 1);
1909
- return true;
1910
- }
1911
- }
1912
- return false;
1913
- });
1914
- return {
1915
- type: "points",
1916
- earned: allCorrect ? 1 : 0,
1917
- total: 1,
1918
- message
1919
- };
1920
- }
1921
-
1922
- const inputNumberAnswerTypes = {
1923
- number: {
1924
- name: "Numbers",
1925
- forms: "integer, decimal, proper, improper, mixed"
1926
- },
1927
- decimal: {
1928
- name: "Decimals",
1929
- forms: "decimal"
1930
- },
1931
- integer: {
1932
- name: "Integers",
1933
- forms: "integer"
1934
- },
1935
- rational: {
1936
- name: "Fractions and mixed numbers",
1937
- forms: "integer, proper, improper, mixed"
1938
- },
1939
- improper: {
1940
- name: "Improper numbers (no mixed)",
1941
- forms: "integer, proper, improper"
1942
- },
1943
- mixed: {
1944
- name: "Mixed numbers (no improper)",
1945
- forms: "integer, proper, mixed"
1946
- },
1947
- percent: {
1948
- name: "Numbers or percents",
1949
- forms: "integer, decimal, proper, improper, mixed, percent"
1950
- },
1951
- pi: {
1952
- name: "Numbers with pi",
1953
- forms: "pi"
1954
- }
1955
- };
1956
- function scoreInputNumber(userInput, rubric) {
1957
- if (rubric.answerType == null) {
1958
- rubric.answerType = "number";
1959
- }
1960
-
1961
- // note(matthewc): this will get immediately parsed again by
1962
- // `KhanAnswerTypes.number.convertToPredicate`, but a string is
1963
- // expected here
1964
- const stringValue = `${rubric.value}`;
1965
- const val = KhanAnswerTypes.number.createValidatorFunctional(stringValue, {
1966
- simplify: rubric.simplify,
1967
- inexact: rubric.inexact || undefined,
1968
- maxError: rubric.maxError,
1969
- forms: inputNumberAnswerTypes[rubric.answerType].forms
1970
- });
1971
-
1972
- // We may have received TeX; try to parse it before grading.
1973
- // If `currentValue` is not TeX, this should be a no-op.
1974
- const currentValue = parseTex(userInput.currentValue);
1975
- const result = val(currentValue);
1976
- if (result.empty) {
1977
- return {
1978
- type: "invalid",
1979
- message: result.message
1980
- };
1981
- }
1982
- return {
1983
- type: "points",
1984
- earned: result.correct ? 1 : 0,
1985
- total: 1,
1986
- message: result.message
1987
- };
1988
- }
1989
-
1990
- /**
1991
- * Several widgets don't have "right"/"wrong" scoring logic,
1992
- * so this just says to move on past those widgets
1993
- *
1994
- * TODO(LEMS-2543) widgets that use this probably shouldn't have any
1995
- * scoring logic and the thing scoring an exercise
1996
- * should just know to skip these
1997
- */
1998
- function scoreNoop(points = 0) {
1999
- return {
2000
- type: "points",
2001
- earned: points,
2002
- total: points,
2003
- message: null
2004
- };
2005
- }
2006
-
2007
- // The `group` widget is basically a widget hosting a full Perseus system in
2008
- // it. As such, scoring a group means scoring all widgets it contains.
2009
- function scoreGroup(userInput, rubric, locale) {
2010
- const scores = scoreWidgetsFunctional(rubric.widgets, Object.keys(rubric.widgets), userInput, locale);
2011
- return flattenScores(scores);
2012
- }
2013
-
2014
- /**
2015
- * Checks the given user input to see if any answerable widgets have not been
2016
- * "filled in" (ie. if they're empty). Another way to think about this
2017
- * function is that its a check to see if we can score the provided input.
2018
- */
2019
- function emptyWidgetsFunctional(widgets,
2020
- // This is a port of old code, I'm not sure why
2021
- // we need widgetIds vs the keys of the widgets object
2022
- widgetIds, userInputMap, locale) {
2023
- return widgetIds.filter(id => {
2024
- const widget = widgets[id];
2025
- if (!widget || widget.static === true) {
2026
- // Static widgets shouldn't count as empty
2027
- return false;
2028
- }
2029
- const validator = getWidgetValidator(widget.type);
2030
- const userInput = userInputMap[id];
2031
- const validationData = widget.options;
2032
- const score = validator == null ? void 0 : validator(userInput, validationData, locale);
2033
- if (score) {
2034
- return scoreIsEmpty(score);
2035
- }
2036
- });
2037
- }
2038
-
2039
- function validateGroup(userInput, validationData, locale) {
2040
- const emptyWidgets = emptyWidgetsFunctional(validationData.widgets, Object.keys(validationData.widgets), userInput, locale);
2041
- if (emptyWidgets.length === 0) {
2042
- return null;
2043
- }
2044
- return {
2045
- type: "invalid",
2046
- message: null
2047
- };
2048
- }
2049
-
2050
- function validateLabelImage(userInput) {
2051
- let numAnswered = 0;
2052
- for (let i = 0; i < userInput.markers.length; i++) {
2053
- const userSelection = userInput.markers[i].selected;
2054
- if (userSelection && userSelection.length > 0) {
2055
- numAnswered++;
2056
- }
2057
- }
2058
- // We expect all question markers to be answered before grading.
2059
- if (numAnswered !== userInput.markers.length) {
2060
- return {
2061
- type: "invalid",
2062
- message: null
2063
- };
2064
- }
2065
- return null;
2066
- }
2067
-
2068
- function validateMockWidget(userInput) {
2069
- if (userInput.currentValue == null || userInput.currentValue === "") {
2070
- return {
2071
- type: "invalid",
2072
- message: ""
2073
- };
2074
- }
2075
- return null;
2076
- }
2077
-
2078
- function scoreMockWidget(userInput, rubric) {
2079
- const validationResult = validateMockWidget(userInput);
2080
- if (validationResult != null) {
2081
- return validationResult;
2082
- }
2083
- return {
2084
- type: "points",
2085
- earned: userInput.currentValue === rubric.value ? 1 : 0,
2086
- total: 1,
2087
- message: ""
2088
- };
2089
- }
2090
-
2091
- const widgets = {};
2092
- function registerWidget(type, scorer, validator) {
2093
- widgets[type] = {
2094
- scorer,
2095
- validator
2096
- };
2097
- }
2098
- const getWidgetValidator = name => {
2099
- var _widgets$name$validat, _widgets$name;
2100
- return (_widgets$name$validat = (_widgets$name = widgets[name]) == null ? void 0 : _widgets$name.validator) != null ? _widgets$name$validat : null;
2101
- };
2102
- const getWidgetScorer = name => {
2103
- var _widgets$name$scorer, _widgets$name2;
2104
- return (_widgets$name$scorer = (_widgets$name2 = widgets[name]) == null ? void 0 : _widgets$name2.scorer) != null ? _widgets$name$scorer : null;
2105
- };
2106
- registerWidget("categorizer", scoreCategorizer, validateCategorizer);
2107
- registerWidget("cs-program", scoreCSProgram);
2108
- registerWidget("dropdown", scoreDropdown, validateDropdown);
2109
- registerWidget("expression", scoreExpression, validateExpression);
2110
- registerWidget("grapher", scoreGrapher);
2111
- registerWidget("group", scoreGroup, validateGroup);
2112
- registerWidget("iframe", scoreIframe);
2113
- registerWidget("input-number", scoreInputNumber);
2114
- registerWidget("interactive-graph", scoreInteractiveGraph);
2115
- registerWidget("label-image", scoreLabelImage, validateLabelImage);
2116
- registerWidget("matcher", scoreMatcher);
2117
- registerWidget("matrix", scoreMatrix, validateMatrix);
2118
- registerWidget("mock-widget", scoreMockWidget, scoreMockWidget);
2119
- registerWidget("number-line", scoreNumberLine, validateNumberLine);
2120
- registerWidget("numeric-input", scoreNumericInput);
2121
- registerWidget("orderer", scoreOrderer, validateOrderer);
2122
- registerWidget("plotter", scorePlotter, validatePlotter);
2123
- registerWidget("radio", scoreRadio, validateRadio);
2124
- registerWidget("sorter", scoreSorter, validateSorter);
2125
- registerWidget("table", scoreTable, validateTable);
2126
- registerWidget("deprecated-standin", () => scoreNoop(1));
2127
- registerWidget("measurer", () => scoreNoop(1));
2128
- registerWidget("definition", scoreNoop);
2129
- registerWidget("explanation", scoreNoop);
2130
- registerWidget("image", scoreNoop);
2131
- registerWidget("interaction", scoreNoop);
2132
- registerWidget("molecule", scoreNoop);
2133
- registerWidget("passage", scoreNoop);
2134
- registerWidget("passage-ref", scoreNoop);
2135
- registerWidget("passage-ref-target", scoreNoop);
2136
- registerWidget("video", scoreNoop);
2137
-
2138
- const noScore = {
2139
- type: "points",
2140
- earned: 0,
2141
- total: 0,
2142
- message: null
2143
- };
2144
-
2145
- /**
2146
- * If a widget says that it is empty once it is graded.
2147
- * Trying to encapsulate references to the score format.
2148
- */
2149
- function scoreIsEmpty(score) {
2150
- // HACK(benkomalo): ugh. this isn't great; the Perseus score objects
2151
- // overload the type "invalid" for what should probably be three
2152
- // distinct cases:
2153
- // - truly empty or not fully filled out
2154
- // - invalid or malformed inputs
2155
- // - "almost correct" like inputs where the widget wants to give
2156
- // feedback (e.g. a fraction needs to be reduced, or `pi` should
2157
- // be used instead of 3.14)
2158
- //
2159
- // Unfortunately the coercion happens all over the place, as these
2160
- // Perseus style score objects are created *everywhere* (basically
2161
- // in every widget), so it's hard to change now. We assume that
2162
- // anything with a "message" is not truly empty, and one of the
2163
- // latter two cases for now.
2164
- return score.type === "invalid" && (!score.message || score.message.length === 0);
2165
- }
2166
-
2167
- /**
2168
- * Combine two score objects.
2169
- *
2170
- * Given two score objects for two different widgets, combine them so that
2171
- * if one is wrong, the total score is wrong, etc.
2172
- */
2173
- function combineScores(scoreA, scoreB) {
2174
- let message;
2175
- if (scoreA.type === "points" && scoreB.type === "points") {
2176
- if (scoreA.message && scoreB.message && scoreA.message !== scoreB.message) {
2177
- // TODO(alpert): Figure out how to combine messages usefully
2178
- message = null;
2179
- } else {
2180
- message = scoreA.message || scoreB.message;
2181
- }
2182
- return {
2183
- type: "points",
2184
- earned: scoreA.earned + scoreB.earned,
2185
- total: scoreA.total + scoreB.total,
2186
- message: message
2187
- };
2188
- }
2189
- if (scoreA.type === "points" && scoreB.type === "invalid") {
2190
- return scoreB;
2191
- }
2192
- if (scoreA.type === "invalid" && scoreB.type === "points") {
2193
- return scoreA;
2194
- }
2195
- if (scoreA.type === "invalid" && scoreB.type === "invalid") {
2196
- if (scoreA.message && scoreB.message && scoreA.message !== scoreB.message) {
2197
- // TODO(alpert): Figure out how to combine messages usefully
2198
- message = null;
2199
- } else {
2200
- message = scoreA.message || scoreB.message;
2201
- }
2202
- return {
2203
- type: "invalid",
2204
- message: message
2205
- };
2206
- }
2207
-
2208
- /**
2209
- * The above checks cover all combinations of score type, so if we get here
2210
- * then something is amiss with our inputs.
2211
- */
2212
- throw new PerseusError("PerseusScore with unknown type encountered", Errors.InvalidInput, {
2213
- metadata: {
2214
- scoreA: JSON.stringify(scoreA),
2215
- scoreB: JSON.stringify(scoreB)
2216
- }
2217
- });
2218
- }
2219
- function flattenScores(widgetScoreMap) {
2220
- return Object.values(widgetScoreMap).reduce(combineScores, noScore);
2221
- }
2222
-
2223
- /**
2224
- * score a Perseus item
2225
- *
2226
- * @param perseusRenderData - the full answer data, includes the correct answer
2227
- * @param userInputMap - the user's input for each widget, mapped by ID
2228
- * @param locale - string locale for math parsing ("de" 1.000,00 vs "en" 1,000.00)
2229
- */
2230
- function scorePerseusItem(perseusRenderData, userInputMap, locale) {
2231
- // There seems to be a chance that PerseusRenderer.widgets might include
2232
- // widget data for widgets that are not in PerseusRenderer.content,
2233
- // so this checks that the widgets are being used before scoring them
2234
- const usedWidgetIds = getWidgetIdsFromContent(perseusRenderData.content);
2235
- const scores = scoreWidgetsFunctional(perseusRenderData.widgets, usedWidgetIds, userInputMap, locale);
2236
- return flattenScores(scores);
2237
- }
2238
-
2239
- // TODO: combine scorePerseusItem with scoreWidgetsFunctional
2240
- function scoreWidgetsFunctional(widgets,
2241
- // This is a port of old code, I'm not sure why
2242
- // we need widgetIds vs the keys of the widgets object
2243
- widgetIds, userInputMap, locale) {
2244
- const upgradedWidgets = getUpgradedWidgetOptions(widgets);
2245
- const gradedWidgetIds = widgetIds.filter(id => {
2246
- const props = upgradedWidgets[id];
2247
- const widgetIsGraded = (props == null ? void 0 : props.graded) == null || props.graded;
2248
- const widgetIsStatic = !!(props != null && props.static);
2249
- // Ungraded widgets or widgets set to static shouldn't be graded.
2250
- return widgetIsGraded && !widgetIsStatic;
2251
- });
2252
- const widgetScores = {};
2253
- gradedWidgetIds.forEach(id => {
2254
- var _validator;
2255
- const widget = upgradedWidgets[id];
2256
- if (!widget) {
2257
- return;
2258
- }
2259
- const userInput = userInputMap[id];
2260
- const validator = getWidgetValidator(widget.type);
2261
- const scorer = getWidgetScorer(widget.type);
2262
-
2263
- // We do validation (empty checks) first and then scoring. If
2264
- // validation fails, it's result is itself a PerseusScore.
2265
- const score = (_validator = validator == null ? void 0 : validator(userInput, widget.options, locale)) != null ? _validator : scorer == null ? void 0 : scorer(userInput, widget.options, locale);
2266
- if (score != null) {
2267
- widgetScores[id] = score;
2268
- }
2269
- });
2270
- return widgetScores;
2271
- }
2272
-
2273
- export { ErrorCodes, KhanAnswerTypes, emptyWidgetsFunctional, flattenScores, getWidgetScorer, getWidgetValidator, inputNumberAnswerTypes, registerWidget, scoreCSProgram, scoreCategorizer, scoreDropdown, scoreExpression, scoreGrapher, scoreIframe, scoreInputNumber, scoreInteractiveGraph, scoreLabelImage, scoreLabelImageMarker, scoreMatcher, scoreMatrix, scoreNumberLine, scoreNumericInput, scoreOrderer, scorePerseusItem, scorePlotter, scoreRadio, scoreSorter, scoreTable, scoreWidgetsFunctional, validateCategorizer, validateDropdown, validateExpression, validateMatrix, validateNumberLine, validateOrderer, validatePlotter, validateRadio, validateSorter, validateTable };
2274
- //# sourceMappingURL=index.js.map