/**
 * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Licensed under BSD (http://www.opensource.org/licenses/bsd-license.php)
 * Date: 1/6/2008
 * @author Ariel Flesler
 *
 * http://flesler.blogspot.com/2008/11/fast-trim-function-for-javascript.html
 */
 
// ------ Generate a string -------

var stringLen = 30,
	string = new Array(stringLen),
	wsPerSide = 0;
	
for( var i=0; i < stringLen; i++ ){
	 string[i] = (i < wsPerSide || i > stringLen - wsPerSide) ? 32 : Math.round(Math.random() * 57) + 65;
}
string = String.fromCharCode.apply( String, string ); // if done like a string, IE will go mad

// ------ Trimming functions -------

function myFirstTrim( str ){
	var	wspace = myFirstTrim.wspace,
		s = -1,
		e = str.length;
	while( wspace[str.charAt(--e)] );
	while( s++ !== e && wspace[str.charAt(s)] );
	return str.slice( s, e+1 );
};
(function(){	
	var chars = ' \n\r\t\v\f \u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u200B\u2028\u2029\u3000';
	myFirstTrim.wspace = {};
	for(var i = 0; i < chars.length;i++ )
		myFirstTrim.wspace[chars.charAt(i)] = true;
})();

// http://blog.stevenlevithan.com/archives/faster-trim-javascript
function trim1( str ){
	return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
};
function trim11 (str) {
	str = str.replace(/^\s+/, '');
	for (var i = str.length - 1; i >= 0; i--) {
		if (/\S/.test(str.charAt(i))) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
};
function trim12 (str) {
	var	str = str.replace(/^\s\s*/, ''),
		ws = /\s/,
		i = str.length;
	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
};
function jQueryTrim( str ){
	return str.replace( /^\s+|\s+$/g, '' );
};

function myBestTrim( str ){
	var	start = -1,
		end = str.length;
	while( str.charCodeAt(--end) < 33 );
	while( str.charCodeAt(++start) < 33 );
	return str.slice( start, end+1 );
};

function finalTrim( str ){
	if( !str )
		return '';
	
	var	modified = false,
		start = -1,
		end = str.length;
	while( str.charCodeAt(--end) < 33 ) modified = true;
	while( str.charCodeAt(++start) < 33 ) modified = true;
	return modified ? str.slice( start, end+1 ) : str;
};

// ------ Benchmark! -------

Benchmarker().compare({
	times: 10000,
	attempts:10,
	onEnd:function(){
		// garbage collector!!
		string = null;		
	}
}, {
	myFirstTrim:function(){
		myFirstTrim(string);
	},
	trim1:function(){
		trim1( string );
	},
	trim11:function(){
		trim11(string);
	},
	trim12:function(){
		trim12(string);
	},
	jQueryTrim:function(){
		jQueryTrim(string);
	},
	myBestTrim:function(){
		myBestTrim(string);
	},
	finalTrim:function(){
		finalTrim(string);
	}
});