For each helper function

Post Reply
User avatar
gabrielp
Advanced member
Posts: 577
Joined: Fri Aug 08, 2014 4:31 pm
Location: Boston
Contact:

For each helper function

Post 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
Chat: open-automation @ gitter
Code: open-automation & dominickp @ GitHub
Tools: Switch, Pitstop, EPMS, Veracore, PageDNA, SmartStream, Metrix
User avatar
gabrielp
Advanced member
Posts: 577
Joined: Fri Aug 08, 2014 4:31 pm
Location: Boston
Contact:

Re: For each helper function

Post 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
Chat: open-automation @ gitter
Code: open-automation & dominickp @ GitHub
Tools: Switch, Pitstop, EPMS, Veracore, PageDNA, SmartStream, Metrix
User avatar
gabrielp
Advanced member
Posts: 577
Joined: Fri Aug 08, 2014 4:31 pm
Location: Boston
Contact:

Re: For each helper function

Post 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);
    }
}
Chat: open-automation @ gitter
Code: open-automation & dominickp @ GitHub
Tools: Switch, Pitstop, EPMS, Veracore, PageDNA, SmartStream, Metrix
Post Reply