@pie-lib/categorize 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,7 +3,7 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
- # [0.14.0](https://github.com/pie-framework/pie-lib/compare/@pie-lib/categorize@0.8.17...@pie-lib/categorize@0.14.0) (2025-07-31)
6
+ # [0.16.0](https://github.com/pie-framework/pie-lib/compare/@pie-lib/categorize@0.8.17...@pie-lib/categorize@0.16.0) (2025-07-31)
7
7
 
8
8
  **Note:** Version bump only for package @pie-lib/categorize
9
9
 
@@ -11,30 +11,26 @@ See [Conventional Commits](https://conventionalcommits.org) for commit guideline
11
11
 
12
12
 
13
13
 
14
- # [0.13.0](https://github.com/pie-framework/pie-lib/compare/@pie-lib/categorize@0.8.17...@pie-lib/categorize@0.13.0) (2025-07-31)
14
+ # [0.15.0](https://github.com/pie-framework/pie-lib/compare/@pie-lib/categorize@0.8.17...@pie-lib/categorize@0.15.0) (2025-07-31)
15
15
 
16
16
  **Note:** Version bump only for package @pie-lib/categorize
17
17
 
18
+ # [0.14.0](https://github.com/pie-framework/pie-lib/compare/@pie-lib/categorize@0.8.17...@pie-lib/categorize@0.14.0) (2025-07-31)
18
19
 
20
+ **Note:** Version bump only for package @pie-lib/categorize
19
21
 
22
+ # [0.13.0](https://github.com/pie-framework/pie-lib/compare/@pie-lib/categorize@0.8.17...@pie-lib/categorize@0.13.0) (2025-07-31)
20
23
 
24
+ **Note:** Version bump only for package @pie-lib/categorize
21
25
 
22
26
  # [0.12.0](https://github.com/pie-framework/pie-lib/compare/@pie-lib/categorize@0.8.17...@pie-lib/categorize@0.12.0) (2025-07-31)
23
27
 
24
28
  **Note:** Version bump only for package @pie-lib/categorize
25
29
 
26
-
27
-
28
-
29
-
30
30
  # [0.11.0](https://github.com/pie-framework/pie-lib/compare/@pie-lib/categorize@0.8.17...@pie-lib/categorize@0.11.0) (2025-07-31)
31
31
 
32
32
  **Note:** Version bump only for package @pie-lib/categorize
33
33
 
34
-
35
-
36
-
37
-
38
34
  # [0.13.0](https://github.com/pie-framework/pie-lib/compare/@pie-lib/categorize@0.8.17...@pie-lib/categorize@0.13.0) (2025-07-31)
39
35
 
40
36
  **Note:** Version bump only for package @pie-lib/categorize
package/lib/index.js ADDED
@@ -0,0 +1,673 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.removeChoiceFromCategory = exports.removeChoiceFromAlternate = exports.removeCategory = exports.removeAllChoices = exports.rearrangeChoices = exports.moveChoiceToCategory = exports.moveChoiceToAlternate = exports.limitInArrays = exports.limitInArray = exports.limitChoices = exports.getBuiltCategories = exports.getAllPossibleResponses = exports.ensureNoExtraChoicesInAnswer = exports.ensureNoExtraChoicesInAlternate = exports.countInChoices = exports.countInAnswer = exports.countChosen = exports.buildState = exports.buildChoices = exports.buildCategories = exports.FooTwo = void 0;
9
+ Object.defineProperty(exports, "score", {
10
+ enumerable: true,
11
+ get: function get() {
12
+ return _scoring.score;
13
+ }
14
+ });
15
+ exports.verifyAllowMultiplePlacements = exports.stillSelectable = void 0;
16
+
17
+ var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
18
+
19
+ var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
20
+
21
+ var _debug = _interopRequireDefault(require("debug"));
22
+
23
+ var _clone = _interopRequireDefault(require("lodash/clone"));
24
+
25
+ var _remove = _interopRequireDefault(require("lodash/remove"));
26
+
27
+ var _scoring = require("./scoring");
28
+
29
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
30
+
31
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
32
+
33
+ var FooTwo = 'foo-two';
34
+ exports.FooTwo = FooTwo;
35
+ var log = (0, _debug["default"])('@pie-lib:categorize');
36
+
37
+ var limitChoices = function limitChoices(choiceId, count, choices) {
38
+ var out = choices.reduce(function (acc, id) {
39
+ var foundCount = countInChoices(choiceId, acc.choices);
40
+
41
+ if (id !== choiceId || foundCount < count) {
42
+ acc.choices.push(id);
43
+ }
44
+
45
+ return acc;
46
+ }, {
47
+ choices: []
48
+ });
49
+ return out.choices;
50
+ };
51
+ /**
52
+ * Limit in an array of arrays.
53
+ * So for an array with [[1,1],[1,1]] if you call limitInArray(1, arr, 3) you'll get: [[1,1], [1]]
54
+ * @param {*} id
55
+ * @param {*} arrays
56
+ * @param {*} limit
57
+ */
58
+
59
+
60
+ exports.limitChoices = limitChoices;
61
+
62
+ var limitInArrays = function limitInArrays(id, arrays, limit) {
63
+ arrays = arrays || [];
64
+ var result = arrays.reduce(function (acc, array) {
65
+ var l = limit - acc.count;
66
+ var result = limitInArray(id, array, l);
67
+ acc.out.push(result.array);
68
+ acc.count = acc.count + (result.count || 0);
69
+ return acc;
70
+ }, {
71
+ out: [],
72
+ count: 0
73
+ });
74
+ return result.out;
75
+ };
76
+ /**
77
+ * Limit the id in the array to the limit set.
78
+ * So for an array with [1,1,1,1] if you call limitInArray(1, arr, 2) you'll get: [1,1]
79
+ * @param {string} id
80
+ * @param {string[]} arr
81
+ * @param {number} limit
82
+ */
83
+
84
+
85
+ exports.limitInArrays = limitInArrays;
86
+
87
+ var limitInArray = function limitInArray(id, arr, limit) {
88
+ arr = arr || [];
89
+
90
+ if (limit === 0) {
91
+ var stripped = arr.filter(function (v) {
92
+ return v !== id;
93
+ });
94
+ return {
95
+ array: stripped,
96
+ count: arr.length - stripped.length
97
+ };
98
+ } else {
99
+ var result = arr.reduce(function (acc, v) {
100
+ if (v === id) {
101
+ if (acc.count < limit) {
102
+ acc.count += 1;
103
+ acc.out.push(v);
104
+ }
105
+ } else {
106
+ acc.out.push(v);
107
+ }
108
+
109
+ return acc;
110
+ }, {
111
+ out: [],
112
+ count: 0
113
+ });
114
+ return {
115
+ array: result.out,
116
+ count: result.count
117
+ };
118
+ }
119
+ };
120
+ /**
121
+ * Ensure that there are no extra choices in answer, if a choice.categoryCount is > 0.
122
+ * @param {{category: string, choices: string[]}[]} answer
123
+ * @param {{id:string,categoryCount:number}} choices
124
+ */
125
+
126
+
127
+ exports.limitInArray = limitInArray;
128
+
129
+ var ensureNoExtraChoicesInAnswer = function ensureNoExtraChoicesInAnswer(answer, choices) {
130
+ choices = choices || [];
131
+ var out = choices.reduce(function (answerArray, choice) {
132
+ log('choice: ----> ', choice.id, 'categoryCount: ', choice.categoryCount);
133
+
134
+ if (choice.categoryCount === undefined || choice.categoryCount === 0) {
135
+ return answerArray;
136
+ } else {
137
+ var _choices = answerArray.map(function (a) {
138
+ return a.choices;
139
+ });
140
+
141
+ var result = limitInArrays(choice.id, _choices, choice.categoryCount);
142
+ var updatedArray = result.map(function (r, index) {
143
+ return {
144
+ category: answerArray[index].category,
145
+ alternateResponses: answerArray[index].alternateResponses,
146
+ choices: r
147
+ };
148
+ });
149
+ return updatedArray;
150
+ }
151
+ }, answer);
152
+ return out;
153
+ };
154
+ /**
155
+ * Ensure that there are no extra choices in alternate responses, if a choice.categoryCount is > 0.
156
+ * @param {{category: string, choices: string[]}[]} answer
157
+ * @param {{id:string,categoryCount:number}} choices
158
+ */
159
+
160
+
161
+ exports.ensureNoExtraChoicesInAnswer = ensureNoExtraChoicesInAnswer;
162
+
163
+ var ensureNoExtraChoicesInAlternate = function ensureNoExtraChoicesInAlternate(answer, choices) {
164
+ choices = choices || [];
165
+ var out = choices.reduce(function (answerArray, choice) {
166
+ log('choice: ----> ', choice.id, 'categoryCount: ', choice.categoryCount);
167
+
168
+ if (choice.categoryCount === undefined || choice.categoryCount === 0) {
169
+ return answerArray;
170
+ } else {
171
+ var alternatePair = {};
172
+ answerArray.forEach(function (answer) {
173
+ return (answer.alternateResponses || []).forEach(function (alternate, index) {
174
+ if (index in alternatePair) {
175
+ alternatePair[index].push(alternate);
176
+ } else {
177
+ alternatePair[index] = [];
178
+ alternatePair[index].push(alternate);
179
+ }
180
+ });
181
+ });
182
+ var recreatedAlternate = [];
183
+ Object.keys(alternatePair).forEach(function (k) {
184
+ var limitAlternate = limitInArrays(choice.id, alternatePair[k], choice.categoryCount);
185
+ alternatePair[k] = limitAlternate;
186
+ alternatePair[k].forEach(function (item, index) {
187
+ if (!recreatedAlternate[index]) {
188
+ recreatedAlternate[index] = [];
189
+ recreatedAlternate[index].push(item);
190
+ } else {
191
+ recreatedAlternate[index].push(item);
192
+ }
193
+ });
194
+ });
195
+ var updatedArray = answerArray.map(function (answer, index) {
196
+ return {
197
+ category: answer.category,
198
+ alternateResponses: recreatedAlternate[index] || answer.alternateResponses,
199
+ choices: answer.choices
200
+ };
201
+ });
202
+ return updatedArray;
203
+ }
204
+ }, answer);
205
+ return out;
206
+ };
207
+ /**
208
+ * Count the number of choice ids in a given answer array
209
+ * @param {string} choiceId
210
+ * @param {{category: string, choices: string[]}[]} answer
211
+ */
212
+
213
+
214
+ exports.ensureNoExtraChoicesInAlternate = ensureNoExtraChoicesInAlternate;
215
+
216
+ var countInAnswer = function countInAnswer(choiceId, answer) {
217
+ var out = answer.reduce(function (acc, a) {
218
+ return acc + countInChoices(choiceId, a.choices);
219
+ }, 0);
220
+ log('[countInAnswer] choiceId:', choiceId, answer);
221
+ return out;
222
+ };
223
+
224
+ exports.countInAnswer = countInAnswer;
225
+
226
+ var countInChoices = function countInChoices(choiceId, choices) {
227
+ return (choices || []).filter(function (c) {
228
+ return c === choiceId;
229
+ }).length;
230
+ };
231
+ /**
232
+ * Count the number of times a choice has been selected in categories.
233
+ * @param {*} choice
234
+ * @param {*} categories
235
+ */
236
+
237
+
238
+ exports.countInChoices = countInChoices;
239
+
240
+ var countChosen = function countChosen(choice, categories) {
241
+ if (!choice || !choice.id) {
242
+ return 0;
243
+ }
244
+
245
+ if (!Array.isArray(categories)) {
246
+ return 0;
247
+ }
248
+
249
+ return categories.reduce(function (acc, c) {
250
+ var count = (c.choices || []).filter(function (h) {
251
+ return h && h.id === choice.id;
252
+ }).length;
253
+ return acc + count;
254
+ }, 0);
255
+ };
256
+ /**
257
+ * @param {string?} categoryId
258
+ * @param {{category:string, choices: string[]}} answers
259
+ */
260
+
261
+
262
+ exports.countChosen = countChosen;
263
+
264
+ var removeCategory = function removeCategory(categoryId, answers) {
265
+ return answers.filter(function (a) {
266
+ return a.category !== categoryId;
267
+ });
268
+ };
269
+ /**
270
+ * @param {string} choiceId
271
+ * @param {{category:string, choices: string[]}} answers
272
+ * @param {string?} categoryId - optional categegory id
273
+ */
274
+
275
+
276
+ exports.removeCategory = removeCategory;
277
+
278
+ var removeAllChoices = function removeAllChoices(choiceId, answers, categoryId) {
279
+ return answers.map(function (a) {
280
+ if (!categoryId || a.category === categoryId) {
281
+ var cloned = (0, _clone["default"])(a.choices);
282
+ (0, _remove["default"])(cloned, function (v) {
283
+ return v === choiceId;
284
+ });
285
+ return _objectSpread(_objectSpread({}, a), {}, {
286
+ choices: cloned
287
+ });
288
+ } else {
289
+ return a;
290
+ }
291
+ });
292
+ };
293
+
294
+ exports.removeAllChoices = removeAllChoices;
295
+
296
+ var rearrangeChoices = function rearrangeChoices(choices, indexFrom, indexTo) {
297
+ if (choices.length === 0) {
298
+ return choices;
299
+ }
300
+
301
+ choices.splice(indexFrom, 1, choices.splice(indexTo, 1, choices[indexFrom])[0]);
302
+ return choices;
303
+ };
304
+
305
+ exports.rearrangeChoices = rearrangeChoices;
306
+
307
+ var verifyAllowMultiplePlacements = function verifyAllowMultiplePlacements(choice, categoryId, answers) {
308
+ return answers.map(function (a) {
309
+ if (a.category !== categoryId) {
310
+ a.choices = (a.choices || []).filter(function (c) {
311
+ return c !== choice.id;
312
+ });
313
+ return a;
314
+ } else {
315
+ a.choices = a.choices.reduce(function (acc, currentValue) {
316
+ if (currentValue.id === choice.id) {
317
+ var foundIndex = acc.findIndex(function (c) {
318
+ return c.id === choice.id;
319
+ });
320
+
321
+ if (foundIndex === -1) {
322
+ acc.push(currentValue);
323
+ }
324
+ } else {
325
+ acc.push(currentValue);
326
+ }
327
+
328
+ return acc;
329
+ }, []);
330
+ return a;
331
+ }
332
+ });
333
+ };
334
+
335
+ exports.verifyAllowMultiplePlacements = verifyAllowMultiplePlacements;
336
+
337
+ var removeChoiceFromCategory = function removeChoiceFromCategory(choiceId, categoryId, choiceIndex, answers) {
338
+ log('[removeChoiceFromCategory] choiceIndex:', choiceIndex);
339
+ return answers.map(function (a) {
340
+ if (a.category === categoryId) {
341
+ var cloned = (0, _clone["default"])(a.choices);
342
+ var index = cloned.findIndex(function (v, index) {
343
+ return v === choiceId && index >= choiceIndex;
344
+ });
345
+
346
+ if (index !== -1) {
347
+ cloned.splice(index, 1);
348
+ }
349
+
350
+ return _objectSpread(_objectSpread({}, a), {}, {
351
+ choices: cloned
352
+ });
353
+ } else {
354
+ return a;
355
+ }
356
+ });
357
+ };
358
+
359
+ exports.removeChoiceFromCategory = removeChoiceFromCategory;
360
+
361
+ var removeChoiceFromAlternate = function removeChoiceFromAlternate(choiceId, categoryId, choiceIndex, altIndex, answers) {
362
+ return (answers || []).map(function (a) {
363
+ if ((a === null || a === void 0 ? void 0 : a.category) === categoryId) {
364
+ var newAlternates = ((a === null || a === void 0 ? void 0 : a.alternateResponses) || []).map(function (altArray, idx) {
365
+ if (idx === altIndex) {
366
+ (altArray || []).splice(choiceIndex, 1);
367
+ return altArray;
368
+ }
369
+
370
+ return altArray;
371
+ });
372
+ return _objectSpread(_objectSpread({}, a), {}, {
373
+ alternateResponses: newAlternates
374
+ });
375
+ }
376
+
377
+ return a;
378
+ });
379
+ };
380
+
381
+ exports.removeChoiceFromAlternate = removeChoiceFromAlternate;
382
+
383
+ var moveChoiceToCategory = function moveChoiceToCategory(choiceId, from, to, choiceIndex, answers) {
384
+ log('[moveChoiceToCategory] choice: ', choiceId, 'from: ', from, 'to: ', to, 'answers: ', answers);
385
+
386
+ if (from === to) {
387
+ return answers;
388
+ }
389
+
390
+ if (from) {
391
+ answers = removeChoiceFromCategory(choiceId, from, choiceIndex, answers);
392
+ }
393
+
394
+ var index = answers.findIndex(function (a) {
395
+ return a.category === to;
396
+ });
397
+
398
+ if (index === -1) {
399
+ answers.push({
400
+ category: to,
401
+ choices: [choiceId]
402
+ });
403
+ return answers;
404
+ } else {
405
+ return answers.map(function (a) {
406
+ if (a.category === to) {
407
+ a.choices = a.choices || [];
408
+ a.choices.push(choiceId);
409
+ return a;
410
+ }
411
+
412
+ return a;
413
+ });
414
+ }
415
+ };
416
+
417
+ exports.moveChoiceToCategory = moveChoiceToCategory;
418
+
419
+ var moveChoiceToAlternate = function moveChoiceToAlternate(choiceId, from, to, choiceIndex, answers, alternateIndex, categoryCount) {
420
+ log('[moveChoiceToAlternate] choice: ', choiceId, 'from: ', from, 'to: ', to, 'answers: ', answers, 'chocieIndex: ', choiceIndex);
421
+
422
+ if (from === to) {
423
+ return answers;
424
+ }
425
+
426
+ return answers.map(function (a) {
427
+ if (a.category === to) {
428
+ if (categoryCount !== 0 && a.alternateResponses) {
429
+ a.alternateResponses[alternateIndex] = (a.alternateResponses[alternateIndex] || []).filter(function (resp) {
430
+ return resp !== choiceId;
431
+ });
432
+ }
433
+
434
+ if (!a.alternateResponses) {
435
+ a.alternateResponses = [];
436
+ a.alternateResponses[alternateIndex] = [];
437
+ }
438
+
439
+ a.alternateResponses[alternateIndex].push(choiceId);
440
+ }
441
+
442
+ if (a.category === from && categoryCount !== 0 && a.alternateResponses && a.alternateResponses[alternateIndex]) {
443
+ a.alternateResponses[alternateIndex] = a.alternateResponses[alternateIndex].filter(function (resp) {
444
+ return resp !== choiceId;
445
+ });
446
+ }
447
+
448
+ return a;
449
+ });
450
+ };
451
+
452
+ exports.moveChoiceToAlternate = moveChoiceToAlternate;
453
+
454
+ var stillSelectable = function stillSelectable(h, builtCategories) {
455
+ if (h.categoryCount > 0) {
456
+ var count = countChosen(h, builtCategories);
457
+ return count < h.categoryCount;
458
+ } else {
459
+ return true;
460
+ }
461
+ };
462
+ /**
463
+ * returns all choices with property 'correct' set to boolean
464
+ * @param {string[]} possibleResponseChoices
465
+ * @param {Object[]} builtCategoryChoices
466
+ *
467
+ * @returns {Object}, returns builtChoices: BuiltChoice[] and allChoicesAreCorrect: boolean
468
+ * BuiltChoice = { id: choiceId, content: choiceContent, correct: boolean }
469
+ */
470
+
471
+
472
+ exports.stillSelectable = stillSelectable;
473
+
474
+ var buildChoices = function buildChoices(possibleResponseChoices, builtCategoryChoices) {
475
+ return builtCategoryChoices.reduce(function (acc, builtChoice) {
476
+ // set correct value on each choice that was selected by user
477
+ var index = acc.copyOfPossibleResponse.findIndex(function (cRC) {
478
+ return builtChoice && cRC === builtChoice.id;
479
+ }); // if the choice exists in the correct response
480
+ // set the correct: true
481
+
482
+ if (index >= 0) {
483
+ acc.builtChoices.push(_objectSpread(_objectSpread({}, builtChoice), {}, {
484
+ correct: true
485
+ }));
486
+ acc.copyOfPossibleResponse = [].concat((0, _toConsumableArray2["default"])(acc.copyOfPossibleResponse.slice(0, index)), (0, _toConsumableArray2["default"])(acc.copyOfPossibleResponse.slice(index + 1)));
487
+ } else {
488
+ acc.builtChoices.push(_objectSpread(_objectSpread({}, builtChoice), {}, {
489
+ correct: false
490
+ }));
491
+ acc.allChoicesAreCorrect = false;
492
+ }
493
+
494
+ return acc;
495
+ }, {
496
+ builtChoices: [],
497
+ copyOfPossibleResponse: (0, _toConsumableArray2["default"])(possibleResponseChoices),
498
+ allChoicesAreCorrect: true
499
+ });
500
+ };
501
+ /**
502
+ * returns corrected answer using this possible correct response
503
+ * @param {Object} possibleResponse, has form: { CategoryId: ChoiceId[] }
504
+ * @param {Object[]} builtCategories
505
+ *
506
+ * @returns {Object}, returns builtCategories: BuiltCategory[] and correct: boolean
507
+ * BuiltCategory = { id: categoryId, label: categoryLabel, correct: boolean, choices: BuiltChoice[] }
508
+ * BuiltChoice = { id: choiceId, content: choiceContent, correct: boolean }
509
+ */
510
+
511
+
512
+ exports.buildChoices = buildChoices;
513
+
514
+ var getBuiltCategories = function getBuiltCategories(possibleResponse, builtCategories) {
515
+ return builtCategories.reduce(function (acc, builtCategory) {
516
+ var possibleResponseChoices = possibleResponse[builtCategory.id] || []; // the correct choices for this category
517
+
518
+ var builtCategoryChoices = builtCategory.choices || []; // the choices in the answer
519
+
520
+ var _buildChoices = buildChoices(possibleResponseChoices, builtCategoryChoices),
521
+ builtChoices = _buildChoices.builtChoices,
522
+ allChoicesAreCorrect = _buildChoices.allChoicesAreCorrect;
523
+
524
+ var allChoicesAreInAnswer = builtCategoryChoices.length === possibleResponseChoices.length;
525
+ acc.builtCategories.push(_objectSpread(_objectSpread({}, builtCategory), {}, {
526
+ correct: allChoicesAreCorrect && allChoicesAreInAnswer,
527
+ choices: builtChoices
528
+ }));
529
+ acc.correct = acc.correct && allChoicesAreCorrect && allChoicesAreInAnswer;
530
+ return acc;
531
+ }, {
532
+ builtCategories: [],
533
+ correct: true
534
+ });
535
+ };
536
+ /**
537
+ * returns all the possible responses by combining the proper alternate responses
538
+ * @param {Object[]} correctResponse
539
+ *
540
+ * @returns {Object[]}, returns Response[]
541
+ * Response = { CategoryId: ChoiceId[] },
542
+ */
543
+
544
+
545
+ exports.getBuiltCategories = getBuiltCategories;
546
+
547
+ var getAllPossibleResponses = function getAllPossibleResponses(correctResponse) {
548
+ if (!correctResponse) {
549
+ return [];
550
+ }
551
+
552
+ return correctResponse.reduce(function (acc, cR) {
553
+ // main response
554
+ if (acc[0]) {
555
+ acc[0][cR.category] = cR.choices;
556
+ } else {
557
+ acc.push((0, _defineProperty2["default"])({}, cR.category, cR.choices));
558
+ } // alternate responses
559
+
560
+
561
+ if (cR.alternateResponses) {
562
+ cR.alternateResponses.forEach(function (aR, index) {
563
+ if (acc[index + 1]) {
564
+ acc[index + 1][cR.category] = aR;
565
+ } else {
566
+ acc.push((0, _defineProperty2["default"])({}, cR.category, aR));
567
+ }
568
+ });
569
+ }
570
+
571
+ return acc;
572
+ }, []);
573
+ };
574
+ /**
575
+ * build the categories to be displayed, where each category has its own list of choices
576
+ * @param {Object[]} categories
577
+ * @param {{id:string}[]} choices
578
+ * @param {{category: string, choices:string[]}[]} answers
579
+ *
580
+ * @returns {Object[]}, returns BuiltCategory[]
581
+ * BuiltCategory = { id: categoryId, label: categoryLabel, choices: BuiltChoice[]},
582
+ * BuiltChoice = { id: choiceId, content: choiceContent }
583
+ */
584
+
585
+
586
+ exports.getAllPossibleResponses = getAllPossibleResponses;
587
+
588
+ var buildCategories = function buildCategories(categories, choices, answers) {
589
+ categories = categories || [];
590
+ answers = answers || [];
591
+ choices = choices || [];
592
+ return categories.map(function (category) {
593
+ var answer = answers.find(function (answer) {
594
+ return answer.category === category.id;
595
+ });
596
+
597
+ var _ref = answer || {},
598
+ _ref$choices = _ref.choices,
599
+ answerChoices = _ref$choices === void 0 ? [] : _ref$choices;
600
+
601
+ return _objectSpread(_objectSpread({}, category), {}, {
602
+ choices: answerChoices.map(function (chId) {
603
+ return choices.find(function (ch) {
604
+ return ch.id === chId;
605
+ });
606
+ })
607
+ });
608
+ });
609
+ };
610
+ /**
611
+ * build the choice and category state
612
+ * @param {Object[]} categories
613
+ * @param {{id:string}[]} choices
614
+ * @param {{category: string, choices:string[]}[]} answers
615
+ *
616
+ * @param correctResponse
617
+ * @returns { categories: Category[], choices: Choice[], correct: boolean, bestResponse: Response }, where Response: { categoryId: choiceId[] }
618
+ */
619
+
620
+
621
+ exports.buildCategories = buildCategories;
622
+
623
+ var buildState = function buildState(categories, choices, answers, correctResponse) {
624
+ categories = categories || [];
625
+ choices = choices || [];
626
+ answers = answers || [];
627
+ var allResponses = getAllPossibleResponses(correctResponse) || [];
628
+ var builtCategories = buildCategories(categories, choices, answers);
629
+ var bestResponse;
630
+ var entirelyCorrect; // at least one defined correct response
631
+
632
+ if (allResponses.length) {
633
+ var builtData = allResponses.reduce(function (acc, possibleResponse) {
634
+ // set correctness for each possible response
635
+ var _getBuiltCategories = getBuiltCategories(possibleResponse, builtCategories),
636
+ categoriesWithChoices = _getBuiltCategories.builtCategories,
637
+ correct = _getBuiltCategories.correct; // if bestResponse not found yet OR no correct response found yet and this one is the correct one
638
+
639
+
640
+ if (acc.bestResponse === null || !acc.entirelyCorrect && correct) {
641
+ return {
642
+ bestResponse: possibleResponse,
643
+ builtCategories: categoriesWithChoices,
644
+ entirelyCorrect: correct
645
+ };
646
+ }
647
+
648
+ return acc;
649
+ }, {
650
+ bestResponse: null,
651
+ builtCategories: [],
652
+ entirelyCorrect: false
653
+ });
654
+ builtCategories = builtData.builtCategories;
655
+ bestResponse = builtData.bestResponse;
656
+ entirelyCorrect = builtData.entirelyCorrect;
657
+ }
658
+
659
+ var filteredChoices = choices.map(function (ch) {
660
+ return stillSelectable(ch, builtCategories) ? ch : {
661
+ empty: true
662
+ };
663
+ });
664
+ return {
665
+ choices: filteredChoices,
666
+ categories: builtCategories,
667
+ correct: entirelyCorrect,
668
+ bestResponse: bestResponse
669
+ };
670
+ };
671
+
672
+ exports.buildState = buildState;
673
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.js"],"names":["FooTwo","log","limitChoices","choiceId","count","choices","out","reduce","acc","id","foundCount","countInChoices","push","limitInArrays","arrays","limit","result","array","l","limitInArray","arr","stripped","filter","v","length","ensureNoExtraChoicesInAnswer","answer","answerArray","choice","categoryCount","undefined","map","a","updatedArray","r","index","category","alternateResponses","ensureNoExtraChoicesInAlternate","alternatePair","forEach","alternate","recreatedAlternate","Object","keys","k","limitAlternate","item","countInAnswer","c","countChosen","categories","Array","isArray","h","removeCategory","categoryId","answers","removeAllChoices","cloned","rearrangeChoices","indexFrom","indexTo","splice","verifyAllowMultiplePlacements","currentValue","foundIndex","findIndex","removeChoiceFromCategory","choiceIndex","removeChoiceFromAlternate","altIndex","newAlternates","altArray","idx","moveChoiceToCategory","from","to","moveChoiceToAlternate","alternateIndex","resp","stillSelectable","builtCategories","buildChoices","possibleResponseChoices","builtCategoryChoices","builtChoice","copyOfPossibleResponse","cRC","builtChoices","correct","slice","allChoicesAreCorrect","getBuiltCategories","possibleResponse","builtCategory","allChoicesAreInAnswer","getAllPossibleResponses","correctResponse","cR","aR","buildCategories","find","answerChoices","chId","ch","buildState","allResponses","bestResponse","entirelyCorrect","builtData","categoriesWithChoices","filteredChoices","empty"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;;AACA;;AACA;;AACA;;;;;;AAIO,IAAMA,MAAM,GAAG,SAAf;;AAEP,IAAMC,GAAG,GAAG,uBAAM,qBAAN,CAAZ;;AAEO,IAAMC,YAAY,GAAG,SAAfA,YAAe,CAACC,QAAD,EAAWC,KAAX,EAAkBC,OAAlB,EAA8B;AACxD,MAAMC,GAAG,GAAGD,OAAO,CAACE,MAAR,CACV,UAACC,GAAD,EAAMC,EAAN,EAAa;AACX,QAAMC,UAAU,GAAGC,cAAc,CAACR,QAAD,EAAWK,GAAG,CAACH,OAAf,CAAjC;;AAEA,QAAII,EAAE,KAAKN,QAAP,IAAmBO,UAAU,GAAGN,KAApC,EAA2C;AACzCI,MAAAA,GAAG,CAACH,OAAJ,CAAYO,IAAZ,CAAiBH,EAAjB;AACD;;AAED,WAAOD,GAAP;AACD,GATS,EAUV;AAAEH,IAAAA,OAAO,EAAE;AAAX,GAVU,CAAZ;AAaA,SAAOC,GAA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AAILD,IAAAA,YAAY,EAAZA;AAJK,GAAP;AAMD,CApDM","sourcesContent":["import debug from 'debug';\nimport clone from 'lodash/clone';\nimport remove from 'lodash/remove';\nimport { score } from './scoring';\n\nexport { score };\n\nexport const FooTwo = 'foo-two';\n\nconst log = debug('@pie-lib:categorize');\n\nexport const limitChoices = (choiceId, count, choices) => {\n const out = choices.reduce(\n (acc, id) => {\n const foundCount = countInChoices(choiceId, acc.choices);\n\n if (id !== choiceId || foundCount < count) {\n acc.choices.push(id);\n }\n\n return acc;\n },\n { choices: [] },\n );\n\n return out.choices;\n};\n\n/**\n * Limit in an array of arrays.\n * So for an array with [[1,1],[1,1]] if you call limitInArray(1, arr, 3) you'll get: [[1,1], [1]]\n * @param {*} id\n * @param {*} arrays\n * @param {*} limit\n */\nexport const limitInArrays = (id, arrays, limit) => {\n arrays = arrays || [];\n\n const result = arrays.reduce(\n (acc, array) => {\n const l = limit - acc.count;\n const result = limitInArray(id, array, l);\n\n acc.out.push(result.array);\n acc.count = acc.count + (result.count || 0);\n\n return acc;\n },\n { out: [], count: 0 },\n );\n\n return result.out;\n};\n\n/**\n * Limit the id in the array to the limit set.\n * So for an array with [1,1,1,1] if you call limitInArray(1, arr, 2) you'll get: [1,1]\n * @param {string} id\n * @param {string[]} arr\n * @param {number} limit\n */\nexport const limitInArray = (id, arr, limit) => {\n arr = arr || [];\n\n if (limit === 0) {\n const stripped = arr.filter((v) => v !== id);\n\n return { array: stripped, count: arr.length - stripped.length };\n } else {\n const result = arr.reduce(\n (acc, v) => {\n if (v === id) {\n if (acc.count < limit) {\n acc.count += 1;\n acc.out.push(v);\n }\n } else {\n acc.out.push(v);\n }\n\n return acc;\n },\n { out: [], count: 0 },\n );\n\n return { array: result.out, count: result.count };\n }\n};\n\n/**\n * Ensure that there are no extra choices in answer, if a choice.categoryCount is > 0.\n * @param {{category: string, choices: string[]}[]} answer\n * @param {{id:string,categoryCount:number}} choices\n */\nexport const ensureNoExtraChoicesInAnswer = (answer, choices) => {\n choices = choices || [];\n\n const out = choices.reduce((answerArray, choice) => {\n log('choice: ----> ', choice.id, 'categoryCount: ', choice.categoryCount);\n\n if (choice.categoryCount === undefined || choice.categoryCount === 0) {\n return answerArray;\n } else {\n const choices = answerArray.map((a) => a.choices);\n const result = limitInArrays(choice.id, choices, choice.categoryCount);\n\n const updatedArray = result.map((r, index) => {\n return {\n category: answerArray[index].category,\n alternateResponses: answerArray[index].alternateResponses,\n choices: r,\n };\n });\n\n return updatedArray;\n }\n }, answer);\n return out;\n};\n\n/**\n * Ensure that there are no extra choices in alternate responses, if a choice.categoryCount is > 0.\n * @param {{category: string, choices: string[]}[]} answer\n * @param {{id:string,categoryCount:number}} choices\n */\n\nexport const ensureNoExtraChoicesInAlternate = (answer, choices) => {\n choices = choices || [];\n\n const out = choices.reduce((answerArray, choice) => {\n log('choice: ----> ', choice.id, 'categoryCount: ', choice.categoryCount);\n\n if (choice.categoryCount === undefined || choice.categoryCount === 0) {\n return answerArray;\n } else {\n let alternatePair = {};\n\n answerArray.forEach((answer) =>\n (answer.alternateResponses || []).forEach((alternate, index) => {\n if (index in alternatePair) {\n alternatePair[index].push(alternate);\n } else {\n alternatePair[index] = [];\n alternatePair[index].push(alternate);\n }\n }),\n );\n\n const recreatedAlternate = [];\n\n Object.keys(alternatePair).forEach((k) => {\n const limitAlternate = limitInArrays(choice.id, alternatePair[k], choice.categoryCount);\n alternatePair[k] = limitAlternate;\n\n alternatePair[k].forEach((item, index) => {\n if (!recreatedAlternate[index]) {\n recreatedAlternate[index] = [];\n recreatedAlternate[index].push(item);\n } else {\n recreatedAlternate[index].push(item);\n }\n });\n });\n\n const updatedArray = answerArray.map((answer, index) => {\n return {\n category: answer.category,\n alternateResponses: recreatedAlternate[index] || answer.alternateResponses,\n choices: answer.choices,\n };\n });\n return updatedArray;\n }\n }, answer);\n\n return out;\n};\n/**\n * Count the number of choice ids in a given answer array\n * @param {string} choiceId\n * @param {{category: string, choices: string[]}[]} answer\n */\nexport const countInAnswer = (choiceId, answer) => {\n const out = answer.reduce((acc, a) => acc + countInChoices(choiceId, a.choices), 0);\n\n log('[countInAnswer] choiceId:', choiceId, answer);\n\n return out;\n};\n\nexport const countInChoices = (choiceId, choices) => (choices || []).filter((c) => c === choiceId).length;\n\n/**\n * Count the number of times a choice has been selected in categories.\n * @param {*} choice\n * @param {*} categories\n */\nexport const countChosen = (choice, categories) => {\n if (!choice || !choice.id) {\n return 0;\n }\n\n if (!Array.isArray(categories)) {\n return 0;\n }\n\n return categories.reduce((acc, c) => {\n const count = (c.choices || []).filter((h) => h && h.id === choice.id).length;\n\n return acc + count;\n }, 0);\n};\n\n/**\n * @param {string?} categoryId\n * @param {{category:string, choices: string[]}} answers\n */\nexport const removeCategory = (categoryId, answers) => answers.filter((a) => a.category !== categoryId);\n\n/**\n * @param {string} choiceId\n * @param {{category:string, choices: string[]}} answers\n * @param {string?} categoryId - optional categegory id\n */\nexport const removeAllChoices = (choiceId, answers, categoryId) => {\n return answers.map((a) => {\n if (!categoryId || a.category === categoryId) {\n const cloned = clone(a.choices);\n\n remove(cloned, (v) => v === choiceId);\n\n return { ...a, choices: cloned };\n } else {\n return a;\n }\n });\n};\n\nexport const rearrangeChoices = (choices, indexFrom, indexTo) => {\n if (choices.length === 0) {\n return choices;\n }\n\n choices.splice(indexFrom, 1, choices.splice(indexTo, 1, choices[indexFrom])[0]);\n\n return choices;\n};\n\nexport const verifyAllowMultiplePlacements = (choice, categoryId, answers) => {\n return answers.map((a) => {\n if (a.category !== categoryId) {\n a.choices = (a.choices || []).filter((c) => c !== choice.id);\n\n return a;\n } else {\n a.choices = a.choices.reduce((acc, currentValue) => {\n if (currentValue.id === choice.id) {\n const foundIndex = acc.findIndex((c) => c.id === choice.id);\n\n if (foundIndex === -1) {\n acc.push(currentValue);\n }\n } else {\n acc.push(currentValue);\n }\n\n return acc;\n }, []);\n\n return a;\n }\n });\n};\n\nexport const removeChoiceFromCategory = (choiceId, categoryId, choiceIndex, answers) => {\n log('[removeChoiceFromCategory] choiceIndex:', choiceIndex);\n\n return answers.map((a) => {\n if (a.category === categoryId) {\n const cloned = clone(a.choices);\n const index = cloned.findIndex((v, index) => {\n return v === choiceId && index >= choiceIndex;\n });\n\n if (index !== -1) {\n cloned.splice(index, 1);\n }\n\n return { ...a, choices: cloned };\n } else {\n return a;\n }\n });\n};\n\nexport const removeChoiceFromAlternate = (choiceId, categoryId, choiceIndex, altIndex, answers) => {\n return (answers || []).map((a) => {\n if (a?.category === categoryId) {\n const newAlternates = (a?.alternateResponses || []).map((altArray, idx) => {\n if (idx === altIndex) {\n (altArray || []).splice(choiceIndex, 1);\n return altArray;\n }\n return altArray;\n });\n return { ...a, alternateResponses: newAlternates };\n }\n return a;\n });\n};\n\nexport const moveChoiceToCategory = (choiceId, from, to, choiceIndex, answers) => {\n log('[moveChoiceToCategory] choice: ', choiceId, 'from: ', from, 'to: ', to, 'answers: ', answers);\n\n if (from === to) {\n return answers;\n }\n\n if (from) {\n answers = removeChoiceFromCategory(choiceId, from, choiceIndex, answers);\n }\n\n const index = answers.findIndex((a) => a.category === to);\n if (index === -1) {\n answers.push({ category: to, choices: [choiceId] });\n\n return answers;\n } else {\n return answers.map((a) => {\n if (a.category === to) {\n a.choices = a.choices || [];\n a.choices.push(choiceId);\n\n return a;\n }\n\n return a;\n });\n }\n};\n\nexport const moveChoiceToAlternate = (choiceId, from, to, choiceIndex, answers, alternateIndex, categoryCount) => {\n log(\n '[moveChoiceToAlternate] choice: ',\n choiceId,\n 'from: ',\n from,\n 'to: ',\n to,\n 'answers: ',\n answers,\n 'chocieIndex: ',\n choiceIndex,\n );\n\n if (from === to) {\n return answers;\n }\n\n return answers.map((a) => {\n if (a.category === to) {\n if (categoryCount !== 0 && a.alternateResponses) {\n a.alternateResponses[alternateIndex] = (a.alternateResponses[alternateIndex] || []).filter(\n (resp) => resp !== choiceId,\n );\n }\n\n if (!a.alternateResponses) {\n a.alternateResponses = [];\n a.alternateResponses[alternateIndex] = [];\n }\n\n a.alternateResponses[alternateIndex].push(choiceId);\n }\n\n if (a.category === from && categoryCount !== 0 && a.alternateResponses && a.alternateResponses[alternateIndex]) {\n a.alternateResponses[alternateIndex] = a.alternateResponses[alternateIndex].filter((resp) => resp !== choiceId);\n }\n\n return a;\n });\n};\n\nexport const stillSelectable = (h, builtCategories) => {\n if (h.categoryCount > 0) {\n const count = countChosen(h, builtCategories);\n\n return count < h.categoryCount;\n } else {\n return true;\n }\n};\n\n/**\n * returns all choices with property 'correct' set to boolean\n * @param {string[]} possibleResponseChoices\n * @param {Object[]} builtCategoryChoices\n *\n * @returns {Object}, returns builtChoices: BuiltChoice[] and allChoicesAreCorrect: boolean\n * BuiltChoice = { id: choiceId, content: choiceContent, correct: boolean }\n */\nexport const buildChoices = (possibleResponseChoices, builtCategoryChoices) => {\n return builtCategoryChoices.reduce(\n (acc, builtChoice) => {\n // set correct value on each choice that was selected by user\n const index = acc.copyOfPossibleResponse.findIndex((cRC) => builtChoice && cRC === builtChoice.id);\n\n // if the choice exists in the correct response\n // set the correct: true\n if (index >= 0) {\n acc.builtChoices.push({\n ...builtChoice,\n correct: true,\n });\n acc.copyOfPossibleResponse = [\n ...acc.copyOfPossibleResponse.slice(0, index),\n ...acc.copyOfPossibleResponse.slice(index + 1),\n ];\n } else {\n acc.builtChoices.push({\n ...builtChoice,\n correct: false,\n });\n acc.allChoicesAreCorrect = false;\n }\n\n return acc;\n },\n {\n builtChoices: [],\n copyOfPossibleResponse: [...possibleResponseChoices],\n allChoicesAreCorrect: true,\n },\n );\n};\n\n/**\n * returns corrected answer using this possible correct response\n * @param {Object} possibleResponse, has form: { CategoryId: ChoiceId[] }\n * @param {Object[]} builtCategories\n *\n * @returns {Object}, returns builtCategories: BuiltCategory[] and correct: boolean\n * BuiltCategory = { id: categoryId, label: categoryLabel, correct: boolean, choices: BuiltChoice[] }\n * BuiltChoice = { id: choiceId, content: choiceContent, correct: boolean }\n */\nexport const getBuiltCategories = (possibleResponse, builtCategories) =>\n builtCategories.reduce(\n (acc, builtCategory) => {\n const possibleResponseChoices = possibleResponse[builtCategory.id] || []; // the correct choices for this category\n const builtCategoryChoices = builtCategory.choices || []; // the choices in the answer\n\n const { builtChoices, allChoicesAreCorrect } = buildChoices(possibleResponseChoices, builtCategoryChoices);\n const allChoicesAreInAnswer = builtCategoryChoices.length === possibleResponseChoices.length;\n\n acc.builtCategories.push({\n ...builtCategory,\n correct: allChoicesAreCorrect && allChoicesAreInAnswer,\n choices: builtChoices,\n });\n acc.correct = acc.correct && allChoicesAreCorrect && allChoicesAreInAnswer;\n\n return acc;\n },\n { builtCategories: [], correct: true },\n );\n\n/**\n * returns all the possible responses by combining the proper alternate responses\n * @param {Object[]} correctResponse\n *\n * @returns {Object[]}, returns Response[]\n * Response = { CategoryId: ChoiceId[] },\n */\nexport const getAllPossibleResponses = (correctResponse) => {\n if (!correctResponse) {\n return [];\n }\n\n return correctResponse.reduce((acc, cR) => {\n // main response\n if (acc[0]) {\n acc[0][cR.category] = cR.choices;\n } else {\n acc.push({ [cR.category]: cR.choices });\n }\n\n // alternate responses\n if (cR.alternateResponses) {\n cR.alternateResponses.forEach((aR, index) => {\n if (acc[index + 1]) {\n acc[index + 1][cR.category] = aR;\n } else {\n acc.push({ [cR.category]: aR });\n }\n });\n }\n\n return acc;\n }, []);\n};\n\n/**\n * build the categories to be displayed, where each category has its own list of choices\n * @param {Object[]} categories\n * @param {{id:string}[]} choices\n * @param {{category: string, choices:string[]}[]} answers\n *\n * @returns {Object[]}, returns BuiltCategory[]\n * BuiltCategory = { id: categoryId, label: categoryLabel, choices: BuiltChoice[]},\n * BuiltChoice = { id: choiceId, content: choiceContent }\n */\nexport const buildCategories = (categories, choices, answers) => {\n categories = categories || [];\n answers = answers || [];\n choices = choices || [];\n\n return categories.map((category) => {\n const answer = answers.find((answer) => answer.category === category.id);\n const { choices: answerChoices = [] } = answer || {};\n\n return {\n ...category,\n choices: answerChoices.map((chId) => choices.find((ch) => ch.id === chId)),\n };\n });\n};\n\n/**\n * build the choice and category state\n * @param {Object[]} categories\n * @param {{id:string}[]} choices\n * @param {{category: string, choices:string[]}[]} answers\n *\n * @param correctResponse\n * @returns { categories: Category[], choices: Choice[], correct: boolean, bestResponse: Response }, where Response: { categoryId: choiceId[] }\n */\nexport const buildState = (categories, choices, answers, correctResponse) => {\n categories = categories || [];\n choices = choices || [];\n answers = answers || [];\n\n const allResponses = getAllPossibleResponses(correctResponse) || [];\n\n let builtCategories = buildCategories(categories, choices, answers);\n let bestResponse;\n let entirelyCorrect;\n\n // at least one defined correct response\n if (allResponses.length) {\n const builtData = allResponses.reduce(\n (acc, possibleResponse) => {\n // set correctness for each possible response\n const { builtCategories: categoriesWithChoices, correct } = getBuiltCategories(\n possibleResponse,\n builtCategories,\n );\n\n // if bestResponse not found yet OR no correct response found yet and this one is the correct one\n if (acc.bestResponse === null || (!acc.entirelyCorrect && correct)) {\n return {\n bestResponse: possibleResponse,\n builtCategories: categoriesWithChoices,\n entirelyCorrect: correct,\n };\n }\n\n return acc;\n },\n {\n bestResponse: null,\n builtCategories: [],\n entirelyCorrect: false,\n },\n );\n\n builtCategories = builtData.builtCategories;\n bestResponse = builtData.bestResponse;\n entirelyCorrect = builtData.entirelyCorrect;\n }\n\n const filteredChoices = choices.map((ch) => (stillSelectable(ch, builtCategories) ? ch : { empty: true }));\n\n return {\n choices: filteredChoices,\n categories: builtCategories,\n correct: entirelyCorrect,\n bestResponse,\n };\n};\n"],"file":"index.js"}
package/lib/scoring.js ADDED
@@ -0,0 +1,145 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.score = void 0;
9
+
10
+ var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
11
+
12
+ var _debug = _interopRequireDefault(require("debug"));
13
+
14
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
15
+
16
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
17
+
18
+ var log = (0, _debug["default"])('@pie-lib:categorize:scoring');
19
+
20
+ var getWeightingRules = function getWeightingRules(scoring) {
21
+ if (!scoring || !scoring.weighting) {
22
+ return [];
23
+ } else {
24
+ if (!scoring.weighting.enabled) {
25
+ return [];
26
+ } else {
27
+ var rules = scoring.weighting ? scoring.weighting.rules || [] : [];
28
+ return rules;
29
+ }
30
+ }
31
+ };
32
+
33
+ var getPartialRulesForCategory = function getPartialRulesForCategory(partial, categoryId) {
34
+ log('partial? ', partial);
35
+
36
+ if (!partial || !partial.enabled) {
37
+ return;
38
+ } else {
39
+ var pr = partial.rules.find(function (pr) {
40
+ return pr.category === categoryId;
41
+ });
42
+ return pr ? pr.rules || [] : [];
43
+ }
44
+ };
45
+ /**
46
+ *
47
+ * Calculate score based on the categories model generated from `buildState` and the partial scoring rules.
48
+ * @param {*} categories - this is the categories that you get from `buildState`.
49
+ * @param {*} scoring - scoring config.
50
+ * @see ../index#buildState
51
+ */
52
+
53
+
54
+ var score = function score(categories, scoring) {
55
+ return new Promise(function (resolve) {
56
+ log('categories: ', categories, 'scoring: ', scoring);
57
+ var weightingRules = getWeightingRules(scoring);
58
+ var weights = categories.map(function (c) {
59
+ var r = weightingRules.find(function (r) {
60
+ return r.category === c.id;
61
+ }) || {
62
+ points: 1
63
+ };
64
+ return _objectSpread(_objectSpread({}, r), {}, {
65
+ category: c.id
66
+ });
67
+ });
68
+ log('weights: ', weights);
69
+ var weightTotal = categories.reduce(function (total, c) {
70
+ var r = weights.find(function (r) {
71
+ return r.category === c.id;
72
+ });
73
+ return total += r.points;
74
+ }, 0);
75
+ log('total: ', weightTotal);
76
+ var withScore = categories.map(function (c) {
77
+ var w = weights.find(function (r) {
78
+ return r.category === c.id;
79
+ }).points;
80
+ log('category: ', c);
81
+
82
+ if (c.correct === true) {
83
+ return {
84
+ category: c.id,
85
+ score: w,
86
+ points: w
87
+ };
88
+ } else {
89
+ var rules = getPartialRulesForCategory(scoring.partial, c.id);
90
+ log('partial rules for category: ', rules);
91
+
92
+ if (!rules) {
93
+ return {
94
+ category: c.id,
95
+ score: 0,
96
+ points: w
97
+ };
98
+ } else {
99
+ var correctCount = (c.choices || []).filter(function (h) {
100
+ return h.correct;
101
+ }).length;
102
+ log('correctCount: ', correctCount);
103
+ var rule = rules.find(function (u) {
104
+ return u.count === correctCount;
105
+ });
106
+ log('rule: ', rule);
107
+ rule = rule || {
108
+ percent: 0,
109
+ count: correctCount
110
+ };
111
+
112
+ var _score = w * (rule.percent / 100);
113
+
114
+ return {
115
+ category: c.id,
116
+ score: _score,
117
+ points: w,
118
+ partial: {
119
+ correctChoices: correctCount,
120
+ rule: rule
121
+ }
122
+ };
123
+ }
124
+ }
125
+ });
126
+ var weightedScore = withScore.reduce(function (sum, c) {
127
+ return sum += c.score;
128
+ }, 0);
129
+ log('weightedScore: ', weightedScore);
130
+ var score = parseFloat((weightedScore / weightTotal).toFixed(2), 10);
131
+ resolve({
132
+ score: score,
133
+ details: {
134
+ weighted: {
135
+ total: weightTotal,
136
+ score: weightedScore
137
+ },
138
+ categories: withScore
139
+ }
140
+ });
141
+ });
142
+ };
143
+
144
+ exports.score = score;
145
+ //# sourceMappingURL=scoring.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/scoring.js"],"names":["log","getWeightingRules","scoring","weighting","enabled","rules","getPartialRulesForCategory","partial","categoryId","pr","find","category","score","categories","Promise","resolve","weightingRules","weights","map","c","r","id","points","weightTotal","reduce","total","withScore","w","correct","correctCount","choices","filter","h","length","rule","u","count","percent","correctChoices","weightedScore","sum","parseFloat","toFixed","details","weighted"],"mappings":";;;;;;;;;;;AAAA;;;;;;AAEA,IAAMA,GAAG,GAAG,uBAAM,6BAAN,CAAZ;;AAEA,IAAMC,iBAAiB,GAAG,SAApBA,iBAAoB,CAACC,OAAD,EAAa;AACrC,MAAI,CAACA,OAAD,IAAY,CAACA,OAAO,CAACC,SAAzB,EAAoC;AAClC,WAAO,EAAP;AACD,GAFD,MAEO;AACL,QAAI,CAACD,OAAO,CAACC,SAAR,CAAkBC,OAAvB,EAAgC;AAC9B,aAAO,EAAP;AACD,KAFD,MAEO;AACL,UAAMC,KAAK,GAAGH,OAAO,CAACC,SAAR,GAAoBD,OAAO,CAACC,SAAR,CAAkBE,KAAlB,IAA2B,EAA/C,GAAoD,EAAlE;AAEA,aAAOA,KAAP;AACD;AACF;AACF,CAZD;;AAcA,IAAMC,0BAA0B,GAAG,SAA7BA,0BAA6B,CAACC,OAAD,EAAUC,UAAV,EAAyB;AAC1DR,EAAAA,GAAG,CAAC,WAAD,EAAcO,OAAd,CAAH;;AAEA,MAAI,CAACA,OAAD,IAAY,CAACA,OAAO,CAACH,OAAzB,EAAkC;AAChC;AACD,GAFD,MAEO;AACL,QAAMK,EAAE,GAAGF,OAAO,CAACF,KAAR,CAAcK,IAAd,CAAmB,UAACD,EAAD;AAAA,aAAQA,EAAE,CAACE,QAAH,KAAgBH,UAAxB;AAAA,KAAnB,CAAX;AAEA,WAAOC,EAAE,GAAGA,EAAE,CAACJ,KAAH,IAAY,EAAf,GAAoB,EAA7B;AACD;AACF,CAVD;AAYA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAEO,IAAMO,KAAK,GAAG,SAARA,KAAQ,CAACC,UAAD,EAAaX,OAAb;AAAA,SACnB,IAAIY,OAAJ,CAA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ACP+B,cAAAA,cAAc,EAAET,YADT;AAEPK,cAAAA,IAAI,EAAEA;AAFC;AAJJ,WAAP;AASD;AACF;AACF,KArCiB,CAAlB;AAuCA,QAAMK,aAAa,GAAGb,SAAS,CAACF,MAAV,CAAiB,UAACgB,GAAD,EAAMrB,CAAN,EAAY;AACjD,aAAQqB,GAAG,IAAIrB,CAAC,CAACP,KAAjB;AACD,KAFqB,EAEnB,CAFmB,CAAtB;AAIAZ,IAAAA,GAAG,CAAC,iBAAD,EAAoBuC,aAApB,CAAH;AAEA,QAAM3B,KAAK,GAAG6B,UAAU,CAAC,CAACF,aAAa,GAAGhB,WAAjB,EAA8BmB,OAA9B,CAAsC,CAAtC,CAAD,EAA2C,EAA3C,CAAxB;AAEA3B,IAAAA,OAAO,CAAC;AACNH,MAAAA,KAAK,EAALA,KADM;AAEN+B,MAAAA,OAAO,EAAE;AACPC,QAAAA,QAAQ,EAAE;AACRnB,UAAAA,KAAK,EAAEF,WADC;AAERX,UAAAA,KAAK,EAAE2B;AAFC,SADH;AAKP1B,QAAAA,UAAU,EAAEa;AALL;AAFH,KAAD,CAAP;AAUD,GA9ED,CADmB;AAAA,CAAd","sourcesContent":["import debug from 'debug';\n\nconst log = debug('@pie-lib:categorize:scoring');\n\nconst getWeightingRules = (scoring) => {\n if (!scoring || !scoring.weighting) {\n return [];\n } else {\n if (!scoring.weighting.enabled) {\n return [];\n } else {\n const rules = scoring.weighting ? scoring.weighting.rules || [] : [];\n\n return rules;\n }\n }\n};\n\nconst getPartialRulesForCategory = (partial, categoryId) => {\n log('partial? ', partial);\n\n if (!partial || !partial.enabled) {\n return;\n } else {\n const pr = partial.rules.find((pr) => pr.category === categoryId);\n\n return pr ? pr.rules || [] : [];\n }\n};\n\n/**\n *\n * Calculate score based on the categories model generated from `buildState` and the partial scoring rules.\n * @param {*} categories - this is the categories that you get from `buildState`.\n * @param {*} scoring - scoring config.\n * @see ../index#buildState\n */\n\nexport const score = (categories, scoring) =>\n new Promise((resolve) => {\n log('categories: ', categories, 'scoring: ', scoring);\n\n const weightingRules = getWeightingRules(scoring);\n\n const weights = categories.map((c) => {\n const r = weightingRules.find((r) => r.category === c.id) || { points: 1 };\n\n return { ...r, category: c.id };\n });\n\n log('weights: ', weights);\n\n const weightTotal = categories.reduce((total, c) => {\n const r = weights.find((r) => r.category === c.id);\n\n return (total += r.points);\n }, 0);\n\n log('total: ', weightTotal);\n\n const withScore = categories.map((c) => {\n const w = weights.find((r) => r.category === c.id).points;\n\n log('category: ', c);\n if (c.correct === true) {\n return { category: c.id, score: w, points: w };\n } else {\n const rules = getPartialRulesForCategory(scoring.partial, c.id);\n\n log('partial rules for category: ', rules);\n\n if (!rules) {\n return { category: c.id, score: 0, points: w };\n } else {\n const correctCount = (c.choices || []).filter((h) => h.correct).length;\n\n log('correctCount: ', correctCount);\n\n let rule = rules.find((u) => u.count === correctCount);\n\n log('rule: ', rule);\n\n rule = rule || { percent: 0, count: correctCount };\n\n const score = w * (rule.percent / 100);\n\n return {\n category: c.id,\n score,\n points: w,\n partial: {\n correctChoices: correctCount,\n rule: rule,\n },\n };\n }\n }\n });\n\n const weightedScore = withScore.reduce((sum, c) => {\n return (sum += c.score);\n }, 0);\n\n log('weightedScore: ', weightedScore);\n\n const score = parseFloat((weightedScore / weightTotal).toFixed(2), 10);\n\n resolve({\n score,\n details: {\n weighted: {\n total: weightTotal,\n score: weightedScore,\n },\n categories: withScore,\n },\n });\n });\n"],"file":"scoring.js"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pie-lib/categorize",
3
- "version": "0.14.0",
3
+ "version": "0.16.0",
4
4
  "description": "",
5
5
  "main": "lib/index.js",
6
6
  "module": "src/index.js",
@@ -14,5 +14,5 @@
14
14
  "scripts": {},
15
15
  "author": "",
16
16
  "license": "ISC",
17
- "gitHead": "889a13bfea2c768b8a3a6eabfc6fe7b7725aa832"
17
+ "gitHead": "7ca3b0a214af57d742b4a9de6d8b424d31da1469"
18
18
  }