Prabhu Sunderaraman

Fullstack Engineer, Programmer, Writer, Trainer

prabhu.bits@gmail.com,     GitHub     Youtube     LinkedIn
  • Home
  • Profile
  • Books
  • Reading List
Browsing: / Home
Shortlink

Node JS, Non-Blocking, Asynchronous API, Event Loop and Loupe

By Prabhu Sunderaraman on March 3, 2015 in JavaScript, NodeJS

One of the core principles in NodeJS is the non-blocking design or asynchronous API or Event Loop architecture. There is a lot of noise made about this principle in the internet. A beginner who sets out to learn what this means is bound to get a bit confused. Let me see if I can add a little bit to that confusion :).

Let’s take a look at this code.

var numbers = [1,2,3,4,5,6];
numbers.forEach(function(num){
	console.log(num);
});

We print each number in the array using the forEach function. Usually developers mistake this to be asynchronous API. This code is completely synchronous, it’s functional style of coding. If you have 100 numbers and execute this code, it will get executed synchronously blocking everything else(???). So what is asynchronous then?
Let’s take a look at the following code that prints all the numbers in the collection.

var numbers = [1,2,3,4,5,6];
numbers.forEach(function(num){
	setTimeout(function(){
	  console.log(num);
	},0);
});

If you try to understand this code with naked eye, we’ll conclude that there’s no difference with the previous version. The setTimeout() function gets executed after 0 milliseconds. So, we get the same output. Ahem!

It’s only partially correct. A call to setTimeout() function involves an asynchronous call to the actual implementation of setTimeout(). The callback function is queued and executed later. In other words, this is an example of asynchronous API.

Now, if you’re wondering what the hell is going on, I am going to ask you to take a look at a fantastic tool called Loupe. Copy paste the both the versions of the code separately, and see the magic that happens before your eyes. See for yourself what Event Loop is.

Share this on: Mixx Delicious Digg Facebook Twitter
Shortlink

Swapping proxies in Sencha Touch

By Prabhu Sunderaraman on February 2, 2015 in Mobile, Sencha Touch

Here’s a simple scenario in your mobile application. You may have to load a collection of cities from the server and display them in a list. When the user accesses the app anytime later, you don’t want to fetch the cities again from the server. Instead, we would like to push the cities in local storage and access them from that storage.

It’s pretty easy to use raw localStorage API and implement it. If you are a Sencha Touch developer, you’ll notice that there are Proxy classes for working with different sources, like ajax, localStorage, sessionStorage etc. So how do we use the same Store class but switch between proxies? Let’s do that. Let’s have two proxies defined as shown below.

var localStorageProxy = {
	type : "localstorage",
	id : "name"
};
var ajaxProxy = {
	type : "ajax",
	url : "Cities",
	reader : {
		   type : "json",
		   rootProperty : "cities"
		}
};

We’ll define a single store class, say CityStore. We’ll initially wire the localStorageProxy and check if values are present in the local storage. If not, we’ll swap it with the ajaxProxy and fetch the values from the server. Then we’ll swap it with localStorageProxy and store the values in local storage. Here’s the code.

Ext.define("CityStore",{
  extend : "Ext.data.Store",
  config : {
	     fields : ["name"],
             proxy : localStorageProxy,
	     listeners : {
			     write : function(){
				 console.log("Successfully Synced to LocalStorage");
			     },
			     load : function(storeObj){
				  var count = storeObj.getCount();
				  if(count == 0 && storeObj.getProxy()
						      .getInitialConfig("type") != "ajax"){
					storeObj.setProxy(ajaxProxy);
					storeObj.load();
				  }
				  else{
					  storeObj.setProxy(localStorageProxy);
					  storeObj.sync();
				  }
			    }
		        }
	}
});

The load event of the Store class is handled to perform the swapping of proxies.

Share this on: Mixx Delicious Digg Facebook Twitter
Shortlink

Introduction to Elixir – III

By Prabhu Sunderaraman on January 31, 2015 in Elixir

This is the third and final part of the posts on introducing the Elixir language. Let’s bring in all those things we’ve have discussed so far and solve a simple problem. This is one of those simple exercises that beginners of a functional programming language usually write to get the hang of the syntax.

A simple exercise

Let’s write some code in Elixir to find the sum of all the numbers in a list. And we’ll do that recursively. We’ll define a module say SimpleExercise with a function sum as shown below.

defmodule SimpleExercise do 	
  def sum([]), do: 0 	
  def sum([head|tail]), do: head + sum(tail) 
end 

The sum function that takes in an empty list returns 0. If we pass in a non-empty list, it’s pattern-matched against head|tail and called recursively. We can invoke the sum function like this.

IO.puts SimpleExercise.sum [1,2,3,4,5] 

Here are some interesting features in Elixir that may need your attention.

Macros

I have never been a great fan of macros, from my C, C++ days. Elixir’s support for macros did make me feel grumpy, till I understood its real power. Meta-programming in Elixir is achieved through macros. In fact, all the code that we have seen so far in this article, like defining modules using defmodule, defining functions using def are macros.

Maps

Elixir introduces the map data structure that was not available in Erlang. Maps are the key-value stores that can have any item as a key. The keys are not ordered as well. The maps data structure was implemented as the keywords structure in the earlier versions of Erlang.

Atoms

Atom is an interesting data type in Elixir. Simple English words with a colon prefix can be used as identifiers in the form of atoms. For example you can define a variable climate with a value of say winter, without using it as a string. climate = :winter . To quote the Erlang documentation, Atoms are constants where their name is their own value.

Share this on: Mixx Delicious Digg Facebook Twitter
Shortlink

Introduction to Elixir – II

By Prabhu Sunderaraman on January 12, 2015 in Elixir

In the previous post, I discussed about getting started with Elixir. In this post let’s talk about immutability and pattern matching in Elixir.

In Elixir, like various functional languages, state is immutable. We cannot change the value. However the syntax paves way for reassignment of values to variables. For example in Elixir the following would work fine.

#immutability.exs  

i = 10 
IO.puts i  

i = 11 
IO.puts i 

We’ve assigned a value of 10 to the variable i. We then change the value of i to 11. Now in pure functional languages like Erlang, this is an error. We cannot reassign a value to a variable. In Elixir, the compiler creates different versions of i, like i1, i2. It looks like Elixir violates immutability, but it doesn’t. This reassignment is disallowed in several functional languages like Erlang. It’s the developer’s job(or headache) to take care of this reassignment. In Elixir, this is taken care by the compiler itself, making the developer’s job easy.

Pattern matching

We talked about the assignment/re-assignment form in Elixir. What’s interesting in Elixir is the = operator. It’s not an assignment operator. It’s a match operator. We can use the = operator to match a value against a pattern. Let’s look at the code below.

#pattern_matching.exs  

i = 10 
11 = i + 1 

The code above works fine., because the match operator =, just compares the left hand side and right hand side. In 11=i+1, the RHS is evaluated and matched with the value on LHS, 11. Say, you write an expression as shown here.

#pattern_matching.exs  

i = 10 
12 = i 

The code, 12=i will throw a MatchError as shown below.
05
Some more examples of pattern matching in Elixir, where we can use lists and tuples are shown here.

{x,y} = {"Hello", "World"} 
IO.puts "#{x} #{y}" #prints Hello and World  

numbers = [1,2,3,4] 
[head|tail] = numbers  
IO.puts head #prints 1 

In the code above, x and y are matched against the tuple {“Hello”,”World”}. We then have a numbers list [1,2,3,4], where the head is matched with the first item and the tail contains the rest of the numbers, ie., 2,3,4.

Share this on: Mixx Delicious Digg Facebook Twitter
Shortlink

Introduction to Elixir – I

By Prabhu Sunderaraman on January 6, 2015 in Elixir

Functional programming languages are at full throttle right now, thanks to multi-core processors and concurrency. The industry experts are frowning upon writing mutable code and functions have replaced the once popular objects as first class citizens. There are a number of functional languages like Scala, Clojure, Haskell, Erlang and the list goes on. In the first part of the series of articles on functional programming languages, I will introduce you to a language called Elixir.

We have JVM based functional languages like Scala and Clojure. Elixir is based on Erlang Virtual Machine (EVM). Erlang is a popular functional language that gets compiled and executed on EVM. The Elixir code that we write also gets executed on the EVM. Elixir is semantically very similar to Erlang, but more expressive and has a larger feature set.
In this article, we will set up the Elixir Environment and look at some features like immutability and pattern matching and we will wind up with a simple exercise.

Taking the first step

Getting started with Elixir is easy. You can install Elixir by using homebrew.

brew install Elixir

Homebrew installs Elixir and the pre-requisites, mainly Erlang.

Hello Elixir

Elixir gives you an interactive console iex. Let’s print Hello World in iex as shown here.
01

But that’s too simple. Let’s write our code in a file, compile it using elixirc and then run it. Elixir code spans over modules. A module is like a container that’s composed of functions. Let’s define a simple module in Elixir, add some functions to it and invoke them. We’ll create a file hello_world.ex and define a +HelloWorld* module in it.

defmodule HelloWorld do  
  def hello do    
   IO.puts "Hello World"  
  end 
end 

Let’s compile hello_world.ex using elixirc. When you do that, you get a Elixir.HelloWorld.beam file as shown below. The beam file contains the bytecodes that get executed in the EVM.
02

You can start the interactive console again and run the HelloWorld.hello function as shown below.
03

We can create Elixir scripts and directly execute them instead of compiling it and invoking it from the console. All we need to do is name the Elixir code file with a .exs extension and run it using elixir. Let’s define HelloWorld module in hello_world.exs file.

#hello_world.exs  

defmodule HelloWorld do  
  def hello do    
   IO.puts "Hello World"  
  end 
end  
HelloWorld.hello 

Execute the script from the console(not from iex) as shown here.
04

Alright!! Let’s crack some more code in the next part.

Share this on: Mixx Delicious Digg Facebook Twitter
« Previous 1 … 25 26 27 … 64 Next »

Youtube Channel




Categories

  • JavaScript (48)
    • RequireJS (5)
  • Go (44)
  • Golang (44)
  • Ext JS (23)
  • Spring (22)
  • Mobile (21)
  • Scala (20)
    • Play (3)
  • Uncategorized (19)
  • Video Sessions (18)
  • GoG (17)
  • Sencha Touch (16)
  • jQuery (14)
  • Languages (13)
  • Java 8 (12)
  • React JS (11)
  • Kotlin (11)
  • HealthyCodeMagazine (9)
  • Video (9)
  • Objective-C (8)
  • NoSQL (8)
  • Android (7)
  • MongoDB (7)
  • GWT (6)
  • Tools (6)
  • HTML 5 (5)
  • Cloud (5)
  • General (5)
  • Micro services (5)
  • Java (5)
  • Books (4)
  • AWS (4)
  • Software Architecture (4)
  • .NET (3)
  • Elixir (3)
  • Docker (3)
  • Reactive (3)
  • NodeJS (2)
  • RoR (2)
  • Backbone (1)
  • AngularJS (1)

Archives

  • 2020 (49)
  • 2019 (7)
  • 2018 (34)
  • 2017 (15)
  • 2016 (7)
  • 2015 (18)
  • 2014 (31)
  • 2013 (55)
  • 2012 (100)

Search

Subscribe




Copyright © 2025 Prabhu Sunderaraman.

Powered by WordPress and News.