UNPKG

@instructure/quiz-interactions

Version:

A React UI component Library for quiz interaction types.

198 lines (196 loc) • 9.35 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.searchForFormulaSolution = exports.buildSolutionsGeneratedMessage = exports.STATUS_STOPPED = exports.STATUS_RUNNING = exports.STATUS_FORMULA_SETUP_INVALID = exports.STATUS_FAILED = exports.STATUS_CANCELED = void 0; exports.toPrecision = toPrecision; var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); var _decimal = _interopRequireDefault(require("decimal.js")); var _sortBy = _interopRequireDefault(require("lodash/sortBy")); var _quizScientificNotation = require("@instructure/quiz-scientific-notation"); var _formatMessage = _interopRequireDefault(require("@instructure/quiz-i18n/es/format-message")); var _setFromArray = _interopRequireDefault(require("../../../util/setFromArray")); var _util = require("../common/util"); function toPrecision(n, precision) { if ((0, _quizScientificNotation.isScientificNotation)(n)) { var _parseScientificNotat = (0, _quizScientificNotation.parseScientificNotation)(n), _parseScientificNotat2 = (0, _slicedToArray2["default"])(_parseScientificNotat, 2), mantissa = _parseScientificNotat2[0], exponent = _parseScientificNotat2[1]; return (0, _quizScientificNotation.formatScientificNotation)(Number(mantissa).toFixed(precision), exponent); } return isNaN(n) ? n : Number(n).toFixed(precision); } function toDecimal(n) { if ((0, _quizScientificNotation.isScientificNotation)(n)) { var _parseScientificNotat3 = (0, _quizScientificNotation.parseScientificNotation)(n), _parseScientificNotat4 = (0, _slicedToArray2["default"])(_parseScientificNotat3, 2), mantissa = _parseScientificNotat4[0], exponent = _parseScientificNotat4[1]; return new _decimal["default"]("".concat(mantissa, "e").concat(exponent)); } return new _decimal["default"](n); } function toInput(n) { return (0, _quizScientificNotation.isScientificNotation)(n) ? toDecimal(n) : Number(n); } var decimalToString = function decimalToString(input) { if (input.minMaxScientific) { return toDecimal(input.value).toString(); } return toDecimal(input.value); }; var toScientificNotation = function toScientificNotation(n, precision) { var _n$toExponential$matc = n.toExponential(precision).match(/^(.+)e\+?(.+)$/).slice(1), _n$toExponential$matc2 = (0, _slicedToArray2["default"])(_n$toExponential$matc, 2), mantissa = _n$toExponential$matc2[0], exponent = _n$toExponential$matc2[1]; return (0, _quizScientificNotation.formatScientificNotation)(mantissa, exponent); }; var randomBetween = function randomBetween(min, max, random) { return max.minus(min).times(random()).plus(min); }; var randomInRange = function randomInRange(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 fixNegativeZero(num) { var math = _util.mathjsLoadingWrapper.mathjs; if (math.isZero(num) && num[0] === '-') { return num.substring(1); } return num; }; var generateInputs = function generateInputs(variables, random) { return variables.map(function (_ref) { var name = _ref.name, min = _ref.min, max = _ref.max, precision = _ref.precision; var minMaxScientific = (0, _quizScientificNotation.isScientificNotation)(min) && (0, _quizScientificNotation.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 hashifyInputs(inputs, toInputNumber) { var result = {}; inputs.forEach(function (input) { result[input.name] = toInputNumber !== decimalToString ? toInputNumber(input.value) : toInputNumber(input); }); return result; }; var serializeInputs = function serializeInputs(inputs) { return (0, _sortBy["default"])(inputs, function (input) { return input.name; }).map(function (input) { return "".concat(input.name, ":").concat(input.value); }).join('|'); }; var SEARCH_COUNT = 100; var searchForFormulaSolution = exports.searchForFormulaSolution = function searchForFormulaSolution(variables, formula, previousSolutions, precision) { var scientificNotation = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; var random = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : Math.random; var searchCount = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : SEARCH_COUNT; var genInputs = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : generateInputs; var usedInputCache = (0, _setFromArray["default"])(previousSolutions.map(function (soln) { return serializeInputs(soln.inputs); })); var precisionValue = Math.min(precision || 0, 16); var _loop = function _loop() { var inputs = genInputs(variables, random); if (usedInputCache.has(serializeInputs(inputs))) { return 0; // continue // eslint-disable-line no-continue } if (!(0, _util.mathjsIsLoaded)()) { throw new Error('attempt to call searchForFormulaSolution before math.js is loaded'); } try { var math = _util.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; try { // first try using Decimal for floating point precision outputArray = compiled.eval(hashifyInputs(inputs, toDecimal)); } catch (_unused) { // 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 (_unused2) { // 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["default"](output.toString()); if (!decimal.isNaN() && decimal.isFinite()) { return { v: { inputs: inputs, output: scientificNotation ? toScientificNotation(decimal, precisionValue) : decimal.toFixed(precisionValue) } }; } } } catch (_unused3) { return { v: null }; } }, _ret; for (var i = 0; i < searchCount; i++) { _ret = _loop(); if (_ret === 0) continue; if (_ret) return _ret.v; } return null; }; var buildSolutionsGeneratedMessage = exports.buildSolutionsGeneratedMessage = function buildSolutionsGeneratedMessage(status, solutionsCount) { if (status === STATUS_FAILED && solutionsCount === 0) { return (0, _formatMessage["default"])('We were not able to find any solutions.'); } else if (status === STATUS_FAILED) { return (0, _formatMessage["default"])("{ 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 (0, _formatMessage["default"])("{ number, plural,\n one {We were able to find 1 solution.}\n other {We were able to find # solutions.}\n }", { number: solutionsCount }); } }; var STATUS_STOPPED = exports.STATUS_STOPPED = 'STATUS_STOPPED'; var STATUS_RUNNING = exports.STATUS_RUNNING = 'STATUS_RUNNING'; var STATUS_FAILED = exports.STATUS_FAILED = 'STATUS_FAILED'; var STATUS_FORMULA_SETUP_INVALID = exports.STATUS_FORMULA_SETUP_INVALID = 'STATUS_FORMULA_SETUP_INVALID'; var STATUS_CANCELED = exports.STATUS_CANCELED = 'STATUS_CANCELED';