Create a gist now

Instantly share code, notes, and snippets.

AS3 Implementation of `curry` function to pre-capture target function arguments left-to-right. Only when are the arguments have been captured does the target function get invoked with the accumulated argument values.
package utils.function
{
public function curry(func:Function, ... args:Array):*
{
var arity:int = func.length;
var currying:Function = function(func:Function, arity:int, args:Array):*
{
return function(... moreArgs:Array):* {
if(moreArgs.length + args.length < arity)
{
return currying(func, arity, args.concat(moreArgs));
}
return func.apply(this, args.concat(moreArgs));
}
}
return currying(func, arity, args);
}
}
@ThomasBurleson
Owner

Here is a sample usage of curry():

import utils.function.curry;

/**
 * Search and filter list of cars based on searchTerm criteria
 */
public function filterByCriteria( allCars:Array, searchTerm:String ) : ListCollectionView
{
        function hasSearchTerm( searchTerm:String, targetToSearch:String ) : Boolean 
        {
          return targetToSearch.toLowerCase().indexOf( searchTerm ) > -1;
        }

      searchTerm = searchTerm ? searchTerm.toLowerCase() : "";

          /**
           * Use the static method `curry` to build a special `curried` function 
           * of the `hasSearchTerm` function; where the `searchTerm` argument is pre-captured. 
           */
      var foundIn     : Function = curry( hasSearchTerm, searchTerm );

      var collection  : ListCollectionView =  new ArrayCollection( allCars );
      var carFilter   : Function = function (car:CarVO ) : Boolean 
          {
              if ( car.hidden )                   return false;
              if ( searchTerm == "")              return true;

              if ( foundIn( car.title ))          return true;
              if ( foundIn( car.owner.name ))     return true;
              if ( foundIn( car.decscription ))   return true;

              return false;
          };


      collection.filterFunction = carFilter;
      collection.refresh();

      return collection;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment