20100513

A Pattern for Non-Local Returns in Javascript

A week or two ago, someone on reddit was complaining about javascripts lack of non-local returns and stating the language was poor as it couldn't be extended to include them.

So, for fun, I wrote a quick implementation of non-local returns in javascript. Probably inefficient as hell, but functional nontheless.

// javascript non-local return
<html><body><script language="javascript">

var WithNonLocalReturn = function( block ){
var ex_t = function(){
var hidden = null ;

this.set = function( retval ){
hidden = retval ;
};

this.get = function( retval ){
return hidden ;
};
};

var ex = new ex_t() ;

var valid = true ;

var leave = function( retval ){
if( valid ){
ex.set( retval ) ;
throw ex ;
} else {
throw ( ""
+ "It is invalid to call the non-local return"
+ "outside the stack of the creating WithNonLocalReturn"
) ;
}
};

try {
return block( leave ) ;
} catch( e ) {
if( e instanceof ex_t ){
return e.get() ;
} else {
throw e ;
}
} finally {
valid = false ;
}
};

var Each = function( iterable , fn ){
for( k in iterable ){
fn( iterable[ k ] ) ;
}
};

alert( WithNonLocalReturn( function( nonLocallyReturn ){
Each( [ 1, 2, 3, 4, 5, 6, 7, 8, 9] ,
function( i ){
alert( 'Testing : ' + i ) ;
if( i == 6 ){
nonLocallyReturn( 'Success : ' + i ) ;
}
});

return 'Failure' ;
}));

</script>


For fun they're nestable and since you name the value-returning function, you can easily and readably select what level nesting to return to. Or horrifically pass a non-local-return through as a sort of continuation down the stack of an otherwise rational bit of logic.

alert( WithNonLocalReturn( function( dontDoThis ){
return 'lolwut'.replace( /lol/g , dontDoThis ) ;
}));


One should probably avoid doing that.

About Me

(2) the subculture of the compulsive programmer, whose ethics prescribe that one silly idea and a month of frantic coding should suffice to make him a life-long millionaire. --ewd1036