js

Queue & Cyclic Queue visualization with ProcessingJS

Previous posts:

Updates

I finished refactoring the code and loading all the scripts using requireJS.
RequireJS not only helped modularize the code but it also helped me find/fix a few bugs.

I knew about modular script loaders by working with nodeJS and commonJS
However, I had never used a script loader on the client side, and after playing with requireJS I can’t see myself not using anymore.
One of my last projects we didn’t anticipate the amount of client side code we would need to write, thus not planning and design a proper architecture. The code was mostly composed by event handlers and some logic needed to determine the flow of the app. It tried to mimic the functionality provided by BackboneJS and SpineJS
With that being said, once the app grew the event handling code started to get bloated and hard to maintain and some logic ended up being repeated across files.
RequireJS more than anything forces you to think in a modular way when creating web apps, and that helps maintain and also scale the app while it grows.

Here is an overview of the structure so far

The Element object is the tile that is used by the processing canvas to represent an element of a data structure
Since the Element can be reused between different data structures, it doesn’t contains any logic regarding how it should behave. It just knows where to position itself and to animate its entry and exit from the canvas.
That worked so far since all three data structures are some what similar. However, the idea is to have an abstract Element and derive separate elements for each data structure/algorithm. This would give more flexibility to each element once more examples are added.

Entry Point

RequireJS allows you to create an entry point for the application, where you can initialize any objects you need.

main.js

  
 require(  
 [  
 "./stack/stack",  
 "./queue/queue",  
 "./cyclic-queue/cyclic-queue",  
 ],  
 function () {

 // Init Stack  
 var Stack = require("./stack/stack");  
 var stack = new Stack();  
 stack.init();

 // Init Queue  
 var Queue = require("./queue/queue");  
 var queue = new Queue();  
 queue.init();

 // Init CyclicQueue  
 var CyclicQueue = require("./cyclic-queue/cyclic-queue");  
 var cyclicQueue = new CyclicQueue();  
 cyclicQueue.init();  
 });  

The first argument passed to require is a list of scripts to load before running the code.
The second argument is the code that will run once all the scripts specified in the first argument are loaded.

In the example above, the stack, queue and cyclic-queue scripts are loaded, then after their instantiation they are initialized.
All the logic of how they need to be initialized and how they will interact with the browser events are define within themselves, so to add a new data structure/algorithm the only thing that needs to be added to the main.js is the instantiation and initialization of the new object.
**An option for a future iteration is to create a factory to instantiate different objects, moving the responsibility of creating objects away from the main.js

Processing canvas

Since each example has its own canvas, a different instance of processing needs to be created.
However, not only the specific code for each example needs a reference to the processing canvas, but also the Element object, and right now all examples use the same Element.
Problem The Element object wasn’t referencing the right instance of processingJS

Solution:
Use requireJS to modularize the instantiation of the processingJS objects

So all the Elements will always reference the right canvas, and its code can be reused between the examples.
*A factory would probably be useful here to centralize the instantiation of the processing objects.

Some screen-shots:

You can find the code here and a live examples here

What’s Next?

There still a bunch of stuff to be done and improved.
The next iteration I plan to create a visualization for Hash Tables
I also want to refactor the code a little bit more and use factories to create processingJS canvas and to initialize the examples

References:

This and That - Understanding Javascript functions

Douglas Crockford mentions in his lectures OnJavascript, that javascript is so powerful that even without understanding the language it’s possible to program with it.
Now I understand what he means.
Javascript was the first language I was introduced to, not learnt, but introduced.
I’ve always used javascript to complement the development of web applications. Usually using frameworks, like jquery or mootols. But never by writing pure javascript code.

Even when I had to write some javascript code, was to use certain APIs, like googlemaps, or groupon for example.
Now that I actually need to write javascript code, I realized that I don’t know javascript as a language.

So what’s the solution? Read some books and write some code :)

This weekend I’ve been trying to understand the library html5PreLoader. The library pre-loads resources into the browser.
While reading the code, I end up looking at some parts and having no clue about what they were doing. Functions inside functions, functions inside objects, functions inside variables, and even functions inside functions.
Totally lost, I went to read about how functions work in javascript.

Here are a few examples of how functions can be used:

Functions used as methods:

A function can be a method in javascript. If the function is stored as a property in an object, it is considered to be a method.
When a method is invoked, this is bound to that object

 
 var myObject = {  
 value: o;  
 increment: function (inc) {  
 this.value += typeof inc === ‘number’ ? inc : 1;  
 };  
 myObject.increment();  
 document.writeln(myObject.value); // 1  
 myObject.increment(2);  
 document.writeln(myObject.value); // 3  

Inner functions:

If a method(function) of an object has a inner function, it is not possible to reference the object properties using the keyword this.
To access the properties of the object, the method must assign this to that. Then the inner function can refer to that as being the object itself.
To fix the problem the value of this is assigned to that

 
 function add(n1, n2)  
 {  
 return typeof (n1 === ‘number’ && typeof n2 === ‘number’) ? n1 + n2 : 0;  
 }  
 myObject.doubleNumber = function () {  
 var that = this;  
 var helper = function () {  
 that.value = add(that.value, that.value);  
 };  
 helper();  
 }  
 myObject.doubleNumber();  
 document.writeln(myObject.value);  

Another workaround for the problem is:

  
 if (!Function.prototype.bind) {

Function.prototype.bind = function (oThis) {

if (typeof this !== "function") // closest thing possible to the ECMAScript 5 internal IsCallable function  
 throw new TypeError("Function.prototype.bind – what is trying to be fBound is not callable");

var aArgs = Array.prototype.slice.call(arguments, 1),  
 fToBind = this,  
 fNOP = function () {},  
 fBound = function () {  
 return fToBind.apply(this instanceof fNOP ? this : oThis || window, aArgs.concat(Array.prototype.slice.call(arguments)));  
 };

fNOP.prototype = this.prototype;  
 fBound.prototype = new fNOP();

return fBound;  
 };  
 }

var x = 9;  
 var module = {  
 x: 81,  
 getX: function() { return this.x; }  
 };  
 document.writeln(getX()); // 81

var getX = module.getX;  
 document.writeln(getX() + ‘
’); // 9, because in this case, "this" refers to the global object // create a new function with ‘this’ bound to module var boundGetX = getX.bind(module); document.writeln(boundGetX()); // 81

What happen is when getX is invoked as a method, it has access to this(module object).
However when the method getX is copied to a variable, it loses the module scope, and this now refers to the global object.
So this.x in getX access the global variable x.
The fix is binding getX to the module object. So then this.x will access the module.x variable.

The only problem with this solution is that isn’t cross browser compatible.

Further readings and references:
Javascript the Good Parts
https://developer.mozilla.org/en/JavaScript/Reference/GlobalObjects/Function/bind
https://developer.mozilla.org/en/JavaScript/Reference/Global
Objects/Object
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function