PageRenderTime 38ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/function/expression/compile.js

https://github.com/husayt/mathjs
JavaScript | 64 lines | 23 code | 4 blank | 37 comment | 6 complexity | 6e08cd06c177214962b4d1ccbd0dda97 MD5 | raw file
Possible License(s): Apache-2.0
  1. module.exports = function (math, config) {
  2. var util = require('../../util/index'),
  3. _parse = require('../../expression/parse'),
  4. collection = require('../../type/collection'),
  5. isString = util.string.isString,
  6. isCollection = collection.isCollection;
  7. /**
  8. * Parse and compile an expression.
  9. * Returns a an object with a function `eval([scope])` to evaluate the
  10. * compiled expression.
  11. *
  12. * Syntax:
  13. *
  14. * var code = math.compile(expr)
  15. * var codes = math.compile([expr1, expr2, expr3, ...])
  16. *
  17. * Examples:
  18. *
  19. * var code = math.compile('sqrt(3^2 + 4^2)');
  20. * code.eval(); // 5
  21. *
  22. * var scope = {a: 3, b: 4}
  23. * var code = math.compile('a * b'); // 12
  24. * code.eval(scope); // 12
  25. * scope.a = 5;
  26. * code.eval(scope); // 20
  27. *
  28. * var nodes = math.compile(['a = 3', 'b = 4', 'a * b']);
  29. * nodes[2].eval(); // 12
  30. *
  31. * See also:
  32. *
  33. * parse, eval
  34. *
  35. * @param {String | String[] | Matrix} expr
  36. * The expression to be compiled
  37. * @return {{eval: Function} | Array.<{eval: Function}>} code
  38. * An object with the compiled expression
  39. * @throws {Error}
  40. */
  41. math.compile = function compile (expr) {
  42. if (arguments.length != 1) {
  43. throw new math.error.ArgumentsError('compile', arguments.length, 1);
  44. }
  45. if (isString(expr)) {
  46. // evaluate a single expression
  47. return _parse(expr).compile(math);
  48. }
  49. else if (isCollection(expr)) {
  50. // evaluate an array or matrix with expressions
  51. return collection.deepMap(expr, function (elem) {
  52. return _parse(elem).compile(math);
  53. });
  54. }
  55. else {
  56. // oops
  57. throw new TypeError('String, array, or matrix expected');
  58. }
  59. }
  60. };