@khanacademy/perseus-score 4.0.0 → 4.0.2

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