The three C’s of Javascript

week5gsoc1

You might be wondering what the three C’s are :

  • Currying
  • Closures
  • Callbacks

Ok what are those ?

Before i start, let me tell you that in Javascript Functions are Objects. So every object in Javascript, be it Number, String, Array; Every Object in javascript has a prototype object. For instance if the object is declared using an object literal then it has access to Object.prototype, Similarly all the arrays so declared have access to the Array.prototype. So since functions are objects, they can be used like any other value. They can be stored in variables, objects, and arrays. They can also be passed as arguments to functions, and donot forget that functions can be returned from functions.
Currying :

In Javascript if one wants to partially evaluate functions then one can take advantage of a concept called function currying. Currying allows us to produce a new function by combining a function and an argument. For example let us consider writing an add function, :

function add(foo, bar) {
if(arguments.length === 1) {
return function (boo) {
return foo + boo;
}
}
return foo + bar;
}
So for the above code,
add(12, 13); // gives 25
add(12)(13); // gives 25

The curry method works by creating a closure that holds that original function and the arguments to curry. It returns a function that, when invoked, returns the result of calling that original function, passing it all of the arguments from the invocation of curry and the current invocation
Closures :

Simply put, a closure is an inner function that has access to the outer (enclosing) function’s variables scope chain. Except the parameters and variables that which are defined using this and arguments all, the inner functions have access to all the parameters and variables of the function in which those are defined.

var a = 0;
function counter() {
var i = 2;
return i*i;
}
function counter1() {
return a+= 1;
}

// this wont work as part of Js closures
function counter_foo() {
var a = 0;
a += 1;
}

// this also wont work as part of Js closures
function counter_bar() {
var c = 0;
function go() { c+= 1;}
go();
return counter;
}
// this will work as part of Js closures
var counter_closure = (function () {
var incr;
return function() {return incr+= 1;}
})();

show(counter1());
show(counter1());
show(counter1()); // since we are added the counter three times the value of a is set to 3.
show(counter_foo());
show(counter_foo());
show(counter_foo()); // this is similar to the above but doesnot set the value of a to 3, but returns undefined.
show(counter_bar());
show(counter_bar());
show(counter_bar()); // Neither this works which will always set the value to 1
show(counter_closure());
show(counter_closure());
show(counter_closure()); // Now this is called closures implementation in Js

Function Closures in Javascript is all about how are the variables being treated and referred to in the local or global scope. In Js variables can be given : 'local scope' 'global scope' There is no inbuilt concept for something called private variables, so when there is a requirement for such a scenario Closures are written in Js in order to make scope for variables that are private in scope. Observing the functions ‘counter1()’, ‘counter_foo()’ and ‘counter_bar()’ there is a similarity that can be observed, Basically we can understand that closures are nothing but self invoking functions in Js. Observe the example ‘counter_closure()’ where in we are calling the function thrice and hoping to increment the functional value each time when we call the function. So this self invoking function runs only once but it increments the value each time it is called. The scope of the variable is protected by the anonymous return function making us assume that this can be called implementation of private variables in Js.
Callbacks :

A callback function is a function that is passed to another function as a parameter and giving the provision for the function to “call us back” later. Since the callback function is just a normal function when it is executed, we can pass parameters to it. We can pass any of the containing function’s properties (or global properties) as parameters to the callback function. Let us look at an example :

function manipulate(foo, bar) {
console.log("Do you know that " + foo + " is better than " + bar);
}
function useIt(boo, callback) {
var t1 = boo.slice(1,5);
var t2 = boo.slice(31,36);
callback(t2, t1);
}
The above code can be used like this :
var str = "Akhil is going to wrestle with hector";
useIt(str, manipulate); // Gives : Do you know that Akhil is better than hector.

So that is how we can implement Currying, Closures and Callbacks in Javascript.

Thats it folks,
Happy Hacking !!

Continue ReadingThe three C’s of Javascript

LearnJS

week4gsoc1

LearnJs is an attempt to portray the best parts of Javasript that are pretty tough and hard to find. It is to be noted that this is not a book/guide in any form, but a congregation of best practices, language constructs, and other simple yet effective snippets that gives us an essence of how we can harness the best out of the language.

So what are all covered in the cheatsheet ?

  • Intro
  • Arrays
  • Strings
  • Objects
  • Functions
  • Conventions
  • Closures
  • Currying
  • Tail Calls

Intro : Declarations

week4gsoc2

We have to understand the fact that in Javascript everything is an object, so for suppose if we declare a string using the String object and compare it with var a = “” then the outcome of the comparision would be false. This is simply because if we declare a string using the bad way and compare it with a string declared using the good way then fundamentally we are comparing a string with an Object(String).
Intro : Semicolons

week4gsoc3

Code Snippet one and two are the same. but the fundamental difference between both the code samples is that one uses semicolons in the lang- -uage semantics but whereas the other doesnot. Basically we are taught to use semicolons in languages such as C, C++, Java etc since lines of code are terminated using ‘;’ but in Javascript the entire scenario is different. There is absolutely no difference in execution of code with or without semicolons.

Objects

week4gsoc4

So basically except the primitive values all are objects in Javascript

Tail Calls

week4gsoc5

Tail calls are nothing but essentially replacing the concept of recursive functions with loop. In a way this can not only save time but also saves space i.e better time complexity and space complexity.Observing both the algorithms above written for factorial we can understand that f() is the traditional recursive method used for finding the factorial, but f1() is the tail call optimized algorithm which is better and fast.

The work is going in progress, since there is still a lot to cover.
Github : Click here
Source : Click here

Thats it folks,
Happy Hacking !!

Continue ReadingLearnJS

The beauty of Directives, Transclusion in Angular.JS

week3gsoc1

To be honest in Angular directives are nothing but DOM elements simply put on steroids. Now if you add transclusion to it literally the possibilty of exploring the playground is boundless .With that said before diving into what directives are and how cool are they, let us basically understand what makes directives in angular so powerful.

Some of the well known directives which are used regularly are :

  • ng-src
  • ng-show
  • ng-hide
  • ng-model
  • ng-repeat

Custom Directives and the benifit of creating reusable components

We often tend to waste a lot of time and energy in writing code which is already/previously written and components which are already built. But what if you could write them only once and reuse them as many times as possible ?
ANS : “Directives”
You can create truly reusable components with directives, and the approach to build custom components is definitely neater and more intuitive.
Where do Custom Directives get implemented ?

  • elements
  • attributes
  • classes

Scope of Directives

After we initialize a directive we can observe that it gets a parent scope by default. In the best interests of the application you write you won’t really want that to happen. So in order to freely modify the properties of the directive we expose the parent’s controller scope to the directives.In some cases your directive may want to add several properties and functions to the scope that are for internal use only.

Example : If you have a directive that deals with comments(just like my sTeam web interface), you may want to set some internal variable to show or hide some of its specific sections. If we set these models to the parent’s scope we would pollute it.

Without polluting, is there any option ?

Absolutely there are two options,

  • Use a child scope
  • Use an isolated scope

If we use a child scope then the child scope prototypically inherits the parent’s scope. If we use an isolated scope then its all on its own, by not inheriting its parent’s scope

Transclusion

Transclusion is a feature that enables us to wrap a directive around arbitrary content. We can extract and compile it against the correct scope later, and eventually place it at the specified position in the directive template. If you set transclude:true in the directive definition, a new transcluded scope will be created which prototypically inherits from the parent scope. If you want your directive with isolated scope to contain an arbitrary piece of content and execute it against the parent scope, transclusion can be used.

Example :

week3gsoc2

See the above snippet, here ng-transclude says where to put the transcluded content. In this case the DOM content Hello {{name}} is extracted and put inside div ng-tran- sclude /div> . The important point to remember is that the expression {{name}} interpolates against the property defined in the parent scope rather than the isolated scope.

Thats it folks,
Happy Hacking !!

Continue ReadingThe beauty of Directives, Transclusion in Angular.JS

Promises, REST API’s & Angular JS

week2gsoc1

Before breaking it down, to all those who don’t know what REST API’s are :

“REST is acronym for REpresentational State Transfer. It is architectural style for distributed hypermedia systems ans was first presented by Roy Fielding in 2000 in his famous dissertation.”

Source : “restfulapi.net”

So what is a Promise ?

Generally promises are representation of a value that which might not be available to us as of now but at some point eventually it will be available. Observe the below image to understand how promises work.

week2gsoc2

So how is this better than callbacks ?

Generally if you are using callbacks in your codebase then at some point of time either for i/o’s or file buffers or something might come in your way and makes you write nested callbacks. Writing nested callbacks is difficult and an alternative to that is promise.

week2gsoc3

REST API’s, promises what are you about to explain ?

Angular has this beautiful service called $q which is helpful for creating promises and using them in your angular applications. Generally many people have concerns over $q but $q is tightly integrated with the scope life cycle. So be it any task it contains all the necessary features needed by most of the heavy duty asynchronous tasks.

Now to start off angular can be really powerfull with the $http Service provided the fact that it has immense potential in allowing us to create heavy duty REST ful API’s, CRUD operation based web applications etc. So let us understand the $http service first before using promises for creating a REST ful API.

$http
|_____ .success()
For a success(), callback is called asynchronously when the request completes and the response arrives from the server
|_____ .error()
For an error(), the error callback is fired

Callbacks which are accpeted by above methods are :

  • data: It is a response obtained from server.
  • status: HTTP status codes 100x, 200x, 300x, 400x, etc which returned from server.
  • config: Object used for generating the request.
  • headers: Headers sent by the server.
  • statusText: HTTP status text of the status code.

Promise Chaining

Chaining is one of the most important aspects of promises. Here the basic idea is that promises can be composed through chaining. This means you can trigger a specified task only after previous promise has been resolved.

Handling errors by designing a promise that always rejects

No API is complete without writing a handler or a middleware that takes care of all the requests which are generally errored. Designing this will be useful if we want to tell a user about the occurrence of an error in terms of a promise rather than a simple value.

week2gsoc4

NOTE : Generally while using $http Service there are somethings which one should have knowledge of, If we happen to send a JS object as POST data in a POST/PUT request, it’s serialized to JSON before getting sent. Similarly, if the server responds with a JSON string it’s parsed into a JavaScript object and passed to the success callback attached to the promise.

Thats it folks,
Happy Hacking !!

Continue ReadingPromises, REST API’s & Angular JS

Factories, Services and Controllers

week1gsoc1

So before I start the blog post, it is better if you know more about what sTeam web interface is and what are the capabilites of sTeam. Click here.

So what is a Controller ?

It is simply a a constructor function which is instantiated by AngularJS when it encounters ng-controller directive in HTML.

So what is a Factory ?

In Angular Js a factory is an injectable type which helps us in encapsulating repetitive logic.

How are they helpful for sTeam web interface ?

So as my first week of work started of for GSOC, the core concentration has been on primarily working with the controllers of the workarea and integrating them with the respective views. In an attempt i started of with adding a :

commentsCtrl

: Used for adding comments to the web interface

workspaceeditorCtrl

: Used for integrating textAngular to the web interface

Things apart, in a broader aspect here what should be understood is about how things should be implemented using controllers, factories and services. Let me illustrate how it should be properly done in angular js.

To start off

How are controllers really helpful in Angular and how should they be used ?

Generally we should understand that controllers responsible for augmenting the scope which is done by attaching models and functions to it that are subsequently accessed in the view. There are some things which are to be understood while writing controllers. Lets go one by one,

  • A Straight “No” for all the DOM manipulation. This must be achieved only with directives
  • If you are having a situation where you are about to write repeatable code, then don’t do it with controllers, instead encapsulate them in services.
  • If you are trying to expose the whole controller instance then it isn’t a good idea. In fact the scope object exists in order to clear separation of concern between controller and view .

So what about Factories ?

“Services, factories, and providers are all injectable types. We must understand that Factories in angular Js are just another example for an injectable type. It looks almost the same as Service but when it comes to implementation you can decide and determine what to instantiate and return from the factory”

scribes by hector | Akhil Pandey

Let me give you a small example before i wrap up, Have a look at the below image,

week1gsoc2

Observe broadcastItem, prepForBroadcast. If you look keenly essentially what i am doing there is creating an injectable type which enables me to change the message that which has to be printed depending on the broadcast item.

One more key thing about factories is that a factory can also depend on other services or factories. Also there is one more point to grab which is we are returning an object from the factory function, so we absolutely have the freedom to determine what should be the object which is to be returned, going further we can base it on certain parameters as well.

Thats it folks,
Happy Hacking !!

Continue ReadingFactories, Services and Controllers