Saturday, November 21, 2009

No one should extend the Object.prototype in JavaScript!

In an earlier post, I wrote:


But everyone should keep in mind that extending the Object prototype in JavaScript is a big NO-NO


But why exactly should no one extend the Object.prototype?

What is the prototype?


Every object in JavaScript has a property (an object) called prototype (Introduced in JavaScript 1.1) that allows you to add custom properties and functions to every instance of that object.

Let's take an example.  First we'll add properties to objects without using the prototype:

var square = function () {  };

var box = new square();
box.height = 55;  //Adding a custom property to the box instance

In the above example, we created a new function called square and other one called box. The box is then initialized as an instance of square.
We then added a custom property to box called height and assigned a value to it.

If we now check the value of box.height, we get 55.

But if we now create another instance of a square, that new instance will not have the height property:

var anotherBox = new square();
alert(anotherBox.height) ; //alerts 'undefined' (not 0)

The reason undefined is displayed is because anotherBox does not have a property called height.

So the best thing to do is to add the height property to the square object, instead of the instantiated objects, via the prototype:

var square = function () {  };
square.prototype.height = 0;

//Now, every instance of square will have a height object

var box = new square();
box.height = 55;

var anotherBox = new square();
alert(anotherBox.height) //alerts 0

anotherBox.height alerts 0 because this time round, the anotherBox object has a property named height and it's set to 0.

I'll soon explain why it's a bad idea to extend the Object.prototype.


In JavaScript, every object inherits from an object called (not surprisingly) Object. Now, earlier on I described how when you attach a property to the prototype, it will exist in all instances of that object...so basically, since every object inherits from Object, when you extend the Object's prototype, every object from then on will have that property that was added to the Object.prototype.

Let's take an example:

Object.prototype.myCustomProperty = 200;

var square = function () {  };
alert(square.myCustomProperty); // 200 is alerted

As you can see from the above example, square now has a property called myCustomProperty!

But now you may think that this won't cause problems because you will only call the properties you know exist in the object you create; and well, that may be true but the real problem occurs when you use the for...in statement.

In JavaScript, there exists a construct that lets you iterate over all the properties of an object, the for...in statement:

Object.prototype.myCustomProperty = 200;

var box = { width: 200, height: 500 };

var props = "";
for (var p in box) {
    props += p + "\n";
}
alert(props);

In the above code I am iterating over every property of the box object and appending the name of that property to a string called props.

The output of the above alert is :



So you see, myCustomProperty now appears as part of the box object! And when you iterate over properties of an object, you will want the properties of only that object and not properties that are up the inheritance chain!

Fortunately enough, there is a workaround for this. This workaround involves using the hasOwnProperty function:

Object.prototype.myCustomProperty = 200;

var box = { width: 200, height: 500 };

var props = "";
for (var p in box) {
    if (box.hasOwnProperty(p)) {
        props += p + "\n";
    }
}
alert(props);

Now the alert displays:


This is because the hasOwnProperty returns true only if the property in the current iteration is directly linked to the object you are using in the loop; and thus, it returned false for the myCustomProperty property.

So make sure that when iterating over properties in JavaScript, you use the for...in construct! ...or else bad things may happen if someone (probably some JavaScript framework) extends the Object.prototype!

Friday, November 20, 2009

Arduino with a 3x4 Keypad

The following is something I made a while back with an Arduino, a speaker I ripped off from an old toy and two LEDs:



To make use of the keypad, I used Arduino's keypad library.

I connected the keypad to the Arduino as follows:

Keypad Pin
Arduino Pin
1
7
2
5
3
8
4
2
5
6
6
3
7
4

The above keypad numberings map as follows:




To use in your code, make sure you include it:

#include <Keypad.h>

You also need to map out the keys like such:

const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns

char keys[ROWS][COLS] = {
  {
    '1','2','3'    }
  ,
  {
    '4','5','6'    }
  ,
  {
    '7','8','9'    }
  ,
  {
    '*','0','#'    }
};

//The below numbers correspond to the Arduino Pins
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {8, 7, 6};    //connect to the column pinouts of the keypad

Afterwards, instantiate the Keypad:

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

Then to get the key pressed, it's just as simple as this:

char key = keypad.getKey();

Thursday, November 19, 2009

Stackoverflow's reverse-engineered WYSIWYM editor

If you want a lightweight, yet advanced (especially if you want it for a website for developers) online wysiwym editor, I suggest you take a look at Stackoverflow's reverse-engineered WMD Editor.

To download it, visit their development folder at github: http://github.com/derobins/wmd



Note that in the demo, I used the wmd along with a modified Stackoverflow css file.




Konami Code in JavaScript

Yesterday I came to know about this thing called a Konami Code and about how many websites use it as an easter egg!

So I decided to write up my own JavaScript version of this Konami Code.  You can download the normal, unpacked version for development or the packed version for production.

Click here to view a demo


To use the code, following these instructions:

1. Download the konami.js file from one of the above-mentioned links and add it to your page:

<script src="konami.js"></script>

This will create a konamiCode object in your website, which can be used in multiple ways. The konamiCode object takes 2 parameters: combination (an array of keyCodes) and a callback function.

The combination parameter can be skipped and if it is skipped, the default combination will be the Konami Code (UP, UP, DOWN, DOWN, LEFT, RIGHT, LEFT, RIGHT, B, A)

2. The simplest way to enable the Konami Code for your website, is like such:

konamiCode(function () {
    alert('You entered the code!');
}).start();

This will start the Konami code listener.

3. To stop listening for code input, store the konamiCode in a variable and call it's stop method:

var konami = konamiCode(function () {
                 alert('You entered the code!');
             }).start();

//...

konami.stop(); // <== stop listening

4. To use a different combination, enter an array as the first parameter of the konamiCode function:

konamiCode([38, 40, 37, 39, 52, 53], function () {
    alert('You entered the code!');
}).start();

The combination listed above is UP, DOWN, LEFT, RIGHT, 4, 2
As you can see, the elements of the array are the Key Codes of the keys, not the letters themselves. Use this website to convert from a key-press to a Key Code



Here is the unpacked code:

/*
 * Konami Code in Javascript
 * Andreas Grech
 * http://blog.dreasgrech.com
 *  v 1.1 (20091119)

 Keycodes for the Konami Code
 UP    : 38
 DOWN  : 40
 LEFT  : 37
 RIGHT : 39
 B     : 66
 A     : 65
*/

var konamiCode = function(combination, callback) {
 var lastCorrectInput = - 1,
 isActive = 0,
 o = {};
 if (typeof combination === "function") {
  callback = combination;
 }
 if (Object.prototype.toString.call(combination) !== "[object Array]") {
  combination = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65];
 }
 o.start = function() {
  if (isActive) {
   return;
  }
  isActive = 1;
  document.onkeyup = function(e) {
   var code;
   if (!isActive) {
    return;
   }
   code = window.event ? window.event.keyCode: e.which;
   if (combination[++lastCorrectInput] === code) {
    if (lastCorrectInput === combination.length - 1) {
     if (callback && typeof(callback) === "function") {
      callback();
     }
    }
    return;
   }
   lastCorrectInput = - 1;
  };
  return o;
 };
 o.stop = function() {
  isActive = 0;
  return o;
 };
 return o;
};

Testing if an element is an array, in Javascript

Up till now, I have always used this function (taken from Crockford's The Good Parts) to check for array validity in JavaScript:

var is_array = function (value) {
    return value &&
        typeof value === 'object' &&
        typeof value.length === 'number' &&
        typeof value.splice === 'function' &&
        !(value.propertyIsEnumerable('length'));
};

But recently I came to know that a guy from Google (Mark Miller) used the following condition (by carefully reading the ECMAScript Standard):

var is_array = function (value) {
    return Object.prototype.toString.call(value) === '[object Array]';
};

Although mind you, the above isn't perfect either, because it can easily be broken by extending the Object prototype :

// native prototype overloaded, some js libraries extends them
Object.prototype.toString= function(){
  return  '[object Array]';
}

function isArray ( obj ) {
  return Object.prototype.toString.call(obj) === '[object Array]';
}

var a = {};
alert(isArray(a)); // returns true, expecting false;

But everyone should keep in mind that extending the Object prototype in JavaScript is a big NO-NO . So, as of the moment, the most robust and concise way you can use to check for array validity in JavaScript is by using Miller's method.

Tuesday, November 17, 2009

Passing a pointer by reference in C

Today I needed a way to pass a pointer to an int to a function, modify the location of that pointer (via malloc) in that function, and then access the modified pointer from outside the function (from the caller).

I tried to code it like such (incorrectly):

int f(int *arr, int n) {
    int i;
    arr = malloc( n * sizeof (*arr));
    for (i = 0; i < n; ++i, ++arr) {
        *arr = i;
    }
    arr -= i;
    printf("Second element (from function) : %d\n", *(arr + 1));
    return 0;
}

int main()
{
    int *arr;
    f(arr, 5);
    printf("Second element (from caller) : %d", *(arr + 1));
    free(arr);
    return 0;
}
This is the output:

Second element (from function) : 1
Second element (from caller) : 1032044593

As you can see from the above output, the correct element is displayed when accessing the array from the function, but when I try to access the array from outside of the function (after it has been malloced and data was added), the value displayed seemed like a value from an unmalloced address!

What was I doing wrong?

The problem with the above code is that I am passing the pointer to an int by value to the function; ie a copy of the pointer.  That is why when I changed its address, the change was only visible from inside the function.

The Correct Way

The correct way to do it is to pass a pointer to the pointer to int (int **arr) to the function, like such:

int f(int **arr, int n) { //arr is now a pointer to a pointer to int
    int i;
    int *temp = malloc(n * sizeof **arr); //declare and malloc temporary space
    for (i = 0; i < n; ++i, ++temp) {
        *temp = i;
    }
    temp -= i;

    *arr = temp;  //Assign the value of the inputted location to the temporary one created earlier on

    printf("Second element (from function) : %d\n", *(temp + 1));
    return 0;
}

int main()
{
    int *arr;
    f(&arr, 5);  //The address of the pointer is now passed, not the pointer itself
    printf("Second element (from caller) : %d", *(arr + 1));
    free(arr);
    return;
}
Now the output from the above function is correct:

Second element (from function) : 1
Second element (from caller) : 1


Monday, November 16, 2009

Number of elements in an array in C

Take the following piece of code:
int main()
{
    int nums[] = {1,2,3,4,5};
    printf("Outside: %d\n",sizeof(nums) / sizeof(*nums));
    f(nums);
    return 0;
}

int f(int nums[]) {
    printf("Inside: %d\n",sizeof(nums) / sizeof(*nums));
}

Here is the output of the above code:
Outside: 5
Inside: 1
As you can see from the above output, when the calculation is done in the scope where the array was initialized, the correct output is displayed; but when it is passed to a function, the calculation fails!
This is because the formal argument int nums[]  does not contain any information about the array whereas the declaration of the array in the main function contains an implicit size  (determined by the number of items in the value), so as long as you use the variable in the main function (ie where it was declared), the compiler knows the size of the array.

When you send the array as a parameter to the f function, there is no information about the size sent along, it's just a pointer to an array of unknown size. The f function could be called from anywhere, so the compiler can't use the information about the variable in the main function.
If you want to know the size of the array in the f function, you have to send that along with the array as another parameter.