simple-squiggle

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

forEach.js (2174B)


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