Clarification:
As some people have pointed out, this does look like a "Is this code ok"-kind of question. The main thing I'm actually curious about is this: how does the .hasOwnProperty
method work?
I mean: IE's JScript engine (<9 at least) doesn't always use hash-tables, so I assume it does little more than iterate over all properties of that object, and then checks to see if it gets those properties from another object higher up the prototype-chain. Is this a fair assumption to make? After all: at some level every code gets translated into loops and branches, but if IE doesn't do hash-tables, doesn't that mean .hasOwnProperty
is just some sugar, just there so you don't have to write the loop?
I think I got this notion from one of DC's blog-posts or video's and it could well be that he was talking about arrays, and the quirky things they are (or rather: can be) in JS. I can't find the video/blog-post(?) ATM. And seeing as JS Arrays are often abused, as many of you I think will agree, I thought the answers to this question could serve as a decent reference. That's why I didn't post it on codereview.
As far as current answers go, and since my question started of from the wrong angle (focussing on the code more than the mechanisms behind it), let me just be so corny as to thank you all for pointing out the issues I didn't think of.
Recently, I augmented the array prototype for a script I was working on (don't shoot, just yet). In order not to reinvent the wheel, I went and searched for some examples of how other people went about it.
Strangly This is quite common, which is plainly needlessly complex. I also found this, as an alternative, other than the poster being rather smug about his fast algorithm I still feel there is room for improvement.
I know I might come across as a smug wise-guy now, my unique
method actually looks like this:
Array.prototype.unique = function()
{
'use strict';
var i,obj,ret;
ret = [];
obj = {};
for (i=0;i<this.length;i++)
{
if (!obj.hasOwnProperty(this[i]))
{
ret.push(this[i]);
obj[this[i]] = i;
}
}
return ret;
};
This way, there just is no need for a second loop AFAIK, is there? Unless, of course, the hasOwnProperty
method is dead slow, but somehow I doubt that, in this case: the chain can only go back 1 level, to the Object.prototype
.
The second link I posted contains some statistics and speed-comparisons, but as we all know they mean next to nothing in the real world. Could anyone point me in the direction of good article on JS and benchmarking (apart from the one on John Resig's blog?
So, just out of curiosity: Does any one of you see a problem with this method? some more info: Object.prototype: unchanged, undefined
is undefined
, no globals no frameworks, and this method isn't blindly implemented (if (!Array.prototype.unique){...}
)