simple-squiggle

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

setSize.js (1613B)


      1 import { flatten } from '../../utils/array.js';
      2 import { factory } from '../../utils/factory.js';
      3 var name = 'setSize';
      4 var dependencies = ['typed', 'compareNatural'];
      5 export var createSetSize = /* #__PURE__ */factory(name, dependencies, _ref => {
      6   var {
      7     typed,
      8     compareNatural
      9   } = _ref;
     10 
     11   /**
     12    * Count the number of elements of a (multi)set. When a second parameter is 'true', count only the unique values.
     13    * A multi-dimension array will be converted to a single-dimension array before the operation.
     14    *
     15    * Syntax:
     16    *
     17    *    math.setSize(set)
     18    *    math.setSize(set, unique)
     19    *
     20    * Examples:
     21    *
     22    *    math.setSize([1, 2, 2, 4])          // returns 4
     23    *    math.setSize([1, 2, 2, 4], true)    // returns 3
     24    *
     25    * See also:
     26    *
     27    *    setUnion, setIntersect, setDifference
     28    *
     29    * @param {Array | Matrix}    a  A multiset
     30    * @return {number}            The number of elements of the (multi)set
     31    */
     32   return typed(name, {
     33     'Array | Matrix': function ArrayMatrix(a) {
     34       return Array.isArray(a) ? flatten(a).length : flatten(a.toArray()).length;
     35     },
     36     'Array | Matrix, boolean': function ArrayMatrixBoolean(a, unique) {
     37       if (unique === false || a.length === 0) {
     38         return Array.isArray(a) ? flatten(a).length : flatten(a.toArray()).length;
     39       } else {
     40         var b = flatten(Array.isArray(a) ? a : a.toArray()).sort(compareNatural);
     41         var count = 1;
     42 
     43         for (var i = 1; i < b.length; i++) {
     44           if (compareNatural(b[i], b[i - 1]) !== 0) {
     45             count++;
     46           }
     47         }
     48 
     49         return count;
     50       }
     51     }
     52   });
     53 });