leafCount.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.createLeafCount = void 0;
  6. var _factory = require("../../utils/factory.js");
  7. var name = 'leafCount';
  8. var dependencies = ['parse', 'typed'];
  9. var createLeafCount = /* #__PURE__ */(0, _factory.factory)(name, dependencies, function (_ref) {
  10. var parse = _ref.parse,
  11. typed = _ref.typed;
  12. // This does the real work, but we don't have to recurse through
  13. // a typed call if we separate it out
  14. function countLeaves(node) {
  15. var count = 0;
  16. node.forEach(function (n) {
  17. count += countLeaves(n);
  18. });
  19. return count || 1;
  20. }
  21. /**
  22. * Gives the number of "leaf nodes" in the parse tree of the given expression
  23. * A leaf node is one that has no subexpressions, essentially either a
  24. * symbol or a constant. Note that `5!` has just one leaf, the '5'; the
  25. * unary factorial operator does not add a leaf. On the other hand,
  26. * function symbols do add leaves, so `sin(x)/cos(x)` has four leaves.
  27. *
  28. * The `simplify()` function should generally not increase the `leafCount()`
  29. * of an expression, although currently there is no guarantee that it never
  30. * does so. In many cases, `simplify()` reduces the leaf count.
  31. *
  32. * Syntax:
  33. *
  34. * leafCount(expr)
  35. *
  36. * Examples:
  37. *
  38. * math.leafCount('x') // 1
  39. * math.leafCount(math.parse('a*d-b*c')) // 4
  40. * math.leafCount('[a,b;c,d][0,1]') // 6
  41. *
  42. * See also:
  43. *
  44. * simplify
  45. *
  46. * @param {Node|string} expr The expression to count the leaves of
  47. *
  48. * @return {number} The number of leaves of `expr`
  49. *
  50. */
  51. return typed(name, {
  52. Node: function Node(expr) {
  53. return countLeaves(expr);
  54. }
  55. });
  56. });
  57. exports.createLeafCount = createLeafCount;