www.webdeveloper.com
Page 13 of 15 FirstFirst ... 31112131415 LastLast
Results 181 to 195 of 221

Thread: Here are 2 prototype-functions I created.

  1. #181
    Join Date
    Jan 2005
    Location
    Los Angeles, CA
    Posts
    4,887

    String.prototype.test

    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>

  2. #182
    Join Date
    Feb 2005
    Location
    USA
    Posts
    1,534
    A Better Shuffle

    Code:
    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;
    }

  3. #183
    Join Date
    Jan 2005
    Location
    Los Angeles, CA
    Posts
    4,887
    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!

  4. #184
    Join Date
    Feb 2005
    Location
    USA
    Posts
    1,534
    Numerical Sort

    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;
    }
    Last edited by BigMoosie; 06-06-2006 at 02:38 AM.

  5. #185
    Join Date
    Jun 2004
    Location
    Portsmouth UK
    Posts
    2,674
    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>
    Vic

    God loves you and will never love you less.

    http://www.vicsjavascripts.org/Home.htm
    If my post has been useful please donate to http://www.operationsmile.org.uk/

  6. #186
    Join Date
    May 2006
    Posts
    11
    cool prototype functions.. a rea time saver

  7. #187
    Join Date
    Jul 2004
    Location
    web develepment land
    Posts
    164

    Talking

    Window.location.search.get(getVarName)
    This is used to find a HTTP_GET_VAR using javascript
    Code:
    String.prototype.get = function() {t=unescape(this);key=arguments[0];a=t.lastIndexOf(key+"=")+(key.length+1);if(a.length-(key.length+1)==-1) {return -1}b=t.substr(a);c=b.indexOf("&");if(c<0) {return b}else {d=b.substring(0,c);return d}}
    example (Used on file :test.html?test=It%20works!)
    Code:
    alert(window.location.search.get("test"))
    If the HTTP_GET_VAR doesn't exist it will return -1
    Need help with any of my scripts? Come chat with me!
    Javascript And File System!
    EMBLEM
    |-____/\____---------------|
    |-\__/||\__/--TRUST--------|
    |--\/|--|\/----THE---------|
    |--/______\-----EMBLEM-----|
    |-----\/-------------------|

  8. #188
    Join Date
    Feb 2005
    Location
    USA
    Posts
    1,534
    Quote Originally Posted by vwphillips
    // 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:

    Code:
    (function(){
     
    // all code here
    
    })();

  9. #189
    Join Date
    Jun 2004
    Location
    Portsmouth UK
    Posts
    2,674
    You may modify the script to your requirements but the credits must remain intact.

    In this instance the uniqueness is relavent to function names in the example

    (this is a standard feature of scripts I produce)
    Vic

    God loves you and will never love you less.

    http://www.vicsjavascripts.org/Home.htm
    If my post has been useful please donate to http://www.operationsmile.org.uk/

  10. #190
    Join Date
    Jan 2005
    Location
    Los Angeles, CA
    Posts
    4,887

    String.prototype.replaceNewLinesWith

    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="&nbsp;" size="2" id="nNL"><br>
    <input type="button" value="Replace" onclick="replaceChars()">
    </div>
    </body>
    </html>

  11. #191
    Join Date
    Feb 2005
    Location
    USA
    Posts
    1,534
    Function wait

    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)];
    		}
    	})();
    Last edited by BigMoosie; 06-06-2006 at 02:32 AM.

  12. #192
    Join Date
    Jan 2005
    Location
    Los Angeles, CA
    Posts
    4,887
    resource saving*

    I like your list variable declaration -- very neat trick!

    Useful function, it is -- if you could get it to work in IE.
    Still good for Firefox:
    Code:
    onmousemove="alert.wait(event.pageX+','+event.pageY)"
    Last edited by Ultimater; 06-05-2006 at 12:58 PM.

  13. #193
    Join Date
    Jul 2005
    Location
    USA
    Posts
    912

    toStudlyCaps()

    Add this to the prototypes list:

    Code:
    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?"
    Last edited by Webnerd; 06-05-2006 at 01:42 PM.
    Bitter web veteran

  14. #194
    Join Date
    Jan 2005
    Location
    Los Angeles, CA
    Posts
    4,887
    @Webnerd str is undefined. Change "str" to "expr".
    Might also want to leave a note for people and yourself so you remember what it does.
    Code:
    alert("hi how Are you?".toStudlyCaps())// alerts "Hi How Are You?"

  15. #195
    Join Date
    Jul 2005
    Location
    USA
    Posts
    912
    All fixed up.toStudlyCaps();
    Bitter web veteran

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles