@instructure/quiz-interactions
Version:
A React UI component Library for quiz interaction types.
222 lines (221 loc) • 10.2 kB
JavaScript
function _array_like_to_array(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
return arr2;
}
function _array_with_holes(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterable_to_array_limit(arr, i) {
var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
if (_i == null) return;
var _arr = [];
var _n = true;
var _d = false;
var _s, _e;
try {
for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally{
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally{
if (_d) throw _e;
}
}
return _arr;
}
function _non_iterable_rest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _sliced_to_array(arr, i) {
return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _type_of(obj) {
"@swc/helpers - typeof";
return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
}
function _unsupported_iterable_to_array(o, minLen) {
if (!o) return;
if (typeof o === "string") return _array_like_to_array(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
import Decimal from 'decimal.js';
import sortBy from 'lodash/sortBy';
import { formatScientificNotation, isScientificNotation, parseScientificNotation } from '@instructure/quiz-scientific-notation';
import t from '@instructure/quiz-i18n/format-message';
import setFromArray from '../../../util/setFromArray';
import { mathjsIsLoaded, mathjsLoadingWrapper } from '../common/util';
export function toPrecision(n, precision) {
if (isScientificNotation(n)) {
var _parseScientificNotation = _sliced_to_array(parseScientificNotation(n), 2), mantissa = _parseScientificNotation[0], exponent = _parseScientificNotation[1];
return formatScientificNotation(Number(mantissa).toFixed(precision), exponent);
}
return isNaN(n) ? n : Number(n).toFixed(precision);
}
function toDecimal(n) {
if (isScientificNotation(n)) {
var _parseScientificNotation = _sliced_to_array(parseScientificNotation(n), 2), mantissa = _parseScientificNotation[0], exponent = _parseScientificNotation[1];
return new Decimal("".concat(mantissa, "e").concat(exponent));
}
return new Decimal(n);
}
function toInput(n) {
return isScientificNotation(n) ? toDecimal(n) : Number(n);
}
var decimalToString = function(input) {
if (input.minMaxScientific) {
return toDecimal(input.value).toString();
}
return toDecimal(input.value);
};
var toScientificNotation = function(n, precision) {
var _n_toExponential_match_slice = _sliced_to_array(n.toExponential(precision).match(/^(.+)e\+?(.+)$/).slice(1), 2), mantissa = _n_toExponential_match_slice[0], exponent = _n_toExponential_match_slice[1];
return formatScientificNotation(mantissa, exponent);
};
var randomBetween = function(min, max, random) {
return max.minus(min).times(random()).plus(min);
};
var randomInRange = function(min, max, precision, random, scientificNotation) {
if (min.greaterThan(max)) {
return null;
}
var value = randomBetween(min, max, random);
return scientificNotation ? toScientificNotation(value, precision) : fixNegativeZero(value.toFixed(precision));
};
var fixNegativeZero = function(num) {
var math = mathjsLoadingWrapper.mathjs;
if (math.isZero(num) && num[0] === '-') {
return num.substring(1);
}
return num;
};
var generateInputs = function(variables, random) {
return variables.map(function(param) {
var name = param.name, min = param.min, max = param.max, precision = param.precision;
var minMaxScientific = isScientificNotation(min) && isScientificNotation(max);
var input = {
name: name,
value: randomInRange(toDecimal(min), toDecimal(max), Number(precision), random, minMaxScientific)
};
if (minMaxScientific) {
input.minMaxScientific = true;
}
return input;
});
};
var hashifyInputs = function(inputs, toInputNumber) {
var result = {};
inputs.forEach(function(input) {
result[input.name] = toInputNumber !== decimalToString ? toInputNumber(input.value) : toInputNumber(input);
});
return result;
};
var serializeInputs = function(inputs) {
return sortBy(inputs, function(input) {
return input.name;
}).map(function(input) {
return "".concat(input.name, ":").concat(input.value);
}).join('|');
};
var SEARCH_COUNT = 100;
export var searchForFormulaSolution = function(variables, formula, previousSolutions, precision) {
var _loop = function(i) {
var inputs = genInputs(variables, random);
if (usedInputCache.has(serializeInputs(inputs))) {
return "continue" // eslint-disable-line no-continue
;
}
if (!mathjsIsLoaded()) {
throw new Error('attempt to call searchForFormulaSolution before math.js is loaded');
}
try {
var math = mathjsLoadingWrapper.mathjs;
// we replace function e() with the constant e
// and function pi() with the constant pi
// this is to match legacy canvas quizzes behavior which accepted both e/pi and e()/pi()
var node = math.parse(formula);
var transformed = node.transform(function(node, path, parent) {
if (node.isFunctionNode && node.fn.isSymbolNode && node.fn.name === 'e') {
return new math.expression.node.ConstantNode(Math.E);
} else if (node.isFunctionNode && node.fn.isSymbolNode && node.fn.name === 'pi') {
return new math.expression.node.ConstantNode(Math.PI);
} else {
return node;
}
});
var compiled = transformed.compile();
var outputArray = void 0;
try {
// first try using Decimal for floating point precision
outputArray = compiled.eval(hashifyInputs(inputs, toDecimal));
} catch (e) {
// Since some mathjs methods don't support Decimal,
// catch here and try again without it.
// If this one throws, it will be caught by outer try block
try {
outputArray = compiled.eval(hashifyInputs(inputs, toInput));
} catch (e) {
// If everything else fails, then the inputs are converted to string
// because mathjs couldn't support Decimal in scientific notation
// if this one throws, it will be caugh by outer try block
outputArray = compiled.eval(hashifyInputs(inputs, decimalToString));
}
}
// `mathjs.eval` spits out a number if the formula has one clause, and a ResultSet object
// with an `entries` array field if it has multiple clauses
var output = outputArray.entries ? outputArray.entries[outputArray.entries.length - 1] : outputArray;
if (output !== void 0) {
var decimal = new Decimal(output.toString());
if (!decimal.isNaN() && decimal.isFinite()) {
return {
v: {
inputs: inputs,
output: scientificNotation ? toScientificNotation(decimal, precisionValue) : decimal.toFixed(precisionValue)
}
};
}
}
} catch (e) {
return {
v: null
};
}
};
var scientificNotation = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : false, random = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : Math.random, searchCount = arguments.length > 6 && arguments[6] !== void 0 ? arguments[6] : SEARCH_COUNT, genInputs = arguments.length > 7 && arguments[7] !== void 0 ? arguments[7] : generateInputs;
var usedInputCache = setFromArray(previousSolutions.map(function(soln) {
return serializeInputs(soln.inputs);
}));
var precisionValue = Math.min(precision || 0, 16);
for(var i = 0; i < searchCount; i++){
var _ret = _loop(i);
if (_type_of(_ret) === "object") return _ret.v;
}
return null;
};
export var buildSolutionsGeneratedMessage = function(status, solutionsCount) {
if (status === STATUS_FAILED && solutionsCount === 0) {
return t('We were not able to find any solutions.');
} else if (status === STATUS_FAILED) {
return t("{ number, plural,\n one {We were only able to find 1 solution.}\n other {We were only able to find # solutions.}\n }", {
number: solutionsCount
});
} else {
return t("{ number, plural,\n one {We were able to find 1 solution.}\n other {We were able to find # solutions.}\n }", {
number: solutionsCount
});
}
};
export var STATUS_STOPPED = 'STATUS_STOPPED';
export var STATUS_RUNNING = 'STATUS_RUNNING';
export var STATUS_FAILED = 'STATUS_FAILED';
export var STATUS_FORMULA_SETUP_INVALID = 'STATUS_FORMULA_SETUP_INVALID';
export var STATUS_CANCELED = 'STATUS_CANCELED';