Wednesday, 25 May 2011

Remembering how to do geometry; JavaScript 'namespaces'

To make the lines representing relationships in Dubbiya, I needed to find where a line intersects a rectangle. I was pretty sure I once knew how to do this. But the knowledge was lurking in an inaccessible part of my mind. So I needed to do some relearning.

I enjoy these parts of projects like Dubbiya. It is many times more enjoyable than the forms-and-reports programming than most of us software developers have to do in their professional life.

Along the way, I learnt that you can't have two functions in JavaScript with the same name, even if the number of arguments differ.

function doSomething(x) {

clashes with

function doSomething(x, y) {

A good IDE alerts you to this before it bites you:

Screen shot 2011 05 25 at 11 20 33 AM






I also learnt a relatively nice way to emulate namespaces in JavaScript. At the top of each JavaScript file I can have something like this:

if (typeof dubbiya === 'undefined') {
dubbiya = {};
if (typeof dubbiya.geometry === 'undefined') {
    dubbiya.geometry = {};

Then each function definition is added as such:

dubbiya.geometry.intersectionPointLineLine = function (line1, line2) {

Now I can call the function as follows:

var pt1 = dubbiya.geometry.intersectionPointLineLine(line1, line2);

It's a bit silly that one needs to artificially create namespaces. Luckily a good IDE makes this style of code readable:

Screen shot 2011 05 25 at 11 18 06 AM

1 comment:

  1. I actually structure my js includes by including a namespaces.js file that defines all the namespaces. Then I don't need to worry about it being defined already.

    There are tools to compile and collate js files so I just use those if it is ever necessary (it hasn't been, yet.)