simple-squiggle

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

leafCount.js (1856B)


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