Page 1 of 1

For each helper function

Posted: Fri Jul 08, 2016 10:12 pm
by gabrielp
If you're like me and hate for loops, this makes iterating a little simpler within Scripter:

Code: Select all

/*
   Foreach helper function
	  callback
		Function to execute for each element, taking three arguments:
		currentValue
			The current element being processed in the array.
		index
			The index of the current element being processed in the array.
		array
			The array that forEach() is being applied to.
*/
var forEach = function(array, callback){
	var currentValue, index;
	for (i = 0; i < array.length; i += 1) {
		currentValue = array[i];
		index = i;
		callback(currentValue, i, array);
    }
}
Example usage:

Code: Select all

	var toAddresses = s.getPropertyValueList('ToAddresses'); // String list property with multiple lines
	
	forEach(toAddresses, function(address, index){
		s.log(2, "address "+index+": "+address);
	});
Output

Re: For each helper function

Posted: Wed Jul 13, 2016 9:47 pm
by gabrielp
This now supports constructed arrays that are empty.

Code: Select all

var forEach = function(array, callback){
	var currentValue, index;
	for (i = 0; i < array.length; i += 1) {
		if(typeof array[i] == "undefined"){
			currentValue = null;
		} else {	
			currentValue = array[i];
		}
		index = i;
		callback(currentValue, i, array);
    }
}
For example:

Code: Select all

var array = new Array(10); // forEach would loop this 10 times

Re: For each helper function

Posted: Wed Sep 07, 2016 7:58 pm
by gabrielp
This version resets the i index variable every time. This was causing confusing behavior within nested forEach loops.

Code: Select all

// For each helper function
var forEach = function(array, callback){
   var currentValue, index;
   var i = 0;
   for (i; i < array.length; i += 1) {
      if(typeof array[i] == "undefined"){
         currentValue = null;
      } else {   
         currentValue = array[i];
      }
      index = i;
      callback(currentValue, i, array);
    }
}