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

2/22/2013

JSLint - javascript code-quality tool from terminal

If you wanna make art of your code, take a look at JSLint. It is a javascript code quality tool, created by Douglas Crockford - world famous js evangelist and author.

Here is a way how to download it with NPM ( node package manager ) and test your code:

In terminal type :
sudo npm install jslint -g

I suppose you know what is nodejs, and you that are using linux or mac.
If you are on windows take a look around, there is a guide somewhere, I am sure.
Next, create a js file, and put some code inside. I am sure that you'll be surprised with the result after testing.  Now move to that folder ( where the file is ) and type jslint name of file.js and learn from the results.

Update to post:

If you are using Vim with syntastic plugin, than JSLint which you installed globally ( with -g flag ) will check all your js script during coding in vim.

Happy Coding.

2/20/2013

What is a helper method ?

You probably heard about them, and use them but you didn't know that. Helper methods are usually  provided by the library. Underscore.js _.each function is widely used helper method throught many libraries.

Here's a nice definiton, from the classic perspective:

Helpers are one consequence of composed methods. If you are going to divide big methods into several smaller ones, you need those smaller methods. These are the helpers. Their purpose is to make larger-scale computations more readable by hiding temporarily irrelevant details and giving you a chance to express your intention through the name of the method. Helpers are typically declared private, moving to protected if the class is intended to be refined by subclassing.
 And example from Backbone.js library:

 
 
  function (attributes, options) {
    var defaults;
    var attrs = attributes || {};
    this.cid = _.uniqueId('c');
    this.attributes = {};
    if (options && options.collection) this.collection = options.collection;
    if (options && options.parse) attrs = this.parse(attrs, options) || {};
    if (defaults = _.result(this, 'defaults')) {
      attrs = _.defaults({}, attrs, defaults);
    }
    this.set(attrs, options);
    this.changed = {};
    this.initialize.apply(this, arguments);
  }
Above, you can see Backbone.Model method, which needs to be instantiated. Model is full of properties, but it is not ment to serve as constructor. For that purpose we use Backbone.Model.extend method, which simply helps establishing inheritance and providing bridge between Model and instance:
function (protoProps, staticProps) {
    var parent = this;
    var child;

    // The constructor function for the new subclass is either defined by you
    // (the "constructor" property in your `extend` definition), or defaulted
    // by us to simply call the parent's constructor.
    if (protoProps && _.has(protoProps, 'constructor')) {
      child = protoProps.constructor;
    } else {
      child = function(){ return parent.apply(this, arguments); };
    }

    // Add static properties to the constructor function, if supplied.
    _.extend(child, parent, staticProps);

    // Set the prototype chain to inherit from `parent`, without calling
    // `parent`'s constructor function.
    var Surrogate = function(){ this.constructor = child; };
    Surrogate.prototype = parent.prototype;
    child.prototype = new Surrogate;

    // Add prototype properties (instance properties) to the subclass,
    // if supplied.
    if (protoProps) _.extend(child.prototype, protoProps);

    // Set a convenience property in case the parent's prototype is needed
    // later.
    child.__super__ = parent.prototype;

    return child;
  }

It is possible to keep together Model and extend. It is not good design approach, cause we will sacrifice modular approach (among others pitfalls). Choosing to separate main method on two loose coupled parts, we are making extend methond reusable to other parts of our code. As you can see, Backbone authors did exactly that - you can extend Model,View,Router,History and Collection with one helper function.

Happy Coding

2/19/2013

Recursion demystified

Recursion is one of the main programming construct, that is very powerfull but sometimes it is not easy to understand.
I found one great example of recursive call:


// self invoking recursive function

(function foo(i) {
    if (i === 3) {
        return;
    }
    else {
        foo(++i);
    };
    console.log(i);
}(0));

Copy and paste it in chrome dev tools or in js interpreted environment. As  you can see it's not fibonacci, which is often used. This example is more straight-forward and simpler.

The output is 3,2,1.  It shows the way recursion works.
In short here is what is happening  - the inner function keeps calling outer function untill it reaches base case.
What is base case ? It is a number of calls which must be provided, usually expressed like a condition. If there is no base case, infinite loop will happen, which is not what we want. Since inner and outer function are same, we have a situation in which a function calls ifself. Foo inside will keep calling itself with provided arguments until it reaches base case.
And now important part: do you wonder why the output is inverted ? What don't we have 1,2,3 instead of 3,2,1 ?
That's because inner foo function is keeping results of calculation ( incrementing i ) somewhere in memory , but it can't provide output since it is called over and over again untill it reaches base case. That memory is called recursive stack, and it is a form of data structure, in which last data entrance is removed of called first. So when inner foo finally reaches base case, it is ready to "unwound" memory stack from the last to the first result giving 3,2,1 output.

Recursion is widely used in functional programming paradigm and it is considered for alternative to iteration. 

2/18/2013

Underscore js rocks

Hello World;

It's time for enlightnement.
Let me introduce you Underscore.js. It's a  small js library that provides lot of functional programming features, which is missing in native js implementations.

How to install it? Very simply - just copy file from this page
http://underscorejs.org/

or from git:
https://github.com/documentcloud/underscore

Put a file in you project folder, link to  it from the main page. In my case it looks like this:


// link to your underscore file



Now you should have new global js object named Backbone. Test it in chrome dev.tools:


// examine Backbone object

    dir(Backbone);

And finally lets see underscore in action (btw shorthand for library is_" ) with one example:

   Range function:


// assign the result to variable range

    var range = _.range(5,10,2)

// log in developer tools

    console.log(range);

         Output is [5,7,9]

Guess what is happening ?
Hint: pay attention to third paramater.

Underscorejs if full of utility functions that you can find in languages like Python of PHP. It is bringing more power and flexibility to Javascript and to your projects in general.
Also, it is a important part of jQuery and Backbone.
Feel free to experiment, it is fun with this great library.

Happy Coding.

2/16/2013

more vim tips & tricks

These days I'm digging deeper into wonderfull world of our favourite editor .
So here's what I discover:

Nerd commenter plugin

commands:
    - ,cc  comment a line of selected text
    - ,ca change comment style ( nerd will recognize language )
    - ,ci toggle comment
 
There is more ofcourse. Very helpfull plugin for production.
Here is a link for downloads.

http://www.vim.org/scripts/script.php?script_id=1218

Easy motion

basic commands:
    - ,,w mark a text so you can easily skip whereever you want
    - ,,k mark  backword

  http://www.vim.org/scripts/script.php?script_id=3526

Happy coding

12/13/2012

Public API -s reference on the web


Today I found awesome website:

http://www.programmableweb.com/


It's a directory, a news source, a reference guide and a community.
So if you are a web-developer ( front or back ) - it is a great resource for exploring.

Happy coding.

12/11/2012

What is thick ( fat ) client ?


This is one of the things that all front-end web developers should know:
fat client (also called heavyrich, or thick client) is a computer (client) in client–server architecture or networks that typically provides rich functionality independent of the central server. Originally known as just a "client" or "thick client" the name is contrasted to thin client, which describes a computer heavily dependent on a server's applications.
A fat client still requires at least periodic connection to a network or central server, but is often characterised by the ability to perform many functions without that connection. In contrast, a thin client generally does as little processing as possible and relies on accessing the server each time input data needs to be processed or validated.