leafCount.js 1.5 KB

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