@instructure/quiz-interactions
Version:
A React UI component Library for quiz interaction types.
190 lines (189 loc) • 8.21 kB
JavaScript
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
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/es/format-message';
import setFromArray from '../../../util/setFromArray';
import { mathjsIsLoaded, mathjsLoadingWrapper } from '../common/util';
export function toPrecision(n, precision) {
if (isScientificNotation(n)) {
var _parseScientificNotat = parseScientificNotation(n),
_parseScientificNotat2 = _slicedToArray(_parseScientificNotat, 2),
mantissa = _parseScientificNotat2[0],
exponent = _parseScientificNotat2[1];
return formatScientificNotation(Number(mantissa).toFixed(precision), exponent);
}
return isNaN(n) ? n : Number(n).toFixed(precision);
}
function toDecimal(n) {
if (isScientificNotation(n)) {
var _parseScientificNotat3 = parseScientificNotation(n),
_parseScientificNotat4 = _slicedToArray(_parseScientificNotat3, 2),
mantissa = _parseScientificNotat4[0],
exponent = _parseScientificNotat4[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 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 = _slicedToArray(_n$toExponential$matc, 2),
mantissa = _n$toExponential$matc2[0],
exponent = _n$toExponential$matc2[1];
return 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 = 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 = 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 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 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 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 = setFromArray(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 (!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;
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(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;
};
export var buildSolutionsGeneratedMessage = function buildSolutionsGeneratedMessage(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';