Tag Archives: javascript

Running Jasmine Tests With PhantomJS

Jasmine + PhantomJSI finally got to mess around with PhantomJS and Jasmine, and couldn’t find a resource that gives clear, concise, accurate information, without language specific or build tool specific coupling, so I decided to write it myself.
Fortunately, it is way simpler than I thought.

PhantomJS

PhantomJS is a standalone, cross platform command line application which does not require any specific server environment or programming language support.

Continue reading

Build Backbone Apps Using RequireJS

TodosBackbone gives us a very powerful set of tools. It gives us models, views, and routes – all event driven, consistent and beautifully embrace underscore.js functionality. Being a library rather than a framework, Backbone doesn’t give us application structure. That “glue” we need too initialize the app and glue all the pieces together.
Since coding is by far easier than explaining, I programmed a Todos app in order to demonstrate how this can be done with Asynchronous Module Definition (AMD) using RequireJS.
Continue reading

Javascript RPN Calculator

RPN (Reverse Polish Notation) is a mathematical notation wherein every operator follows all of its operands, which was designed to reduce computer memory access and utilize the stack to evaluate expressions.

The syntax looks like:

rpn("3 3 +"); // => 3 + 3 => 6
rpn("2 2 + 3 *"); // => (2 + 2) * 3 => 12
rpn("2 2 3 + *"); // => (2 + 3) * 2 => 10 
rpn("2 2 3 3 / * /"); // => ((3 / 3) * 2) / 2 => 1;

A typical interview question would be to implement a RPN calculator since it is simple enough to resolve in less than an hour and it tests our ability to notice a problem that cries out for a stack based solution.
It also tests our absence from the “Introduction to Algorithms” course in college.

Obviously there are other algorithms to implement RPN, such as recursion, but using a stack will be more efficient: a stack will take O(n) times rather than O(n2) for recursion.

Of course, this has very little to do with UI programing, but we are dealing with interview questions.
Continue reading

PubSub / Observer Pattern and Coupling

PubSub (or the observer pattern) is obviously the hottest pattern in client side development, and I would like to take a shot at trying to refine the best practices for using it in a flexible and robust way.

The definition provided in the original Gang of Four book on Design Patterns states:

“Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically”

As in any design pattern, an important part is to keep the application loosely coupled and with high cohesion.
Continue reading

Backbone.js Poller

Lets say you have a Backbone.js based messaging system on your application, and you want to stay synced with the server so you could alert your users when a new message arrives. You would like to call the server once every couple of seconds and ask for status updates.
Or maybe your model represents an on going background task, you want to poll for status updates.
You could start with something basic such as:

function poll(collection, delay) {
  setInterval(function(){
    collection.fetch({data: {foo: 'bar'}});
  }, delay);
}

This works, but has some flaws:

  1. You may end up running simultaneous requests hitting the browser’s allowed connection per host limit (typically 6, 2 on IE7, according to browserscope)
  2. Nothing prevents you from running the function multiple time with the same collection
  3. You can’t easily stop the process, and abort running requests
  4. It doesn’t handle cases where we want to stop polling a model on a condition (say, when it’s task is done)

This may results in unnecessary load on the server side

You could run the next request only upon successful fetch request, and write something like this:

function poll(collection, delay) {
  collection.fetch({
    data: {foo: 'bar'},
    success: function(){
      setTimeout(function(){
        poll(collection, delay);
      }, delay)
    }
  });
}

This solves #1 bit doesn’t help other issues.
It takes a little more than that, and starts smelling like a special helper is needed.
You could add a poll() and unpoll() methods to your base models or collections using inheritance or mixin.
I wouldn’t like to promote such approach since it breaks the model’s interface and introduces tight coupling between the model and application state.
This easily becomes a slippery way down to maintenance hell.
A better pattern would be to use an external helper that will keep our interfaces clean and our models stateless and decoupled.

I ended up writing a Backbone Poller, A polling helper utility for Backbone.js.
a basic usage for our messaging system will could like

var inbox = new InboxCollection();
var poller = Backbone.Poller.get(inbox, {
    delay: 2000, 
    data: {sort: 'date desc'}
});
poller.on('success', function(){
    // do something on every successful fetch
});
poller.start();

A more advanced usage for our long going offline task could look like

var options = {
    delay: 2000,
    // when this becomes false the poller will stop
    condition: function(model){
        return model.get('done') !== true; 
    }
};

var task = new OfflineTaskModel();
var poller = Backbone.Poller.get(task, options);
poller.on('complete', function(){
    // task is done, do something
});
task.set('command', 'some-long-procedure');
task.save({},{
    success: function(){
        poller.start();
        
    }
});

The code and examples are available under the MIT license in github.

Javascript Design Patterns: Strategy

For a quick assignment I was asked to write the following program:

In the language of your choosing build an application that, given an English language document as input, builds a data structure capturing the count of each word in the document.

Bonus:
Create an inverted index as well: a mapping of the words to absolute positions in the document.

As context, this is a foundational algorithm for search systems and information retrieval. Be sure to consider accuracy, complexity, and intent in the design of your program.

The last phrase was the one that got me thinking.
This sounded a little vague, so I started thinking what kind of design I can implement that would be flexible enough so I can apply the algorithms later.
This kind of program usually runs on the back end using Java/Python/etc, but obviously, the language of my choice was javascript.

I started by defining a master processor:

var Processor = function(doc) {
    this.doc = doc;
};
Processor.prototype.parse = function(parser, sorter) {
    data = parser.parse(this.doc);
    if (sorter && typeof sorter.sort === 'function') {
        return sorter.sort(data);
    }
    else {
        return data;
    }
};

This processor gets a document (in our simple example, a long string) and has parse method, which accepts a “parser” object that has a parse() method and an optional “sorter” object that has a sort() method.
As the names suggest, the former will parse the document, and the latter will sort the results.
This use of the Strategy Design Pattern will allow the application to be flexible for algorithm changes, in the future.

First, I defined an abstract Parser object.
This object is responsible to convert the input to a standard format, and apply an algorithm

var Parser = function(){};
/**
 * The implementation will return an object literal 
 * with the format {word: num, word: num ...}
 * 
 * @param str {String}
 * @returns {Object}
 */
Parser.prototype.parse = function(str){
    throw 'please extned abstract object';
};

/**
 * Convert an object literal into a sortable array
 * with the format [[word, num], [word, num], ...]
 * 
 * @param data {Object}
 * @returns {Array}
 */
Parser.prototype.convert = function(data) {
    var arr = [],
        data = data || {};
    for(var key in data) {
        if(data.hasOwnProperty(key)) {
            arr.push([key, data[key]]);
        }
    }
    return arr;
};

My next step was defining the parsers I was requested to write:
One for capturing the count of each word in the document:


var CountParser = function(arr) {
this.arr = arr;
};
CountParser.prototype = new Parser; // extend the base parser
CountParser.prototype.parse = function(str) {
var value, i, l, data = {},
arr = str.split(/[\s]+/);
for(i=0, l=arr.length; i

Backbone.js URI Sync Adapter

I am working on a backbone based search page, and was trying to figure out what would be a simple way to have both a state model and a URI that represents that state of the page (the search string, search parameters, user preferences, etc.).

Thinking of mixing backbone routes and the application models seemed like an overkill, and would force me to handle everything through a route or an event.

After a short struggle, I realized that the best case would be to have a model that keeps me in model land, but has the representation in the URI, and came out with Backbone URI Storage.

The concept is very simple, and works like charm – use a standard backbone model, enjoy data binding, and simply hook the model in the URI.

var State = Backbone.Model.extend({
    sync: uriSync
});
var Search = Backbone.Model.extend({
    url: '/rest/v1/search/';
});

And now, I can update the application state when my search changes:

var state = new State({id: 'search-page'});
var search = new Search();
search.on('change', function(){
    state.save(search.toJSON());
});

A working code example can be found here.

Its as simple as that!