Skip to content

Instantly share code, notes, and snippets.

@edulan
Created May 13, 2010 00:12
Show Gist options
  • Save edulan/399303 to your computer and use it in GitHub Desktop.
Save edulan/399303 to your computer and use it in GitHub Desktop.
/**
* AS3 implementation of Ruby Enumeration class
*/
public dynamic class Enumerable
{
private var _array:Array;
public function Enumerable(... parameters) {
if(parameters != null)
_array = parameters;
else
_array = new Array();
}
/**
* f(item:*):Boolean;
*/
public function detect(f:Function):Object {
var first:Object;
var detected:Boolean;
detected = _array.some(function(item:Object, i:int, a:Array):Boolean {
first = item;
return f(item);
});
return (detected ? first : null);
}
/**
* f(item:*):Boolean;
*/
public function select(f:Function):Object {
return _array.filter(function(item:Object, index:int, array:Array):Boolean {
return f(item);
});
}
/**
* f(item:*):Object;
*/
public function map(f:Function):Array {
var array:Array = new Array();
_array.forEach(function(item:Object, i:int, a:Array):void {
array.push(f(item));
});
return array;
}
/**
* f(memo:Object, item:*):Object;
*/
public function reduce(initial:Object ,f:Function):Object {
var memo:Object = initial;
_array.forEach(function(item:Object, i:int, a:Array):void {
memo = f.call(null, memo, item);
});
return memo;
}
}
@edulan
Copy link
Author

edulan commented May 13, 2010

Some examples:

var array:Enumerable = new Enumerable(1, 2, 3);

array.detect(function(n:Number):Boolean { return n == 2; }); // 2
array.select(function(n:Number):Boolean { return n > 1; }); // 2,3
array.map(function(n:Number):Number { return n % 2; }); // 1,0,1
array.reduce(0, function(a:Number, n:Number):Number { return a + n; }); // 6

@edulan
Copy link
Author

edulan commented May 13, 2010

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