jsBenchmarker

Source of "useful_functions"

Back
/**
 * @text This test only declares functions, view source.
 */
 
function sequence(){
	var args = [].slice.call(arguments),
		l = args.length;
	return function(){
		for( var i = 0, ret; i < l; ++i )
			ret = args[i].apply(this,arguments);
		return ret;
	};
};

function range( from, to, step ){
	if( to == undefined ){
		to = from;
		from = 0;
	}
	
	if( !step )
		step = from > to ? -1 : 1;
	
	var arr = [], 
		asc = step > 0;
	
	for( var i = -1; from < to == asc && from != to; from += step )
		arr[++i] = from;
			
	return arr;
};

function matrix( rows, cols, map ){
	var obj = [ ], _cols = cols, row,
		domap = typeof map == 'function';
		
	while( rows-- ){
		row = obj[rows] = new Array(_cols);
		if( map == undefined )
			continue;
		cols = _cols;
		while( cols-- )
			row[cols] = domap ? map( rows, cols ) : map;
	}
	return obj;
};

function format( str, params ){
	return str.replace( /\{([^{}]+)\}/g, function( all, ns ){
		var p = params;
		ns = ns.split('.');		
		do p = p[ns.shift()];
		while( p && ns.length );
		return p === undefined ? all : p;											  
	});
};

function each( obj, fn, scope ){
	var i, l;
	if( 'length' in obj )
		for( i = 0, l = obj.length; i < l && fn.call( scope, obj[i], i ) !== false; ++i );
	else
		for( i in obj && fn.call( scope, obj[i], i ) !== false );
};

function map( obj, fn, scope, ret ){
	if( !ret )
		ret = 'length' in obj ? [ ] : { };
	var arr = 'length' in ret;
	
	each( obj, function( v, k ){
		ret[ arr ? ret.length : k ] = fn.call( scope, v, k );
	});
	return ret;
};
function filter( obj, fn, scope ){
	var arr = 'length' in obj,
		ret = arr ? [ ] : { };
		
	each( obj, function( v, k ){
		if( fn.call(scope, v, k) )
			ret[ arr ? ret.length : k ] = v;
	});
	return ret;
};

function reduce( obj, ret, fn, scope ){
	if( typeof fn != 'function' ){
		scope = fn;
		fn = ret;
		ret = undefined;
	}
	each( obj, function( v, k ){
		ret = ret === undefined ? v : fn.call(scope,ret,v,k);
	});	
	return ret;
};