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