simple-squiggle

A restricted subset of Squiggle
Log | Files | Refs | README

evaluate.js (2108B)


      1 import { deepMap } from '../../utils/collection.js';
      2 import { factory } from '../../utils/factory.js';
      3 import { createEmptyMap } from '../../utils/map.js';
      4 var name = 'evaluate';
      5 var dependencies = ['typed', 'parse'];
      6 export var createEvaluate = /* #__PURE__ */factory(name, dependencies, _ref => {
      7   var {
      8     typed,
      9     parse
     10   } = _ref;
     11 
     12   /**
     13    * Evaluate an expression.
     14    *
     15    * Note the evaluating arbitrary expressions may involve security risks,
     16    * see [https://mathjs.org/docs/expressions/security.html](https://mathjs.org/docs/expressions/security.html) for more information.
     17    *
     18    * Syntax:
     19    *
     20    *     math.evaluate(expr)
     21    *     math.evaluate(expr, scope)
     22    *     math.evaluate([expr1, expr2, expr3, ...])
     23    *     math.evaluate([expr1, expr2, expr3, ...], scope)
     24    *
     25    * Example:
     26    *
     27    *     math.evaluate('(2+3)/4')                // 1.25
     28    *     math.evaluate('sqrt(3^2 + 4^2)')        // 5
     29    *     math.evaluate('sqrt(-4)')               // 2i
     30    *     math.evaluate(['a=3', 'b=4', 'a*b'])    // [3, 4, 12]
     31    *
     32    *     let scope = {a:3, b:4}
     33    *     math.evaluate('a * b', scope)           // 12
     34    *
     35    * See also:
     36    *
     37    *    parse, compile
     38    *
     39    * @param {string | string[] | Matrix} expr   The expression to be evaluated
     40    * @param {Object} [scope]                    Scope to read/write variables
     41    * @return {*} The result of the expression
     42    * @throws {Error}
     43    */
     44   return typed(name, {
     45     string: function string(expr) {
     46       var scope = createEmptyMap();
     47       return parse(expr).compile().evaluate(scope);
     48     },
     49     'string, Map | Object': function stringMapObject(expr, scope) {
     50       return parse(expr).compile().evaluate(scope);
     51     },
     52     'Array | Matrix': function ArrayMatrix(expr) {
     53       var scope = createEmptyMap();
     54       return deepMap(expr, function (entry) {
     55         return parse(entry).compile().evaluate(scope);
     56       });
     57     },
     58     'Array | Matrix, Map | Object': function ArrayMatrixMapObject(expr, scope) {
     59       return deepMap(expr, function (entry) {
     60         return parse(entry).compile().evaluate(scope);
     61       });
     62     }
     63   });
     64 });