Nodejs Array Each eachRecursive(fieldName, filterOrDoFun, doFun)

Here you can find the source of eachRecursive(fieldName, filterOrDoFun, doFun)

Method Source Code

// Copyright 2015 Alec Thilenius
// All rights reserved.

/**//w w  w .j a  v a2  s.c om
 * Array Helpers
 */

/**
 * Runs a doFun on each item in a tree structure, where children are denoted by
 * 'fieldName'. An optional filter function can be provided as the second
 * argument, filtering what objects the doFun is called on, not what objects are
 * Crecursed downward.
 * Can be called in the forms:
 * eachRecursive(fieldName, doFunction)
 * eachRecursive(fieldName, filterFunction, doFuncation)
 */
Array.prototype.eachRecursive = function(fieldName, filterOrDoFun, doFun) {
  var filter = doFun ? filterOrDoFun : null;
  doFun = doFun || filterOrDoFun;
  var doArrayRecursive = function(arr) {
    if (!arr || !(arr instanceof Array)) {
      return;
    }
    for (var i = 0; i < arr.length; i++) {
      var item = arr[i];
      // Filter if provided
      if (!filter || filter(item)) {
        doFun(item);
      }
      // Recurse down children
      var children = item[fieldName];
      if (children && children instanceof Array) {
        doArrayRecursive(children);
      }
    }
  };
  doArrayRecursive(this);
};

Related

  1. each(method)
    Array.prototype.each = function(method) {
      for (var i = 0; i < this.length; i++) {
        this[i][method]()
    
  2. each(method)
    Array.prototype.each = function(method) {
      var _handBreak = false;
      function _break() { _handBreak = true; }
      for (var i = this.length - 1; i >= 0; i--) {
        if (_handBreak) return this;
        method.call(this, this[i], i, _break); 
      return this;
    };
    ...
    
  3. each(method)
    Array.prototype.each = function(method) {
      var args = Array.prototype.slice.call(arguments,1)
      for (var i = 0; i < this.length; i++) {
        this[i][method].apply(this[i],args)
    
  4. each(visitor)
    Array.prototype.each = function(visitor) {
      var iterator = this.getIterator();
      while (iterator.hasNext()) {
        var ret = visitor.call(this, iterator.next(), iterator.current);
        if (ret === false)
          break;
    
  5. eachIndex(iterationFunction)
    Array.prototype.eachIndex = function(iterationFunction) {
        for (var i = 0; i < this.length; i++) {
            iterationFunction(this[i], i);
    };
    
  6. eachWithIndex(f)
    Array.prototype.eachWithIndex = function(f) {
      for (var i = 0; i < this.length; ++i) {
        f(this[i], i);
      return this;
    
  7. each_with_index(callback)
    Array.prototype.each_with_index = function(callback) {
      for (var i=0; i < this.length; i++) { callback(this[i], i); } 
    
  8. each_with_index(f)
    Array.prototype.each_with_index = function (f) {
      for (var i=0; i<this.length; i++) {
        f(this[i], i)