UNPKG

algebraic-captcha

Version:

NodeJS math captcha package with algebraic formulas

63 lines 2.21 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const lodash_1 = require("lodash"); class FormulaBuilder { constructor(config) { this.config = config; } generateFormula() { const formulaChunks = this.generateFormulaChunks(); /* tslint:disable:function-constructor */ const answer = new Function(`return ${formulaChunks.join(' ')}`)(); /* tslint:enable:function-constructor */ const formula = formulaChunks.concat('=').concat(this.config.targetSymbol); return this.config.isFormulaMode() ? this.makeFormula(formula, answer) : this.makeEquation(formula, answer); } generateFormulaChunks() { const { minValue, maxValue, operandAmount, operandTypes } = this.config; const formulaParts = []; let index = 0; while (index < 2 * operandAmount + 1) { index % 2 === 0 ? formulaParts.push(lodash_1.random(minValue, maxValue).toString()) : formulaParts.push(lodash_1.sample(operandTypes)); index++; } return formulaParts; } /** * Returns formula in classic presentation * @example 5 + 1 = ? * @param {String[]} formula * @param {Number} answer * @returns {Object} * @private */ makeFormula(formula, answer) { const res = { formula, answer }; return res; } /** * Returns formula in equation presentation * @example 5 + ? = 6 * @param {String[]} formula * @param {Number} answer * @returns {IFormula} * @private */ makeEquation(formula, answer) { const operands = formula .slice(0, formula.length - 2) .filter((item, index) => index % 2 === 0) .map(Number); const target = lodash_1.sample(operands); const targetIndex = formula.indexOf(target.toString()); formula[targetIndex] = this.config.targetSymbol; formula[formula.length - 1] = answer.toString(); answer = target; const res = { formula, answer }; return res; } } exports.FormulaBuilder = FormulaBuilder; //# sourceMappingURL=formula-builder.js.map