simple-squiggle

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

forEach.js (2011B)


      1 import { maxArgumentCount } from '../../utils/function.js';
      2 import { forEach as forEachArray } from '../../utils/array.js';
      3 import { factory } from '../../utils/factory.js';
      4 var name = 'forEach';
      5 var dependencies = ['typed'];
      6 export var createForEach = /* #__PURE__ */factory(name, dependencies, _ref => {
      7   var {
      8     typed
      9   } = _ref;
     10 
     11   /**
     12    * Iterate over all elements of a matrix/array, and executes the given callback function.
     13    *
     14    * Syntax:
     15    *
     16    *    math.forEach(x, callback)
     17    *
     18    * Examples:
     19    *
     20    *    math.forEach([1, 2, 3], function(value) {
     21    *      console.log(value)
     22    *    })
     23    *    // outputs 1, 2, 3
     24    *
     25    * See also:
     26    *
     27    *    filter, map, sort
     28    *
     29    * @param {Matrix | Array} x    The matrix to iterate on.
     30    * @param {Function} callback   The callback function is invoked with three
     31    *                              parameters: the value of the element, the index
     32    *                              of the element, and the Matrix/array being traversed.
     33    */
     34   return typed(name, {
     35     'Array, function': _forEach,
     36     'Matrix, function': function MatrixFunction(x, callback) {
     37       return x.forEach(callback);
     38     }
     39   });
     40 });
     41 /**
     42  * forEach for a multi dimensional array
     43  * @param {Array} array
     44  * @param {Function} callback
     45  * @private
     46  */
     47 
     48 function _forEach(array, callback) {
     49   // figure out what number of arguments the callback function expects
     50   var args = maxArgumentCount(callback);
     51 
     52   var recurse = function recurse(value, index) {
     53     if (Array.isArray(value)) {
     54       forEachArray(value, function (child, i) {
     55         // we create a copy of the index array and append the new index value
     56         recurse(child, index.concat(i));
     57       });
     58     } else {
     59       // invoke the callback function with the right number of arguments
     60       if (args === 1) {
     61         callback(value);
     62       } else if (args === 2) {
     63         callback(value, index);
     64       } else {
     65         // 3 or -1
     66         callback(value, index, array);
     67       }
     68     }
     69   };
     70 
     71   recurse(array, []);
     72 }