Create function to iterate callback - Node.js Data Type

Node.js examples for Data Type:function

Description

Create function to iterate callback

Demo Code


function iterate ( n, callback )
{
  if ( typeof n !== 'number' )
    throw 'Error: iterate function called with not a number as first argument';

  if ( typeof callback !== 'function' )
    throw 'Error: iterate function called with not a function as second argument';

  for ( var i = 0; i < n; i += 1 )
  {/*from   w  w  w .j av a 2  s. c  om*/
    var ret = callback( i );
    if ( ret !== undefined )
      return ret;
  }
}

function iterateBack ( n, callback )
{
  return iterate( n, function ( i )
  {
    return callback( n - i - 1 );
  });
}

function iterateArray ( arr, callback )
{
  if ( typeof callback !== 'function' )
    throw 'Error: iterateArray function called with not a function as second argument';

  return iterate( arr.length, function ( i )
  {
    var ret = callback( arr[i], i );
    if ( ret !== undefined )
      return ret;
  });
}

function iterateArrayBack ( arr, callback )
{
  return iterateBack( arr.length, function ( index )
  {
    return callback( arr[ index ], index );
  });
}

Related Tutorials