UNPKG

@instructure/quiz-interactions

Version:

A React UI component Library for quiz interaction types.

59 lines (49 loc) 1.4 kB
import {searchForFormulaSolution} from './util' import {loadMathjs} from '../common/util' export default class GenerateSolutionsService { constructor({onStart, onSuccess, onFailure, onCancel}) { this._onStart = onStart this._onSuccess = onSuccess this._onFailure = onFailure this._onCancel = onCancel this._promise = Promise.resolve() } start(numSolutions, variables, formula, precision, scientificNotation = false) { this._onStart() const foundSolutions = [] const promises = [] for (let i = 0; i < numSolutions; i++) { promises.push( loadMathjs().then(() => { const solution = searchForFormulaSolution( variables, formula, foundSolutions, precision, scientificNotation, ) if (solution !== null) { foundSolutions.push(solution) } }), ) } const promise = Promise.all(promises).then(() => { if (!this.__promiseIsCurrent(promise)) { return } foundSolutions.length === numSolutions ? this._onSuccess(foundSolutions) : this._onFailure(foundSolutions) }) this._promise = promise return promise } cancel() { this._promise = Promise.resolve() this._onCancel() } __promiseIsCurrent(promise) { return promise === this._promise } }