The amount of times I thought test was a prototype of String instead of RegExp and written:
Code:
alert("hi there how are you".test(/hi/))
I can't even nearly count...
Code:
<script type="text/javascript">
String.prototype.test=function(reg){if("test" in reg)return reg.test(this);return null;}
alert("hi there how are you".test(/hi/))
alert(/hi/.test("hi there how are you"))
alert("hi there how are you".test(/bye/))
alert(/bye/.test("hi there how are you"))
</script>
Array.prototype.shuffle=function(){
var r, t, i=this.length;
while (i>1)
r = Math.random()*i-- >> 0,
t = this[i],
this[i]=this[r],
this[r]=t;
return this;
}
Very nice one BigMoosie! Never thought of using the bitwise operator before in place of Math.floor nor using commas instead of semicolons to concentrate the while-loop body into a single statement to avoid curley brackets. Very nice code indeed!
The built in sort() function treats Number object as strings making "12" appear before "2".
This sort below is a selection sort that overcomes this problem for numbers however strings will still exhibit this annoying property.
The first line (this.sort()) is in place as it increases the speed by roughly a factor of 10, however it will still work without it and should probably be removed if you know your array will already be mostly sorted.
Code:
Array.prototype.sort2 = function(){
this.sort();
var store;
for (var i=1; i<this.length; i++) {
store=this[i];
for (j=i; j>0 && this[j-1]>store; j--) this[j]=this[j-1];
this[j]=store;
}
return this;
}
An Array Prototype to convert an array of 'words'
to a dimensioned array where each field is an array
with field 0 holding the original word
and field 1
the number of occurrences of characters in a string
passed to the prototype.
Code:
<script language="JavaScript" type="text/javascript">
/*<![CDATA[*/
// Nearest Word (03-June-2006)
// by Vic Phillips http://www.vicsjavascripts.org.uk/
// An Array Prototype to convert an array of 'words'
// to a dimensioned array where each field is an array
// with the word as field 0
// and field 1 the number of occurrences of characters in a string
// passed to the prototype.
// Application Notes
//
// Best explained in the form of an example
//
// ** The 'Word' arrays
//
var Ary1=['word','Tom','qwerty','qwertyqwerty'];
var Ary2=['joe','Tomy','quick brown fox','Vic Phillips'];
//
//
// ** The String' Input
//
// <input onkeyup="f68Nearest(this,Ary1);" /> ['word','Tom','qwerty','qwertyqwerty']
// <input onkeyup="f68Nearest(this,Ary2);" /> ['joe','Tomy','quick brown fox','Vic Phillips']
//
// ** Example Function using the Prototype
//
function f68Nearest(f68obj,f68ary){
var f68result=f68ary.nearest(f68obj.value);
var f68txt=[];
for (var f680=0;f680<f68result.length;f680++){
f68txt.push(f68result[f680]);
}
document.getElementById('Result').value='Result:\n'+f68txt.join('\n');
}
//
//
// ** The Array Prototype 'nearest'
// **** Functional Code - NO NEED to Change
//
Array.prototype.nearest=function(f68val){
var f68val=f68val.toLowerCase();
var f68split=f68val.toLowerCase().split('');
var f68ckary=[];
for (var f680=0;f680<f68split.length;f680++){
for (var f681=0;f681<this.length;f681++){
if (!f68ckary[f681]){ f68ckary[f681]=[]; }
var f68aval=this[f681].toLowerCase().split('');
for (var f682=0;f682<f68aval.length;f682++){
if (f68aval[f682]==f68split[f680]){
f68ckary[f681].push(f68split[f680]);
}
}
}
}
for (var f683=0;f683<this.length;f683++){
f68ckary[f683]=[this[f683],f68ckary[f683].length];
}
return f68ckary;
}
//
// **** General
//
// All variable, function etc. names are prefixed with 'f68' to minimise conflicts with other JavaScripts
// These character are easily changed to characters of choice using global find and replace.
//
// The Functional Code(607 bytes) is best as an External JavaScript
//
// Tested with IE6 and Mozilla FireFox
//
/*]]>*/
</script>
// All variable, function etc. names are prefixed with 'f68' to minimise conflicts with other JavaScripts
Variables declared either as a parameter or with the keyword "var" are local to that function and cannot conflict with other variables. Try accessing your variables from outside your function and you will notice it is impossible making it pointless to obscure the variable names.
In the occasional surcumstance that a persistant variable is required and has to be declared outisde of your function you can wrap both the function and the variable in an anonymous function like this:
The New Line character varies on the operating system: \n: Unix and Unix-like systems, Linux, AIX, Xenix, Mac OS X, BeOS, Amiga, RISC OS and others \r\n: CP/M, MP/M, DOS, Microsoft Windows \r: Apple II family and Mac OS through version 9
The best way I've found to serve up a new line in all the operating systems is initializing a textarea with a newline then grabbing its value.
An example using String.prototype.replaceNewLinesWith:
Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html dir="ltr" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta http-equiv="content-script-type" content="text/javascript">
<title>New Lines</title>
<script type="text/javascript">
String.prototype.replaceNewLinesWith=function(str){
var NL=getNewLine();if(!NL)return false;
var re=false;
if(NL == "\r\n")re=/\r\n/g;
else if(NL == "\r")re=/\r/g;
else if(NL == "\n")re=/\n/g;
if(!re)return false;
return this.replace(re,str);
}
function getNewLine(){
if(!document.getElementById)return false;
var NL=document.getElementById('newlinechar');
if(!NL)return false;
if(NL)NL=NL.value.split('a')[1];
return NL;
}
</script>
<script type="text/javascript">
function replaceChars(){
if(!document.getElementById){alert("Your browser is too old for this script to work properly!");return false;}
var e=document.getElementById("nNL");if(!e){alert("Could not find any elements with the ID \"nNL\"!");return false;}
var ta=document.getElementById("ta");if(!ta){alert("Could not find any elements with the ID \"ta\"!");return false;}
ta.value=ta.value.replaceNewLinesWith(e.value);
}
</script>
</head>
<body>
<div>
<textarea cols="1" rows="1" style="display:none;" id="newlinechar">a
a</textarea>
<textarea cols="50" rows="5" id="ta">Line One
Line Two
Line Three</textarea><br>
Replace New lines with: <input type="text" value=" " size="2" id="nNL"><br>
<input type="button" value="Replace" onclick="replaceChars()">
</div>
</body>
</html>
If you have a javascript intense thread that you wish to execute on user events such as mouse move then sometimes it can make your code non-responsive as it may execute perhaps 50 times when the mouse is moved only a short distance, this here will solve the problem, just call myFunct.wait(params) and it will be alot more resource saving.
Code:
(function(){
var list=[];
Function.prototype.wait = function(){
var i=list.length;
while (i-->0) if (list[i][0]==this) return;
i=arguments;
list[list.length]=[this,setTimeout(function(){
list.shift()[0].apply(window,i);
},1)];
}
})();
String.prototype.toStudlyCaps=function(){
var val=this; var results=this.match(/\b(\w+)\b/g); var expr="";
for(i=0;i<results.length;i++){
expr=eval("/\\b"+results[i]+"\\b/");
val=val.replace(expr,results[i].substr(0,1).toUpperCase()+results[i].substr(1,results[i].length).toLowerCase());
}
return val;
}
alert("hi how Are you?".toStudlyCaps()); // alerts "Hi How Are You?"
Bookmarks