Code: Impossible

Posts Tagged ‘Javascript’

W.O.M.M. #6 – enumerateOver()

Sunday, March 7th, 2010

works-on-my-machine-starburst

I’ve been focusing more and more on my port of Ling-to-Objects, Jsoq the past few weeks. It’s still in really early stages and I’m not quite sure about it’s actual usefulness but I’m learning a lot about JavaScript and having a ton of fun along the way!

Jsoq deals with arrays a lot. About 95% of it’s use cases involve either looping through, altering, or creating arrays. Having a ton of for loops in my code just seems so… not right. For loops have always seemed dirty to me. They just aren’t elegant enough.

Here is your normal, average, everyday for loop in Javascript.


var array = "1,2,3,4,5,6,7,8,9,10".split(',');

for(var i = -1, l = array.length; ++i < l;) {
    alert(array[i]);
}

This works. It’s reliable and gets the message across. But what if we needed to loop over an array and get all the items that matched a condition? Using a for loop the code could look something like:


var array = [ 1, 2, 3, 4, 5, 1, 2, 3, 4 ];
var results = [];
var condition = function(i) { return i%2 == 0; };

for(var itt = -1, len = array.length; ++itt < len;) {
	if( condition(array[itt]) ) {
		results.push(array[itt]);
	}
}

This does work, I’ve written code like this many times before, and while technically there isn’t anything wrong with it I think there is still room for improvement.

Jsoq is going to be handling arrays all over the place so the solution to this problem needs to be simple.

Here’s what I need:

  • to loop over an entire collection and perform an action on each item.
  • If that action produces a result, the item is to be pushed into an array and returned to after the loop is done
  • .

  • Also: it needs to be readable, someone else coming along should be able to determine what this thing is doing without too much difficulty. So I had my work cut out for me.

A few hours later I had a decent function that I could use to replace a lot of the for loops I had. After some more refactoring I was able to wipe them all out and replace them with calls to enumerateOver(). Here is the latest version from source control:


function enumerateOver(collection, work) {
	var result = [], val = [];

	if (isArray(collection)) {
		try {
			for (var i = -1, l = collection.length; ++i < l;) {
				result = work(collection[i], i);
				if (typeof result !== "undefined" && result != null) {
					val.push(result);
				}
			}
		}catch (e) {
			if (e != jsoq.$break) throw(e);
		}

		if (val.length > 0) {
			return val;
		}
	}else {
		try {
			val = work(collection, 0);
		}
		catch (e) {
			if (e != jsoq.$break) throw(e);
		}
		if (typeof val !== 'undefined') {
			return val;
		}
	}
	return result == null ? [] : result;
}

And here is the code to replace the for loops above, re-written to use enumerateOver()


var results2 = enumerateOver(array, function(i, c) {
     return i%2 == 0;
});

So by implmenting this function I was able to come up with a more readable, testable and streamlined codebase. Is this suitable for everyone? Definitely not, but I did it for a few reasons:

  1. Like I mentioned before. I’ve never been at ease with for loops and being able to replace them all with calls to a single function was a huge win for me
  2. The normal use-case didn’t fit right. I needed to not only iterate over arrays but also return the results of work performed on those items. Doing this the “regular” way just wouldn’t work (see previous reason)
  3. I thought this was a fun problem to solve

If you have any feedback, good, bad, or indifferent add a comment!

Using jQuery on an Iframe

Thursday, March 4th, 2010

The other day I had to alter the stylesheets in a child IFrame when a user selected an item from a drop-down. My first draft was pretty ugly, it ivolved getting the DOM from the child IFrame (by getting it’s contentWindow or contentDocument property) then getting the of the DOM and looping over all the child items… yuck!

I coded up this jQuery extension method which will return a jQuery-wrapped DOM instance for any of the matched IFrames.


(function($) {
    $.fn.extend({
        dom: function () {
            var $this = $(this);
            var getDom = function(o) {
                if( !o || (!o.contentWindow && !o.contentDocument) ) {
                    return null;
                }

                var doc = (o.contentWindow || o.contentDocument);

                return doc.document || doc;
            };

            var dom = getDom($this[0]);

            return dom === null ? $this : $(dom);
        }
    });
})(jQuery);

So with this, getting the styles for a child IFrame is as easy as:


$('iframe').dom().find('head link').each(function(index, item) {
    alert(item.href);
});

Unfortunately, this code will only work if your IFrame is hosting content that is on the same domain as its parent.

Solving “$(document).ready is not a function” and other problems

Wednesday, January 13th, 2010

Has this ever happened to you: you’ve been working on a customer’s site, writing some really awesome jQuery flashy, fadey, scrolly, interactivey thing, you deploy it, and everything is awesome. The customer rejoices and the customer’s customers rejoice. Rejoicing is had by everyone.

And then you get an email one day:

“Everything is broken. We’ve kidnapped your dog. Fix our site or you’ll never see Spartacus again.”

And before you have time to wonder why you ever named your dog “Spartacus” to begin with (i mean come. on.), you’re off in debug hell. You load the site and see all sorts of weird errors:

“$().ready is not a function”

“$(document) doesn’t support this property or method”

Or my personal favorite:

“null is null or not an object”

You open up FireFox, activate FireBug, load the console, and type “alert($)”, press run, and instead of seeing the expected jQuery function:


function (E, F) {
    return new (o.fn.init)(E, F);
}

You instead get:


function $(element) {
    if (arguments.length > 1) {
        for (var i = 0, elements = [], length = arguments.length; i < length; i++) {
            elements.push($(arguments[i]));
        }
        return elements;
    }
    if (Object.isString(element)) {
        element = document.getElementById(element);
    }
    return Element.extend(element);
}

Or even:


function $(id) {
    return document.getElementById(id);
}

DOH! Looks like another javascript library has been loaded and has overwritten the $() shortcut for jQuery. Woe is I. Why can’t we all just get along?!?

Well, we can’t stop people from including their favorite javascript libraries, but what we can do is prevent our code from suffering as a result. We’ll need a nice, big beefy, bodyguard to make sure our code isn’t messed with while it’s out clubbing with Prototype, Scriptaculous or even MooTools (who invited him??!?).

Here’s what our bodyguard function will look like


( function($) {

} ) ( jQuery );

So what this does is call our anonymous function and pass the jQuery object. This will scope ‘$’ to within our little function so we won’t step on anyone else’s toes (and they won’t bump into us while we’re on the dance floor and spill our drink everywhere). Okay, I think I've taken the clubbing metaphor far enough.

Basically this will allow our code to run and use the $ shortcut for JQuery as if it were loaded without any of these other libraries on the page.

Here is what the completed code would look like:


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript">
</script>

<script src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js" type="text/javascript">
</script>
<script src="http://ajax.googleapis.com/ajax/libs/scriptaculous/1.8.3/scriptaculous.js" type="text/javascript">
</script>

<script type="text/javascript">
( function($) {
    // we can now rely on $ within the safety of our “bodyguard” function
    $(document).ready( function() { alert("nyah nyah! I’m able to use '$'!!!!");  } );
} ) ( jQuery );

//this will fail
$(document).ready( function() { alert('fail?'); } );
</script>

I love using this simple self-calling anonymous function style when working with jQuery because it saves me from typing jQuery(), which really does look a lot more ugly than using the $() shortcut. It also protects my code from any scoping issues and lets the code function normally when jQuery is put into no conflict mode.

My opinion, if you're doing work in jQuery on sites that you don't control 100%, you should be using this method to protect your code and your clients.

Updated: changed link for jquery to use 1.4.1 at the google CDN (tsk, tsk, tsk I was using the googlecode.com link)

JavaScript Performance Re-match

Wednesday, December 2nd, 2009

Back in 2007 Jeff Atwood ran the top 4 web browsers through the SunSpider JavaScript Benchmark and posted his findings. It’s been close to 2 years since then and I was curious to see how FireFox 3.5, IE8, IE7 (in Compatibility Mode) and Google Chrome 4.0.249.11 would fair.

So I did pretty much the same thing Jeff did and here is what I found:

JavaScript Performance Graph

* System specs: Windows 7 64-bit on a Dual-Core 2.53ghz CPU with 4gb of RAM with no browser extensions

  1. Chrome kicks some serious butt over everyone else with the entire test suite running to completion in under 1 second!!
  2. FireFox 3.5 has some serious improvements coming in at just over 1.5 seconds total, which is about 1/10 the time it took FireFox 2.0
  3. Internet Explorer 8 and Internet Explorer 7 (compat mode) are still bringing up the rear but they had a better showing than the 20+ seconds IE7 took when Jeff ran the test

Surprises?
The only thing I found surprising about the results was that if you removed the string test from both IE runs then IE8 in compatibility mode beats IE8 running normally. That doesn’t seem right to me and I seriously hope JavaScript performance is something that gets addressed in IE9. And by “addressed” I mean “fixed by replacing Trident with WebKit”.

So, what do these results actually mean? Well I guess it depends. If you use your browser to read blogs and check your gmail then you shouldn’t really care about these numbers. However, if you’re a web developer you should be paying strong attention to these numbers and how far they’ve come in just 2 years.

W.O.M.M. Project Euler #3

Wednesday, November 25th, 2009

works-on-my-machine-starburst

Here we are with another excellent installment in the “Works On My Machine” series where I post some code, some thoughts and hopefully show you something interesting/cool/new.

Today I’m going to talk briefly about Project Euler problem #3. Problem 3 asks you to find the largest prime factor of the number 600,851,475,143.

My solution is pretty simple but it works:


var getLargestPrimeFactor = function(num)
{
    var factors = [];
    for ( var f = 2; f < num; f++ )
    {
        if( num%f == 0 )
        {
            factors.push(f);
            num = num /f;
        }
    }
    factors.push(num);
    return factors[factors.length-1];
};

alert( getLargestPrimeFactor(600851475143));

Try this code!

You may have noticed that there isn't a check for a factors optimus primeness anywhere in there.

Thats because the getLargestPrimeFactor() function is dividing the number by it's smallest factor, and the smallest factor for any number is always prime so when we run out of factors we've got the largest prime factor. Yeah, that's pretth cool IMO.

I read the discussion threads for problem 3 after I solved it and I was surprised that hardly anyone removed the prime checks from their code.

So, problem 3 is in the bag and I feel pretty good about coming up with the prime check optimization (or lack thereof). A small bit of proof that I know what I'm doing. Sometimes :D


Page optimized by WP Minify WordPress Plugin