Pair program with me! profile for carousel at Stack Overflow, Q&A for professional and enthusiast programmers

8/02/2013

Classic design patterns in coffeescript

Today I am going to start a series of posts, in which I want to implement classic OO design patterns with the help of coffeescript.  In case you don't know what is coffeescript and what are the benefits of using it, I highly recommend visiting official coffee site: http://coffeescript.org/, and looking for some tutorials online.

So, to start let's define what is design pattern ?

Wiki article says:
In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design
They were introduced to the OO world by the work of GoF ( gang of four ) group, and their famous book:
 http://www.amazon.com/Design-Patterns-Elements-Object-Oriented-ebook/dp/B000SEIBB8

Patterns in this book are discussed from the point of  classic OO languages ( with strong type system, class-based inheritance ...)
Javascript doesn't support these features, but provide some more flexibile and modern paradigms for solving  problems.
It includes prototype based inheritance, no classes, dynamic type system, no block scope, functions as first class. Writing design patterns with Javascript can be challenging. JS is very flexibile, since same things can be done "in more than one way".

First patterns, that I am going to introduce is  Iterator
  
Implementation in coffeescript:
//
# Behavioral 
# Iterator design pattern with Coffeescript
# Object is explicitly exported in global namespace ( for testing with console.log in the
# browser )
arr = ["begin","middle","end"]

i = 0 
len = arr.length

this.obj = 
    prev:()->
        if arr[i] is "begin"
            obj.end()
            return arr[i]
        arr[--i]

    current:()->
        arr[i]

    next:()->
        if arr[i] is "end"
            obj.begin()
            return arr[i]
        arr[++i]

    begin:()->
        i=0

    end:()->
        i=arr.length-1

//


After compiling in native Javascript:

//
// Generated by CoffeeScript 1.6.2
(function() {
  var arr, i, len;

  arr = ["begin", "middle", "end"];

  i = 0;

  len = arr.length;

  this.obj = {
    prev: function() {
      if (arr[i] === "begin") {
        obj.end();
        return arr[i];
      }
      return arr[--i];
    },
    current: function() {
      return arr[i];
    },
    next: function() {
      if (arr[i] === "end") {
        obj.begin();
        return arr[i];
      }
      return arr[++i];
    },
    begin: function() {
      return i = 0;
    },
    end: function() {
      return i = arr.length - 1;
    }
  };

}).call(this);
//

All code can be foud on my GitHub page
Happy Coding

No comments:

Post a Comment