Skip to content

Instantly share code, notes, and snippets.

@virtix
Created June 1, 2010 17:05
Show Gist options
  • Save virtix/421176 to your computer and use it in GitHub Desktop.
Save virtix/421176 to your computer and use it in GitHub Desktop.
<cfcomponent>
<cfscript>
//Hmmm .... how can we flatten without using state?
{buffer = [];}
function flatten(a){
var dup = [];
buf = [];
_flatten(a);
dup.addAll(buffer);
buffer = []; //make sure we reset state!
return dup;
}
private function _flatten(a){
var item = chr(0);
for(item in a){
if( isArray(item) ) _flatten( item );
else arrayAppend( buffer, item);
}
}
function concat(a,b){
var c = [];
var i = 1;
c = duplicate(a);
for(i in b){
arrayAppend( c, i );
}
return c;
}
function inc(a){
return map(a,_inc); //would be nice to have a lambda or closure here
}//
function _inc(val){
if( isNumeric(val) ) return ++val;
return val;
}//
// executes the given function on each element of the list and returns a new list
function map(a, func){
var item = chr(0);
var _a = [];
for(item in a){
if( isArray( item )) arrayAppend(_a, map(item, func) );
else arrayAppend( _a, func(item) );
}
return _a;
}//
// executes the given function on each element of the list
function foreach(a, func){
var item = chr(0);
for(item in a){
if( isArray( item )) map(item, func) ;
else func(item);
}
}//
</cfscript>
</cfcomponent>
<cfcomponent output="false" extends="mxunit.framework.TestCase">
<cfscript>
map = createObject("component", "Mapper");
private function print(m){
writeoutput(m);
}
function testForEach(){
var a = [1,2,3,4,5];
out = getPagecontext().getOut();
map.foreach( a, print );
}
function incrementEachNumericInAnArray(){
var a = [ 1,2,3,[4],[5,6,[7,8]],[11,[12],13,[14,[15,'0xAC3B',[16]]]], -1,'abc','xyz', {foo='bar'} ];
var b = map.inc(a);
debug(b);
}
function flatternAnArray(){
var a = [ 1,2,3,[4,5,6],[7,[8,9,[10]]] ];
var expected = [1,2,3,4,5,6,7,8,9,10];
var b = map.flatten(a);
debug(b);
assertEquals( expected,b );
}
function concatTest(){
var a = [ 'A','quick', 'brown','fox' ];
var b = [ 'jumps', 'over', 'the', 'lazy', 'dog' ];
c = map.concat(a,b);
debug(c);
}
</cfscript>
</cfcomponent>
@virtix
Copy link
Author

virtix commented Jun 1, 2010

map = createObject("component", "Mapper");

function incrementEachNumericInAnArray(){
var a = [ 1,2,3,[4],[5,6,[7,8]]];//,[11,[12],13,[14,[15,'0xAC3B',[16]]]], -1,'abc','xyz', {foo='bar'} ];
var b = map.inc(a);
debug(b);
}

function flatternAnArray(){
var a = [ 1,2,3,[4,5,6] ];
var b = map.flatten(a);
debug(b);
}

function concatTest(){
var a = [ 'A','quick', 'brown','fox' ];
var b = [ 'jumps', 'over', 'the', 'lazy', 'dog' ];
c = map.concat(a,b);
debug(c);
}

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