Skip to main content

Array magic in JavaScript

I was trying to create a queue to collect all the element related functions to run after the elements had been created. As I was Googling, I came by this snippet.
var calls = [];

function executeNext(next) {
    if(calls.length == 0) return;
    var fnc = calls.pop();
    fnc();
    if(next) {
        executeNext(true);
    }
}

/*To call method chain synchronously*/
calls.push(callMe3);
calls.push(callMe2);
calls.push(callMe1);
executeNext(true);

/*To call method chain asynchronously*/
calls.push(callMe3);
calls.push(function(){
    callMe2();
    executeNext(false);
});
calls.push(function(){
    callMe1();
    executeNext(false);
});
An array was a perfect fit with the built in push() and pop() function. I also needed something that would work the pop() till the array was empty. As Douglas Crockford says in his wonderful book 'JavaScript: the good parts', arrays are actually (slightly disguised) objects. So one can simple add to the native methods that the array variable already has simply by declaring it and then use it. This would be truly elegant and very readable.
The Html Code used
<p id="demo1">
<br>Click the button to call the new ucase() method, and display the result.</p>
<br><button onclick="myFunction()">Try it</button>
And the JavaScript used
var fruits = ["Banana1", "Orange1", "Apple1", "Mango1"]
fruits.myUcase=function()
{
for (i=0;i<this.length;i++)
  {
  this[i]=this[i].toUpperCase();
  }
}

function myFunction()
{
fruits.myUcase();
var x=document.getElementById("demo1");
x.innerHTML=fruits;
}
Demo 1:
Click the button to call the new ucase() method, and display the result.

When one declares a new array, one simply inherits a prototype- this is called prototypal inheritence. JavaScript gives us the power to change this prototype itself. Since the array is actually an object, one can simply add methods directly to the array prototype. From w3school's reference page
<p id="demo2">
Click the button to create an array, call the new lcase() method, 
<br>and display the result.</p>
<button onclick="myFunction2()">Try it</button>
And the javascript
Array.prototype.myLcase=function()
{
for (i=0;i<this.length;i++)
  {
  this[i]=this[i].toLowerCase();
  }
}

function myFunction2()
{
var fruits2 = ["BANANA2", "OrAnGe2", "APpLE2", "mANgO2"];
fruits2.myLcase();
var x=document.getElementById("demo2");
x.innerHTML=fruits2;
}
Demo 2:
Click the button to create an array, call the new lcase() method,
and display the result.

As mentioned before, since the prototype for Arrays has been changed to add a new method myLcase() to change all the elements in the array to lower-case, it should be able to use this method myLcase() in the previously declared array fruits (used in the demo1.).
function myFunction3()
{
fruits.myLcase();
var x=document.getElementById("demo");
x.innerHTML=fruits;
}
The HTML is the same as in the first Demo.
Demo 3:
Click the button to call the new lcase() method on the fruits variable
and display the result.

This means that the methods added to the Array prototype would be usable even in the case of previously declared array variables. So the way of declaration affects the scope of the method. The term Scope itself is worthy of another blog post.

Since my specific need was to create a array to which one functions would be added which would empty it one by one and use them individually as an argument to the function given as an argument to the method added to the already declared array variable. To put it more simply, f is a function given as an argument to the added method popall. While actually using this method, the argument given is alert, which means the actual function happening when f(this.pop()) is alert(this.pop()) .
      stack = []
      stack.popall=function(f){
        if(this.length == 0) return this;
        while(this.length != 0) f(this.pop());
        return this;
      };

      stack.push('ah');
      stack.push('ah1');
      stack.push('ah2');
      stack.push('ah3');
And the html-
<button onclick=alert(stack.pop())>pop</button>
<button onclick=stack.push('ah'+stack.length.toString())>push</button>
<button onclick=stack.popall(alert)>empty</button>
<button onclick=stack.popall(alert).push('empty!')>empty n push</button>
Demo:

Comments

Post a Comment

Popular posts from this blog

The first half of 2017 in review

Hi people, Half the year is over and i think its good to list out things, so that i have an idea as to how i am doing with my studies ( and pretty much everything else ). It's been a wonderful and fulfilling half year, to be honest. I did a lot of things I always wanted to do.  I started experimenting with hydroponics - haven't really progressed much, but I am sure I will do something substantial in the other half of the year. Benefits are a lot over traditional way, and the joy of watching your plants grow are invaluable, at the least. I read a few books on history. I have always wanted to do this , but I always had an excuse or 2 to avoid it. I finally started, and it's brought me a sense of childlike wonder, something I sorely missed. I cleaned my home! That's 20 years of procrastination right there! It was insane but I got it done. Whew! And wow!  At the beginning of the year, i finished my re-study of the CS subjects. Post February, i opened th...

Year 2016 in review and goals for 2017

Hello people, It's my 34th birthday today and I wanted to put the past year in review and where I wanted my life to go in the next year. Achievements of this year: Machine learning course by Andrew Ng ( completed ) Calculus I by Robert Ghrist ( completed ) Calculus II by Robert Ghrist ( completed ) Probability and Statistics ( 2 weeks left ) Data science - pandas ( 1 week done )  My first linear regression program Built a neural network from scratch  My first Regex. From scratch. No references. With tests. Algorithms I by Robert Sedgwick ( only audit ) Algorithms II by Robert Sedgwick ( only audit ) Also did the BE subjects for CS, all the stuff I had learned over the years. I am super happy to know that MOOCS help a lot in career advancement . Self-help books that really helped: How to win friends and influence people - Dale Carnegie   A mind for Numbers - Barbara Oakley   Altogether, a pretty good year, where le...

When you say........

......you don't believe in god, you admit there is a god to believe in This is the meme post that started this train of thought in my mind.   I have heard one of my classmates say a long time ago, if women truly believed that they were equal to men, then they would not fight for it. While I never accepted it, i didn't know how to speak against it either. but it was there, somewhere in my mind. I think i made some sense out of it, at last. This is stupidity. This is like saying 'If we Indians seriously believed that freedom was ours, we would never have had to fight for it'. The fight for independance was a fight to make the other party understand and/or accept your viewpoint. The first resonable method might be to consider the other person's viewpoint. And using that as a base point,then work, with suitable proof and arguments, raise, alter, or reconstruct their viewpoint to match ours. This method follows the logic that people can and will be fair in an...