www.webdeveloper.com
Page 12 of 15 FirstFirst ... 21011121314 ... LastLast
Results 166 to 180 of 221

Thread: Here are 2 prototype-functions I created.

  1. #166
    Join Date
    Nov 2002
    Location
    England
    Posts
    693
    yes its the same function... I've modified the code because you can't decrypt when the code has been converted to hex. Usage is included in the file: enc.txt;

    //encrypt using single DES (with an 8 byte key) in CBC mode with the given input vector
    string.DES ("8bytekey", 1, 1, "inputvec");
    //encrypt using triple DES (with a 24 byte key) in ECB mode
    string.DES ("this is a 24 byte key !!", 1);
    //decrypt using single DES in ECB mode
    string.DES ("8bytekey", 0);
    Attached Files Attached Files

  2. #167
    Join Date
    Feb 2005
    Location
    USA
    Posts
    1,534
    Number.prototype.toBytes()

    Takes a number and returns as a file size the number of byes or kilobytes etc. (up to terabytes):

    Code:
    Number.prototype.toBytes=function(){
    	for (var n=this*(this<0?-1:1), p=0; n>=1024 && p<4; ++p) n/=1024;
    	return (this<0?"-":"")+(n=Math.floor(n))+" "+["","kilo","mega","giga","tera"][p]+"byte"+(n!=1?"s":"");
    };
    Last edited by BigMoosie; 08-20-2005 at 08:17 AM.

  3. #168
    Join Date
    Nov 2002
    Location
    England
    Posts
    693

    String interpolation, perl style

    var name="Carl";
    var number = 2;
    var colour = new Array("red","lime","orange");

    String.prototype.interpolate = function interpolate (){
    var s = 0;var returnstring = "";var tempstring = this;var num = 0;
    for(var i=0; i<this.split("$").length; i++){
    returnstring += tempstring.substring(num, tempstring.indexOf("$"));tempstring = tempstring.substring(tempstring.indexOf("$")+1, tempstring.length);var theVar = tempstring.substring(0, tempstring.indexOf(" "));
    if(num == 0){
    num = 1;
    }
    if(theVar.indexOf("[$")>-1){
    var aindexVar = theVar.substring(theVar.indexOf("[$")+2, theVar.indexOf("]"));
    if(eval("window."+aindexVar)){
    theVar = theVar.substring(0, theVar.indexOf("[")) + "[" + eval(aindexVar) + "]";
    }else{
    s = 1;
    }}
    tempstring = tempstring.substring(tempstring.indexOf(" "), tempstring.length);
    if(theVar.substring(0,1) == "_"){
    returnstring += "$" + theVar.substring(1, theVar.length)
    }else if(s == 1){
    s = 0;
    returnstring += "undefined";
    }else if(theVar == ""){
    }else if(eval("window."+theVar)){
    returnstring+=eval(theVar);
    }else{
    returnstring+="undefined";
    }
    }
    return returnstring + tempstring;
    }

    alert("Hello my name is $name and my favourite colour is $colour[$number] . I bought a bicycle today, it cost $_250 ".interpolate());

    instead of alert("Hello my name is " + name + " and my favourite colour is " + colour[number] + ". I bought a bicycle today, it cost $250");

    Variables must start with a "$" and finish with a " " (space). To add a dollar sign to the string use $_ (Warning: the $_ is treated as a variable and must end with a space " ").

    The code is a bit sloppy as it's all off of the top of my head. It may be a bit buggy as I haven't tested it fully. Anyone is free to rewrite it and make improvements.

    Regards

    Carl
    Last edited by Scriptage; 08-22-2005 at 04:49 AM.

  4. #169
    Join Date
    Nov 2002
    Location
    England
    Posts
    693

    Variable interpolation: v2

    <script>
    String.prototype.S = function(){

    var returnString = "";
    var variables = this.split("{");
    returnString += variables[0];
    for(var i=1; i<variables.length; i++){
    if(variables[i].indexOf("}") == -1){
    returnString += "{" + variables[i];
    }else{

    var myVar = variables[i].substring(0, variables[i].indexOf("}"));
    var endString = variables[i].substring(myVar.length+1, variables[i].length);

    if(myVar.indexOf(" ")>-1){
    returnString += "{" + variables[i];
    }else{

    if(myVar.indexOf("[")>-1){

    var mySub = myVar.substring(myVar.indexOf("[")+1, myVar.indexOf("]"));

    if(mySub.indexOf("'") == -1 && mySub.indexOf('"') == -1 && !parseInt(mySub) && mySub != 0){

    if(eval("window." + mySub)){
    returnString += eval(myVar) + endString;
    }else{
    returnString += "{" + variables[i];
    }

    }else{
    if(eval(myVar)){
    returnString += eval(myVar) + endString;
    }else{
    returnString += "{" + variables[i];
    }
    }

    }else if(eval("window." + myVar)){
    returnString+= eval(myVar) + endString;
    }else{
    returnString += "{" + variables[i];
    }

    }
    }
    }
    return returnString;
    }
    var name = new Array();
    name[0] = "Ben";
    name[1] = "Carl";
    name[2] = "Brady";
    name['one'] = "John";
    var number = 2;
    alert("display an array element by its number: {name[0]}, display an array element by a string: {number['one']}, display a variable {number}, don't worry about using {brackets} because if it isn't a variable it isn't processed".S())
    alert("Use windows variables in a string: {screen.height}")
    </script>

    A much more useful version of the interpolation prototype. This is quite useful... don't you agree?

    Enjoy

    Carl
    Last edited by Scriptage; 08-24-2005 at 09:20 AM.

  5. #170
    Join Date
    Feb 2005
    Location
    USA
    Posts
    1,534
    Looks like it could be quite useful to somebody who has become accustom to that method of coding, though for me regular variable concatenation is second nature so I probably won't find much use.

    Instead of using:

    eval("window." + mySub)

    you should use:

    window[mySub]


    It will prove much more efficient. I am yet to see a case where eval() is actually better than the alternative.

  6. #171
    Join Date
    Jan 2005
    Location
    Los Angeles, CA
    Posts
    4,887
    Date.prototype.setMe is a function that accepts 3 arguments and sets the Date Object directly (i.e. it sets it like setTime() w/o returning the date object but actually setting it directly) it accepts the day,Month,Year and sets the Date Object for you in 1-2-3.

    Code:
    <script type="text/javascript">
    
    Date.prototype.setMe=function(d,m,y){
    
    if(arguments.length<3)return this.getTime();
    if(isNaN(d)||isNaN(m)||isNaN(y))return this.getTime();
    d=Number(d);m=Number(m);y=Number(y);
    var meDate=new Date(0);
    meDate.setDate(d);meDate.setMonth(m);meDate.setFullYear(y);meDate.setHours(0);
    this.setTime(meDate.getTime());return this.getTime();
    
    }
    
    </script>
    
    <script type="text/javascript">
    
    var now=new Date();
    now.setMe(7,23,1984)
    alert(now.toLocaleString())
    
    </script>
    Last edited by Ultimater; 08-26-2005 at 02:36 PM.

  7. #172
    Join Date
    Jan 2005
    Location
    Los Angeles, CA
    Posts
    4,887
    Date.prototype.UTCsetMe Let's you set it's Day,Month, and Year for UTC and it uses a zero for it's hours,minutes,seconds,milliseconds.

    GMT(Greenwich Mean Time) and UTC(Universal Time Coordinated) are usually thought of as interchangable. The difference is that UTC is atomic time while GMT is an actual timezone.
    Code:
    <script type="text/javascript">
    
    Date.prototype.UTCsetMe=function(d,m,y){
    
    if(arguments.length<3)return this.getTime();
    if(isNaN(d)||isNaN(m)||isNaN(y))return this.getTime();
    d=Number(d);m=Number(m);y=Number(y);
    var meDate=new Date(0);
    meDate.setUTCDate(d);
    meDate.setUTCMonth(m);
    meDate.setUTCFullYear(y);
    
    this.setTime(meDate.getTime());return this.getTime();
    
    }
    
    </script>
    
    <script type="text/javascript">
    
    var now=new Date();
    now.UTCsetMe(7,23,1984)
    alert(now.toUTCString())
    
    </script>

  8. #173
    Join Date
    Jan 2005
    Location
    Los Angeles, CA
    Posts
    4,887
    Array.prototype.getAddedKeys is a function that loops though all of the elements of an array, regardless their keys, and generates a new array with all of the elements side-by-side along with their keys. It's quite hard to explain yet a very powerful function.
    Code:
    <script type="text/JavaScript"><!--
    Array.prototype.getAddedKeys=function(){var a=this,kArray=[],vArray=[],i,l,nArray=[];for(i in a){if(i in Array.prototype)continue;kArray[kArray.length]=i;vArray[vArray.length]=a[i]}l=kArray.length;for(i=0;i<l;i++){nArray[nArray.length]=kArray[i];nArray[nArray.length]=vArray[i];}return nArray}
    
    var b=["zero","one","two","three"];
    b[5]="five"
    b["number9"]=9
    
    alert(b.getAddedKeys())
    
    //--></script>

  9. #174
    Join Date
    Jan 2005
    Location
    Los Angeles, CA
    Posts
    4,887
    Array.prototype.addImg is a function that makes the syntax to preload mutiple images, easier.
    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-Style-Type" content="text/css">-->
    <meta http-equiv="Content-Script-Type" content="text/javascript">
    <title>Ultimater's Array.prototype.addImg example</title>
    <script type="text/javascript"><!--
    Array.prototype.addImg=function(s){var tmp=new Image();tmp.src=s;this[this.length]=tmp;}
    //--></script>
    <script type="text/javascript"><!--
      var ia=new Array();
          ia.addImg("http://www.webdeveloper.com/forum/image.php?u=30740&amp;dateline=1115558351"); 
          ia.addImg("http://www.webdeveloper.com/forum/image.php?u=30185&amp;dateline=1128637189"); 
    alert(ia[0].src);
    alert(ia[1].src);
    //--></script>
    </head>
    <body>
    <p></p>
    </body>
    </html>
    Last edited by Ultimater; 10-11-2005 at 03:10 AM.

  10. #175
    Join Date
    Jan 2005
    Location
    Los Angeles, CA
    Posts
    4,887
    Array.prototype.keyAndValueSort is a function built for sorting keys and values. Every other array element is a key followed by the next array element -- it's value. The syntax is as follows:
    Code:
    [key,value,key,value,key,value]
    The function first makes sure that there are an even amount of array elements, otherwise the function is smart-enough to assign a blank string to the last key.
    The function preforms the regular sort method on the array's keys and rememeber's the value for each key which is what makes this function useful in the first place.
    This function is also smart enough to know that there can only be one unique key of any given name. If you have more than on key with the same name, the function will ignore the key and value of the first and use the key and value of the last instead.

    When the function is finished, it returns an array in the same syntax as goes into the function:
    Code:
    [key,value,key,value,key,value]
    Happy coding!
    Code:
    <script type="text/javascript">
    Array.prototype.keyAndValueSort=function(){
    var l=this.length;
    var bl=l;if(bl%2==1)bl--;
    
    var keys=new Array();
    var values=new Array();
    
    for(var i=0;i<l;i+=2){
    keys[keys.length]=this[i]
    if(i==bl){values[values.length]="";break}
    values[values.length]=this[i+1]
    }
    
    l=keys.length
    var nObj={};
    for(i=0;i<l;i++){
    nObj[keys[i]]=values[i];
    }
    
    var nKeys=new Array();
    for(i in nObj){
    nKeys[nKeys.length]=i
    }
    nKeys.sort();
    l=nKeys.length;
    
    var nValues=new Array();
    for(i=0;i<l;i++){
    nValues[nValues.length]=nObj[nKeys[i]]
    }
    
    var outArray=new Array();
    for(i=0;i<l;i++){
    outArray[outArray.length]=nKeys[i]
    outArray[outArray.length]=nValues[i]
    }
    return outArray;
    }
    </script>
    <script type="text/javascript">
    //simple key and value sorting example:
    var a=["a",1,"b",2,"d",4,"c",3];
    alert(a.keyAndValueSort())
    
    //the key "key1" appears twice in the array and the function will ignore the first key and value
    var j=["key1","overridedvalue","key2","there","key1","hi","key3","!"];
    alert(j.keyAndValueSort())
    
    </script>
    Last edited by Ultimater; 11-21-2005 at 02:18 AM.

  11. #176
    Join Date
    Jan 2005
    Location
    Los Angeles, CA
    Posts
    4,887

    String.prototype.indexesOf

    I have used the built-in indexOf method much too long and saw reason to build a better method. There should be a way for indexOf to return an array containing ALL the indexOf-instaces of the search string rather than just the index of the first instance. Regular Expressions come with a "g" modifier flag, why can't indexOf also come with one?

    String.prototype.indexesOf will go through the entire string collecting all instances into an array. If no matches are found, it returns a blank array (not a -1). For each match it finds, it's indexOf is added to the array.



    Code:
    <script type="text/javascript">
    String.prototype.indexesOf=function(){
    if(arguments.length==0||String(arguments[0]).length==0){return new Array()};
    var s=String(arguments[0]),outArray=new Array(),l=this.length,beginat=0,t;
    while(beginat<=this.length){
    t=this.indexOf(s,beginat);if(t==-1)break;outArray[outArray.length]=t;beginat=t+1
    }
    return outArray;
    }
    </script>
    
    <script type="text/javascript">
    var testString="abcdefg abcdefg a";
    alert( testString.indexesOf("a") );  //[0,8,16]
    alert( testString.indexesOf("abcdefg") );  //[0,8]
    </script>

  12. #177
    Join Date
    Feb 2005
    Location
    USA
    Posts
    1,534
    I have a problem I cannot solve, consider this:

    Code:
    (function(){
    	var a = window.alert;
    	window.alert=function(q){
    		a("BigMoosie\n\n"+q);	
    	}
    })();
    This code will add the word 'BigMoosie' to every single alert called. This is quite neat as the workaround has been enclosed within an empty function making the variable 'a' inaccessible to global functions.

    I wish to do a similar thing to a prototype function for example this will make the split function's first argument defualt to an empty string if it is not set:

    Code:
    String.prototype.split2 = String.prototype.split;
    String.prototype.split = function(s, a){
    	return this.split2(s || "", a);
    }
    However this is not as neat because the split2 function is global and can be accessed by other codes still, how would I make it private like in the previous example?

  13. #178
    Join Date
    Jan 2005
    Location
    Los Angeles, CA
    Posts
    4,887
    Mean something like this?
    Code:
    <script type="text/javascript">
    
    (function(){
    
    var j=String.prototype.split
    String.prototype.split=function(){
    return j.apply(this,["||"])
    }
    
    })();
    
    alert(("a||b").split())
    </script>

  14. #179
    Join Date
    Jan 2005
    Location
    Los Angeles, CA
    Posts
    4,887
    I have a great idea for a RegExp prototype function: (unfinished)
    Code:
    <script type="text/javascript">
    RegExp.prototype.getRandomMatch=function(){
    var rearray=this.toString().split('/');
    var re=rearray[1];var flags=rearray[2]
    alert("RegExp:\n"+re+"\n\nFlags:\n"+flags);
    }
    var reg=/\d\w[a-zA-Z]/ig;
    reg.getRandomMatch()
    </script>
    Just imagine creating a really complex RegExp that you barely even finish writting,
    Code:
    /(<td\b)((?:(?! </?td ) . )*?)( \r?\n? )(?=(?: <td\b ) |(?: </\s*tr\b ) )/i
    and calling the getRandomMatch function to have it return an example random string that would match the criteria.

    With all the positive and negitive search-aheads, I don't even know where to start writting this function...
    Last edited by Ultimater; 01-15-2006 at 05:34 PM.

  15. #180
    Join Date
    Dec 2002
    Location
    Manchester, UK
    Posts
    6,276
    Here's a nice randomly useless one, semi-inspired by Cinders.
    Code:
    String.prototype.makeStupid = function(stupidityLimit){
    
      var stupid		= new Array();
      var stupidness	= "";
    
      /*
    
    	Add in your stupidisms here, the later they are declared, the less likely they
    	are to occur.
    
      */
    
      stupid[stupid.length]	= "!";
      stupid[stupid.length]	= "1";
      stupid[stupid.length]	= "eleven";
      stupid[stupid.length]	= "twelve";
      stupid[stupid.length]	= "SHIFT+1";
    
      /*
    
    	The higher the value of the "stupidityRareness" variable, the less often the
    	later values in the array occur.
    
      */
    
      var stupidityRareness	= 20;
    
      for( var n=0; n < stupidityLimit; n++){
        stupidness		+= stupid[Math.floor(stupid.length * Math.pow(Math.random(),stupidityRareness))];
      }
    
      return this+stupidness;
    
    }
    
    alert("PWNZ0R8T3D!".makeStupid(50));
    Last edited by David Harrison; 02-16-2006 at 12:21 AM.
    Every fight is a food fight when you’re a cannibal.

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