Monday, January 12, 2015

Browserifying all the things

To quote a famous author,who if this blog post is to believed has started writing Javascript:
        "It is a truth universally acknowledged, that a good Javascript developer who writes           Node.js code  loves the CommonJS module format."
Before you read the rest of this article,if you are unfamiliar with browserify read the browserify handbook , if you are interested in figuring out more about alternate module systems such as requirejs .If you are unfamiliar with the module pattern go here and if you want to know why polluting the global module system is bad go here. I would rather you use these resources than have me butcher them while trying to explain them.If you are already using either the ES6 or System.js modules ,there is a ton of things you could teach me,so go on gloat over it.

Another interesting aspect is that managing your project's dependencies is easier because each dependency is listed in the package.json,this means that anyone else who works use your code , work with as either a developer,a plugin/middleware creator or as an enduser will understand the dependencies on the project and will be able to add their own in a way that is entirely transparent.

But there is more to it than just the explicit listing of dependencies,you do not need to add these dependencies to a git repository , thereby keeping it minimal , you could use npm install to install all these dependencies just as easily.

Now, imagine a scenario where you can use npm install to build all your server-side and client-side dependencies all at the same time. Ofcourse , this will also setup your grunt or gulp task runner along with any of the required tasks as well. This frees a lot of your time from chasing after dependencies that you already know you want to use or version mismatches which cause works on my system bugs when setting up a new project or setting up development environment on a virtual machine (beware of the virtualbox bug that does not allow symlinks and makes it difficult to setup cli tools) or a coworker's environment.

This is , I believe the appeal of using browserify which allows you to use the time-tested CommonJS module system , bundles your code and all of your actual dependencies(just the ones you need , not the ones you decieded to install but never use) into a single file with source map support for debugging.

And then there are transforms which allow you to dynamically compile only the handlebars template you require just before bundling , allow you to require that are built for amd only or available with bower only , compile coffeescript to javascript , compile from either SASS or LESS to CSS. Take a look at all the transforms available here . 

But , you have an understandable question , how would I load jQuery and jQuery plugins with it , certain CSS frameworks and Backbone need jQuery to be available either as jQuery or $ on the global scope.This does not solve any of my problems , it does not work for me ,it looks like an individual selling encyclopedias on the sidewalk , well dressed but offering a product that is of absolutely no use to me , you might say.

Before you slam the door in our collective faces(mine and browserify's,just because it is a module loader does not mean it does not have feelings) , listen to this , you can shim modules that are not written to take complete advantage of the commonjs module format or modules that are required by other modules to be available on the global scope using a transform called browserify-shim . 

(1) Loading Bootstrap/Semantic-UI and jQuery

jQuery has been published as an npm module that does not require shimming for a while,so you can just:

        npm install jquery --save

and 
     
       var $=require('jQuery');

Bootstrap is also available as an npm module,you can add the css to your html the same way you usually do it or you can require it using cssify or browserify-css(which supports concatenating and minifying css into a single style tag with a data-href attribute).

To shim the javascript,use this config which is an excerpt from my package.json:

 "dependencies": {  
   "bootstrap": "^3.3.1",  
   "jquery": "^2.1.3"  
  },  
  "browserify": {  
   "transform": [  
    "browserify-shim"  
   ]  
  },  
  "browser": {  
   "bootstrap": "./node_modules/bootstrap/dist/js/bootstrap.js"  
  },  
  "browserify-shim": {  
   "bootstrap": {  
    "depends": [  
     "jquery:jQuery"  
    ]  
   }  

The browser property allows you to create aliases to javascript files that you need,now go ahead and use these files within the browserify-shim property.Bootstrap expects to find jquery on the global scope as jQuery,this is specified as shown above,it depends(an array because there can be more than one dependency) on the jquery module and expects to find jQuery module,this is specified as moduleName:globalName.You can load semantic-ui in a similar manner replacing the file to be shimmed with semantic-ui instead of bootstrap.

You can either specify your transforms in the browserify command or you can preconfigure them inside transforms within package.json.I have configured the hbsfy and browserify-shim transforms to be executed whenever I browserify my code.

 "dependencies": {  
   "backbone": "^1.1.2",  
   "bootstrap": "^3.2.0",  
   "jquery": "^2.1.3"  
  },  
  "browserify": {  
   "transform": [  
    "browserify-shim",  
    "hbsfy"  
   ]  
  },  
  "browser": {  
   "bootstrap": "./node_modules/bootstrap/dist/js/bootstrap.js",  
   "backbone": "./node_modules/backbone/backbone.js",  
   "bootstrap-validator": "./bootstrap-validator-master/dist/validator.js",  
   "bootcards": "./bootcards-master/dist/js/bootcards.js",  
   "Backbone.actAs.Paginatable": "./Backbone.actAs.Paginatable-master/src/Backbone.actAs.Paginatable.js",  
   "backbone-query": "./backbone_query-master/backbone-query.js"  
  },  
  "browserify-shim": {  
   "bootstrap": {  
    "depends": [  
     "jquery:jQuery"  
    ]  
   },  
   "backbone": {  
    "depends": [  
     "jquery:$"  
    ],  
    "exports": "Backbone"  
   },  
   "bootstrap-validator": {  
    "depends": [  
     "jquery:jQuery",  
     "bootstrap"  
    ]  
   },  
   "bootcards": {  
    "depends": [  
     "jquery:$",  
     "bootstrap"  
    ]  
   },  
   "Backbone.actAs.Paginatable": {  
    "depends": [  
     "backbone:Backbone"  
    ]  
   },  
   "backbone-query": {  
    "depends": [  
     "backbone:Backbone"  
    ]  
   }  
  }  


Wait,one last thing before you leave,how would you figure out if your shim config is working,for all you know,the file you specified for the alias might not exist,maybe you specified the wrong dependencies , a ton of things could go wrong when you specify a shim config(I have hated shims ever since I first used requirejs,they are a nessecary evil caused by differing opinions and a need to support all of them),you could add a flag to inform you of all the gory details when you run browserify:

BROWSERIFYSHIM_DIAGNOSTICS=1 browserify -d . -o js/bundle.js

Thursday, January 8, 2015

The naive developers application stack

In this modern day and age of JavaScript,things change very rapidly,first we built stuff with jQuery and maybe added a bit of underscore to add a little spice to our application. Now you've moved on, it looks like you crown a new king every other day .

Yesterday you were excited about the prospect of building MV* apps , now you are talking of doing server side javascript and then using server side modules on the client side with npm whatever that means . 

Today , you are excited about this weird angularjs thingy but I do not see the difference between onclick and ng-click and wait,are you placing that script tag in the head.Now,you have module system to manage all the module systems that you built , this is dizzying . I could only wonder about what you want tomorrow,generators to generate generators that wait for other generators perhaps.

You too once used these tools,these are the tools of the naive developer,some one who is beginning their journey into the world of JS:

(i)jQuery(duh):

Every one uses jQuery and everyone recommends that everyone else use it regardless of whether they have used it,heard of it or not. This library is intensely popular with managers as the answer to the statement , the browser cannot do that and it will not work everywhere.

jQuery came into existence because writing DOM manipulation code was incredibly hard while on the other hand,targeting DOM elements for CSS is incredibly easy(the basic selectors are simple and declarative,there are other more difficult to grok css selectors that I have shot myself in the foot with).

It weeds out browser incompatibilities and ensures that your code works across all browsers , this library plays a major role in keeping IE(6-8) alive . If there is something that jQuery cannot do , there is a plugin for it.

(ii) lodash

Functional programming is a major buzzword today in the programming universe , every language is advertising itself as a functional programming language with OO support instead of the other way , functional programming allows the programmer to use beautiful expressions with minimum code.

(iii) Q 

Promises are one of the greatest things about programming in js today,if you have not heard about them,learn about them and starting using them,Promises make your asynchronous requests easier to work with and easier to encapsulate.

(iv) Handlebars/Jade

Handlebars and Jade are templating libraries that allow you to construct custom html with data much more easily,no writing millions of lines of jQuery code that creates a table element,now you have to give the same treatment to each tr and td.You can precompile these Handlebars templates for better loading time.

(v) Browserify:

Browserify sounds like a fine idea to me,but the niggling concern at the back of my head has always been this:

     How the heck do I work with jQuery,bootstrap and certain other libraries using this build tool?

The answer for now,can only be a shim configuration transform provided by browserify-shim which transforms these modules into shimmed modules.

(vi) Express + MongoDB

This is what I use to build my servers and they rarely go work, I have found that working with express is exceptional and rather intuitive.It makes the business of server-side web development very simple,it provides you with routing which I believe is the greatest thing since sliced bread.

I am still fishing around for a good behaviour driven framework to perform tests on both node and the application.Mocha seems highly promising, the jspm and Systemjs modules seem promising but I would like to continue using Browserify for atleast a while now.

The next question for me would be:

          "To stream or not to stream"

Do I use a build tool.which one do I pick and why?There are two options available,Grunt and Gulp,I have setup everything but a proper grunt-watch task.Gulp is fairly new to me and anything I do in it blows up in my face,so grunt is the tool to go to for me.

Tuesday, September 30, 2014

Templating with Handlebars

When I started developing for the web using Javascript,I thought jQuery was everything.I believed that it was a nessecary and sufficient condition to accomplish everything I wanted.With this frame of mind,I tried to accomplish the task of building fairly large pieces of markup using jQuery.This is not a pleasent task by any means,the code required to build each piece of UI would be different and difficult to build and it involved concatenating strings with variables.

However,I would not be deterred,I used a few generalized methods along with a few basic higher order functions such as foreach,map and reduce to accomplish this task.The functions I wrote accepted an object with the tag,the attributes(everything from classes to custom attributes would be placed there) and an array of children objects each of which would have the same structure as the element with their children.The task of the function was to recursively render all the children starting from the deepest level of nesting and come back to the top of the tree.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
var foreach = function foreach (arr, fn) {
   for (var i = 0; i < arr.length; i++) {
       fn(arr[i]);
   }
};

function mapFunc (arr, fn) {
   var res = [];
   foreach(arr, function (elem) {
     res.push(fn(elem));
   });
   return res;
};

function reduce (arr, base, fn) {
    foreach(arr, function (elem) {
        base = fn(base, elem);
    });
    return base;
};

function createElement(obj) {
  var res = $('<' + obj.el + '>');
  if (obj.attributes)   res.attr(obj.attributes);
  if (obj.style) res.css(obj.style);
  if (obj.text) res.text(obj.text);
  return res;
}
function createElementWithChildren (obj) {
   var res = createElement(obj);
   reduce(obj.children, res, function (base, elem) {
      var ans;
      if(!elem.children)  ans=createElement(elem);
      //this still goes to the object,finds the name bound in the object and uses it
      else   ans=createElementWithChildren(elem);       
      ans.appendTo(base);
      return base;
    });
   return res;
}

The idea was that I would have to then build methods for each element that we used and bring them together,which I did,successfully.I built an entire table using this.But this is rather cumbersome to create and difficult to maintain,besides I did not want to build a UI framework kind of thing(which I would have failed horribly at).

Then I discovered Handlebars,I could build templates,markup which allowed for placeholders that would be compiled into a function which when provided with the contextual data it required would transform magically into a string consisting of the markup with the placeholders filled in.

A template can be written in your html file like this:

1
2
3
4
5
6
7
8
9
<script type="text/x-handlebars-template" id="myTemplate>
    <img src="{{coverImage}}"/>
    <ul>
      <li>{{title}}</li>
      <li>{{author}}</li>
      <li>{{releaseDate}}</li>
      <li>{{keywords}}</li>
    </ul>
</script>

The {{}} holds the property in your context object that will be used here.In order to test this with some contextual data,you could try the http://tryhandlebarsjs.com/ website with just the template(code inside the script tag).

You must include the handlebars library either from a CDN or from a file.Having done that you can use:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
var source=$("#myTemplate").html();
var template=Handlebars.compile(source);
var context={
  coverImage:"images/placeholder.png",
  title:"Javascript Allonge",
  author:"Reginald Braithwaite",
  releaseDate:"Unknown",
  keywords:"javascript"
}
var html=template(context); 

First you load your template,using the id you provided it with,Handlebars.compile generates a function which accepts the context using which the template is converted to html.Handlebars,unlike other templating languages such as Underscore or even your server side templating languages is a logicless.By enforcing a seperation of concerns,Handlebars makes your template easier to read and maintain unlike the methods I initially showed with a hodge podge of data,markup and jQuery all thrown together.

Does this mean that you lose a lot of functionality provided by the foreach loop in the above methods to render multiple items with the same signature?Nope,Handlebars has built-in helpers for this precise reason.

You can conditionally render parts of a template using the if,else helper and repeatedly render a part of the template using the each helper.To find out about Handlebars helpers use http://handlebarsjs.com/block_helpers.html. As the documentation suggests you can write your own helpers for Handlebars using the



1
2
3
Handlebars.registerHelper('helperName',function(context,options){
   //code here
});

For example,I was recently faced with a bit of a dilemma,how could I render any object as a simple visualization that would have a names(properties) and their corresponding values in several different formats,maybe they would be encapsulated within a single list item,maybe they would have to be displayed within a table row as two columns,maybe they will act as a label and an input's value in a form.The possibilities were endless and the ideas few.

After a little thought,I built a helper that would recieve as it's context an object,the helper would convert this object into an array of objects each containing a name and a value,which would then be used as a context for whatever template is within it.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Handlebars.registerHelper("vis_2col",function(context,options){
/*
Take the keys in an object,place them in the first column while add corresponding values to a second column,this could be a table but it could be a lot more,so allow for three elements viz.
  1.an enclosing element
  2.a name element
  3.a value element
*/
  var ret="",
      i,
      key,
      con2=[];
   if(context instanceof Object)
   {
      for(key in context)
      {   
         if(context.hasOwnProperty(key))
  {       con2.push({name:key,value:context[key]});
  }
       }
       for(i=0;i<con2.length;i++)
       {
   ret=ret+options.fn(con2[i]);
       }  
    }
    return ret;
});

I was loading loading Handlebars templates from external files,I was seemingly happy,but there was already trouble in paradise.I wanted to precompile the templates,remember the compilation step of taking your template and stuffing it into the Handlebars.compile function,the idea of precompilation is that this can be done much before(or maybe just before) you load them into your page.

Handlebars is also available as a cli tool which has been packaged as an npm module.I installed that,successfully precompiled my template and tried to use it in my web page,it was a disaster...an absolute disaster.After a few month of worrying about it with several approaches and retreats,I found the issue,npm installs the handlebars 2.0. alpha module while I was using the handlebars 1.3.0 library on the client side.This was the issue that had given me bad dreams for a long time.

I installed the correct npm module as suggested here: http://stackoverflow.com/questions/24638374/precompiled-handlebars-template-not-working
And also,I switched over to using the .handlebars extensions to avoid loading templates like a.hbs in my code.

My templates were precompiled and there was much rejoicing all around...why am I alone,hmm never mind,there was great rejoicing all around.Little did they know that evil lurked around the corner.People are indescisive,they bicker,they nitpick,they fight and they seek to control the one thing they can understand,the shiny veneer of your web application the UI.They do not understand that what may seem like dragging a few pixels around might be the straw that breaks the camel's back.

Maybe you roll your own CSS,more power( and double the work) to you.Use a framework and extend it,it is much simpler.I prefer Bootstrap for no reason except that I found a good tutorial on Youtube and heard people throwing the term responsive design around.If you are using handlebars or any other templating engine,the structure of your contextual data might change depending on the markup in the template.

Is there anything that can be done to ease the pain of having to change your template every single time someone tells you to remove a form and a table.Has the mighty templating engine or does it still have a few tricks up its sleeves?Indeed it does,and it is called partials.

Usually partials are used for seperating complex templates to make them simpler and easier to maintain.However,you can use them aggressively for conditional loading,if condition is satisfied load the dropdown,otherwise display a message.Or use it for rapid prototyping,swap partials in and out of the app instead of rewriting your template if the UI change requested of you is large enough.

There is then the matter of registering partials,a wise man once stated "A template is a partial,you fool".Following the sagely advice,I have a js file with just one line in it,it says:


1
Handlebars.partials=Handlebars.templates;

Using these techniques,I have built dynamic forms where you change your partial based on the data you obtain from the server.This is the exact same thing I was trying to accomplish using the jQuery approach stated at the beginning of this blog post.In that case,Imagine,making lightning fast UI changes using a jQuery plugin based component and creating new methods to render the html every single time.Now,heave a sigh of relief,sip your coffee,keep coding with template engines and CSS framworks that just work and experience a productivity boost.

Update:
This update is sublime text specific , if you are not a sublime text user , move on.
I am currently watching  https://code.tutsplus.com/courses/perfect-workflow-in-sublime-text-2 ,

I am in the process of discovering some of Sublime Text's most amazing and awesome features,one among them being snippets . A snippet is a pre-defined block of code that can be invoked using a keyword(sublime calls it a trigger) , I have found snippets for javascript , jQuery and several other must use libraries.

I noticed that Package Control did not have any snippets for Handlebars , so I wrote a few of my own snippets based on stuff that I frequently use.I wrote a few general purpose framework agnostic snippets.To create a new snippet,go to the menu Tools->New Snippet( in Sublime Text 2) . Save the file in a folder called Handlebars , this will work on a new file if you set the syntax to Handlebars

Invoke this by typing hbs-if and pressing Tab


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<snippet>
 <content><![CDATA[
{{#if}}
 ${1:Ok}
{{/if}}  
]]></content>
 <!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
 <tabTrigger>hbs-if</tabTrigger> 
 <!-- Optional: Set a scope to limit where the snippet will trigger -->
 <!-- <scope>source.python</scope> -->
</snippet>

Invoke this by typing the tabTrigger hbs-ife and pressing if after(duh):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<snippet>
 <content><![CDATA[
{{#if}}
 ${1:ok}
 {{else}}
  ${2:nope}
{{/if}}
]]></content>
 <!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
 <tabTrigger>hbs-ife</tabTrigger>
 <!-- Optional: Set a scope to limit where the snippet will trigger -->
 <!-- <scope>source.python</scope> -->
</snippet>

This is a snippet for the each helper , I find it essential to check if the array has any data before invoking the each helper with it.In case the array is empty , you can instead provide an alternate message(if you choose to):


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<snippet>
 <content><![CDATA[
{{#if ${1:content}.length}}
 {{#each ${2:content}}}
  ${3:loop}
 {{/each}}
{{/if}}
]]></content>
 <!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
 <tabTrigger>hbs-each</tabTrigger>
 <!-- Optional: Set a scope to limit where the snippet will trigger -->
 <!-- <scope>source.python</scope> -->
</snippet>

This is the snippet for the Handlebars' killer feature,the partial:


1
2
3
4
5
6
7
8
9
<snippet>
 <content><![CDATA[
{{> ${1:partialName}}}
]]></content>
 <!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
 <tabTrigger>hbs-p</tabTrigger>
 <!-- Optional: Set a scope to limit where the snippet will trigger -->
 <!-- <scope>source.python</scope> -->
</snippet>

This is the snippet for with,which causes the template enclosed within it to be executed using the context provided to with.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<snippet>
 <content>&lt;![CDATA[
{{#with ${1:obj}}}
 ${2:context_switch}
{{/with}}
]]&gt;</content>
 <!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
 <tabtrigger>hbs-with</tabtrigger>
 <!-- Optional: Set a scope to limit where the snippet will trigger -->
 <!-- <scope>source.python</scope> -->
</snippet>

This is the snippet for the Handlebars unless helper , the unless helper checks if a condition is falsy :


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<snippet>
 <content><![CDATA[
{{#unless ${1:condition}}}
 ${2:nope}
{{/unless}}
]]></content>
 <!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
 <tabTrigger>hbs-un</tabTrigger>
 <!-- Optional: Set a scope to limit where the snippet will trigger -->
 <!-- <scope>source.python</scope> -->
</snippet>

Another interesting thing about snippets is that there are several stop points within it,when you hit Tab after the snippet has been expanded,it will go to each stop point till the end of the snippet is reached.In the xml code,the snippet is represented by ${number:default value}.

Friday, June 20, 2014

To great supsense and awesome endings

A long long time ago,everybody read serialized novels published as stories,this approach to writing was followed with great success by Charles Dickens(who is the narrator in The Old Curiosity Shop) and Arthur Conan Doyle(the death and resurrection of Sherlock Holmes is a case in point).It is widely believed that Dickens popularized the cliffhanger(atleast the word,if not the idea) and it changed the world forever.Instead of bringing the episode to a satisfactory end while assuaging the audience,authors learned that it made much more sense to have a dramatic non-ending.There are multiple advantages of doing this,firstly the mighty author did not have to figure it all out immediately,it also provides a chance for patching loose ends in the story and course-correction.Not only is it a great aesthetic device,it is the greatest sales pitch ever,if it is done right.

The community of storytellers fell in love with this idea and tried to restructure their stories to fit this framework.Using cliffhangers in a story changes everything,it changes the amount/quality of information that is presented to the reader and the charecters.It enables the author to use information,a charecter's perspective and the perception of information as tools of the narrative.It also requires that the author plan ahead(at least to an extent) and carefully craft a story to provide hints and clues leading either huge reveals/cliffhangers.Using perception and perspective as tools introduce wild and exotic ideas such as the unreliable narrator,an idea expressed at it's best by movies such as Memento and Fight Club.

Writing in this style also means that as more is revealed by/about a certain charecter,it becomes more emotionally involved and the author follows them by making the stakes bigger,keeping them interested,pushing them to care even more about the story then they believe they could have.Real world people begin discussing the story and the charecters as if they existed in the real world and a good cliffhanger causes massive speculation like the one caused by the end of the second season of Sherlock.I have begun to believe that a human being is incapable of resisting a cliffhanger,it might just be that the greatest exploit of the brain's Reward Circuit.

In the modern world,the cliffhanger has been greatly abused,reality shows will tell you who gets eliminated,game shows will tell you if this man won Rs.10,000,but only after the break.A popular series of books will tell you if the lead charecter prefers a werewolf to a vampire but only in the third novel.And an Indian soap opera asks you Did Jhanvi notice the spoon?(thank you for this one Quora).Oh GOD,is this what the world has come to?

Me: We were talking about cliffhangers,we need a cliffhanger to end this.
Sleepy Brain: What's the matter bro,just go to sleep.
Inquisitive Brain:Whose idea was it write down your ramblings now?
Subconcious: I have been researching this for a while now.
Sleepy Brain:No,you werent.Stop taking credit for my work.
Tired yet inquisitive brain: Is it possible that you unknowingly collaborated on this?
Sleepy yet alarmed brain:Dont believe the subconcious,do not trust the conscience,I did it all alone.I always get what I want.
Conscience:Did someone mention me,by the way I think...
Agitated conscience[garbled voice,unable to find an outlet]:Is anybody there?Listen to me...
Strange voice: You talkin' to me?

                                                 THE END

Sunday, March 16, 2014

Trying to level up:Reading pseudo code and libraries

Rather than being devoted to my thoughts and my obsessions,all the posts in this blog seem to be devoted to the stuff I do when I'm not compelled to do anything or the stuff I do when I ignore my responsibilities for a little while(a guilty pleasure I sometimes enjoy).Writing these posts also convinces me that I am not wasting the little time I have,I tell the guilty parts of me "See,you did enough to fill a blog post".Sometimes it also enables me to do quality brainstorming,I sometimes write new code or edit and improve my code for the blog.So essentially you can say it's more for myself than it is for you.And if I am doing this stuff in my free time,they are part of my thoughts and obsessions.This also allows me to share my code and my ideas with other developers which I rarely do.

Since the last blog post,I had enough time to read a bit of pseudo code and try my hand at implementing a few measly sorting algorithms and various linked-lists in C(please don't ask me to do the running time analysis...yet).

 #include<stdio.h>  
 #include<stdlib.h>  
 int getMaxGap(int size);  
 int* getRandomNumbers(int size,int seed);  
 int* shellSort(int arr[],int size);  
 int* getPseudoRandomNumbers(int size,int seed);  
 int getMaxGap(int size)  
 {  
      int gap=1;  
      while(gap<size)  
      {  
           gap=gap*3+1;  
      }  
      return gap/9;  
 }  
 //this gives me truly random numbers...but they are completely useless for sorting...  
 int* getRandomNumbers(int size,int seed)  
 {  
      int i;  
      srand(seed);  
      int *res=calloc(size,sizeof(int));  
      for(i=0;i<size;i++)  
      {  
           res[i]=rand();  
      }  
      return res;       
 }  
 int* getPseudoRandomNumbers(int size,int seed)  
 {  
      int i;  
      int *res=calloc(size,sizeof(int));  
      for(i=0;i<size;i++)  
      {  
           res[i]=rand()%seed;  
      }  
      return res;  
 }  
 int* insertionSort(int* arr,int size)  
 {  
      int i,j,key;  
      for(i=1;i<size;i++)  
      {  
           key=arr[i];  
           for(j=i-1;j>=0 && key<arr[j];j-=1)  
           {  
                arr[j+1]=arr[j];       
           }  
           arr[j+1]=key;       
      }  
      return arr;       
 }  
 int* shellSort(int arr[],int size)  
 {  
      int gap=getMaxGap(size);  
      int j,k,key;  
      while(gap>0)  
      {  
           for(j=gap;j<size;j++)  
           {  
                key=arr[j];  
                for(k=j-gap;k>=0 &&key<arr[k];k-=gap)  
                     arr[k+gap]=arr[k];                 
                arr[k+gap]=key;       
           }       
           gap=gap/3;  
      }  
      return arr;  
 }  
 //next for bubblesort...compare adjacent elements with one another and swap when required,you will notice that after i passes   
 //the n-1 th element is in it's proper place...  
 int* bubbleSort(int* arr,int size)  
 {  
      int i=0,pass=0;  
      int switched=1;  
      //because an element goes to it's proper place after each iteration,it would only require size-1 iterations...  
      for(pass=0;pass<size-1;pass++)  
      {  
           //for each pass...use size-pass-1 because of arr[i+1] i+1<size=>i<size-1  
           //checks if values have been swapped in this pass  
           if(switched)  
           {  
                switched=0;  
                for(i=0;i<size-pass-1;i++)  
                {  
                     if(arr[i]>arr[i+1])  
                     {  
                          switched=1;  
                          arr[i]=arr[i]+arr[i+1];  
                          arr[i+1]=arr[i]-arr[i+1];  
                          arr[i]=arr[i]-arr[i+1];  
                     }       
                }  
           }            
      }       
      return arr;       
 }  
 int main(int argc,char** argv)  
 {            
      int j;  
      int *res=getPseudoRandomNumbers(18,25);  
      printf("\nThe input array\n");  
      for(j=0;j<18;j++)  
      {  
           printf("%d\t",res[j]);  
      }  
      printf("\nThe output array is\n");  
      res=bubbleSort(res,18);  
      for(j=0;j<18;j++)  
      {  
           printf("%d\t",res[j]);  
      }  
      free(res);       
      return 0;  
 }  


I have learnt,a long time back about a magical chain of C structures called Linked Lists,this was a time when the word pointers andconsequently any code that had them terrified me before I realized that had it was just a way to directly access a memory locations and traverse them based on the size of data-type you were storing.In C,it is not just a useful feature,it is essentially the central core of the programming language.

Would you like to create an array,please specify a size so that we know how much memory to allocate in a contigious block and we wont always tell you this but what you have is the pointer to the first element,you want to update a value from a function without returning an updated value,better pass in a memory location using a pointer and change the value.Maybe you would like to hold a reference to a struct in another struct,use a pointer because structs are passed in by value.

Here is a doubly linked list that can act as a queue,a stack and a deque,I wrote this a long time back and I havent checked or updated in a while,so I am really nervous about posting it here.

 #include<stdio.h>  
 #include<stdlib.h>  
 struct Node* createNode(int val);  
 void insertBefore(struct Node* toAdd,struct Node* behind);  
 void insertAfter(struct Node* toAdd,struct Node* after);  
 void removeThis(struct Node* node);  
 void removePrevious(struct Node* node);  
 void removeNext(struct Node* node);  
 void push(int val);  
 int pop();  
 int pullHead();  
 void pushTail(int value);  
 void pushHead(int value);  
 void freeLinkedList();  
 struct Node  
 {  
      int value;  
      struct Node* next;  
      struct Node* prev;  
 };  
 typedef struct Node Node;  
 Node* head;  
 Node* createNode(int val)  
 {  
      Node* res=malloc(sizeof(Node));  
      res->value=val;  
      res->next=NULL;  
      res->prev=NULL;  
      return res;  
 }  
 void insertBefore(Node* toAdd,Node* behind)  
 {  
      if(behind==head)  
      {  
           toAdd->next=head;  
           head->prev=toAdd;  
           head=toAdd;  
      }  
      else  
      {  
           Node* back=behind->prev;  
           back->next=toAdd;  
           behind->prev=toAdd;  
           toAdd->prev=back;  
           toAdd->next=behind;  
      }  
 }  
 void insertAfter(Node* toAdd,Node* after)  
 {  
      if(after->next!=NULL)  
      {  
           Node* front=after->next;  
           after->next=toAdd;  
           toAdd->prev=after;  
           toAdd->next=front;  
           front->prev=toAdd;       
      }  
      else  
      {  
           after->next=toAdd;  
           toAdd->prev=after;  
      }       
 }  
 void removeThis(Node* node)  
 {  
      if(node==head)  
      {  
           Node* temp=head->next;  
           temp->prev=NULL;  
           head->next=NULL;  
           free(head);  
           head=temp;  
      }       
      else  
      {  
           Node* back=node->prev;  
           Node* front=node->next;  
           back->next=front;  
           front->prev=back;  
           node->next=NULL;  
           node->prev=NULL;  
           free(node);  
      }  
 }  
 void removePrevious(Node* node)  
 {  
      if(node==head)  
      {  
           puts("The head is the first node of the list,no node could be found behind it for removal");  
      }  
      else  
      {  
           Node* back=node->prev;  
           if(back->prev!=NULL)  
           {  
                Node* dback=back->prev;  
                dback->next=node;  
                node->prev=dback;  
                back->prev=NULL;  
                back->next=NULL;  
                free(back);  
           }  
           else  
           {  
                back->next=NULL;  
                node->prev=NULL;  
                head=node;  
                free(back);  
           }       
      }  
 }  
 void removeNext(Node* node)  
 {  
      if(node->next==NULL)  
      {  
           puts("This node is the tail of the list,it is not connected to any other node in the forward direction,removal impossible\n");  
      }  
      else  
      {  
           Node* temp=node->next;  
           Node* front=temp->next;  
           node->next=front;  
           front->prev=node;  
           temp->next=NULL;  
           temp->prev=NULL;  
           free(temp);  
      }  
 }  
 void push(int val)  
 {  
      Node* res=createNode(val);  
      res->value=val;  
      res->next=head;  
      head=res;  
 }  
 int pop()  
 {  
      Node* temp=head;  
      int res=temp->value;  
      head=temp->next;  
      head->prev=NULL;  
      temp->next=NULL;  
      free(temp);  
      return res;  
 }  
 int pullHead()  
 {  
      return pop();  
 }  
 void pushTail(int value)  
 {  
      //problem:find the last node needs traversal  
      Node* res=createNode(value);  
      Node* temp=head;  
      while(temp->next!=NULL)  
      {  
           temp=temp->next;  
      }  
      temp->next=res;  
 }  
 void pushHead(int value)  
 {  
      push(value);  
 }  
 void printAllNodesFrom(Node* node)  
 {  
      while(node->next!=NULL)  
      {  
           printf("%d--",node->value);  
           node=node->next;  
      }  
      printf("%d\n",node->value);  
 }  
 //BUG...  
 void printAllNodesTo(Node* node,int order)  
 {  
      //NON-ZERO:Go to head and print to node:  
      if(order)  
      {  
           Node* temp=node;  
           while(node!=head)  
           {  
                node=node->prev;  
           }  
           while(node->next!=temp)  
           {  
                printf("%d--",node->value);  
                node=node->next;  
           }  
           printf("%d\n",node->value);  
      }  
      //0:REVERSE ORDER  
      else  
      {  
           while(node->prev!=head)  
           {  
                printf("%d--",node->value);  
                node=node->prev;  
           }  
           printf("%d\n",node->prev->value);  
      }  
 }  
 void freeLinkedList()  
 {  
      Node* node=head;  
      Node* temp;  
      while(node!=NULL)  
      {  
           temp=node;  
           node=node->next;  
           temp->next=NULL;  
           temp->prev=NULL;  
           free(temp);  
      }       
 }  
 int main(int argc,char** argv)  
 {  
      head=createNode(1);//1  
      insertAfter(createNode(2),head);//1--2  
      insertBefore(createNode(3),head->next);//1--3--2  
      insertBefore(createNode(4),head);//4--1--3--2  
      printAllNodesFrom(head);  
      removeThis(head->next);//4--3--2  
      removeThis(head);//3--2  
      printAllNodesFrom(head);  
      removePrevious(head);//prints warning  
      removePrevious(head->next);//2  
      printAllNodesFrom(head);  
      push(5);//5--2  
      pushTail(6);//5--2--6  
      printAllNodesFrom(head);  
      removeNext(head);//5--6  
      printAllNodesFrom(head);  
      pop();//6  
      printAllNodesFrom(head);  
      push(7);//7--6  
      Node* n=createNode(8);  
      insertAfter(n,head->next);//7--6--8  
      freeLinkedList();  
      return 0;  
 }  


And while continuing to read the JavaScript Allonge,I came across this memoize function,I took a look at memoization on Wikipedia and luckily found some pseudo code for it that can be used inside JavaScript.The pseudo code specified appends the lookup table as a property of the function being called,I managed to create a version of the function that works for a function that requires a single parameter.Instead of doing what the pseudo-code suggested  I used a closure to use and update the lookup-table.

For multiple parameters we need to create a key,in JavaScript Allonge,the key is a JSON string of the arguments array-like object(which is hated and reviled by the JS community so much so that it is preparing to leave JavaScript in the future).The version of memoize allows you to pass your keymaker function which can be used instead of what I described above.In other blog posts over the web people have used recursion and closures in memoization which I would rather not do.


 var memoize=function(fn,context)  
 {  
   var cache={};  
   return function(param)  
   {  
     if(!cache[param])  
     {  
       cache[param]=fn.call(context,param);  
     }  
     return cache[param];  
   }  
 }  
 console.log(memoize(fibbonaci)(20));  
 console.log(memoize(factorial)(5));  
 function factorial(n)  
 {  
   if(n==0)  
     return 1;  
   else  
     return n*factorial(n-1);    
 }  
 function fibbonaci(n)  
 {  
   if(n==0 || n==1)  
     return 1;    
   else  
   {  
     return fibbonaci(n-1)+fibbonaci(n-2);  
   }  
 }  


I have also started reading the source code of libraries such as http://bit.ly/1d3jrlA which is about 350 lines and is concerned with functional programming in JavaScript which might even serve as a gentle soothing introduction to reading the source code of some of the other open source libraries such as underscore,requirejs and jquery that  I would like to work with/am working with.However I do not like it that the string lambdas used there do not allow me to create closures because closures allow encapsulation and awesome functions such as memoization.

I remember watching a video where Crockford said that the arguments array must only be used in a read-only manner because it could break compatibility with older versions of the Public Enemy#1 where arguments does not inherit from Array.prototype.So,I guess I should be worried about using this function.


 Functional.compose = function () {  
   var fns = Functional.map(Function.toFunction, arguments),  
     arglen = fns.length;  
   return function () {  
     for (var i = arglen; --i >= 0;)  
       arguments = [fns[i].apply(this, arguments)];//should we fiddle with the arguments like this??  
     return arguments[0];  
   }  
 }  


Now,there is this and then there is THIS,that monstrous keyword that breaks code by just changing to the value to the global object or to undefined(since ES5).And thus,I decided to try the arrow functions in the Firefox scratchpad.

 var harmonyFunc=s => s;  
 alert(harmonyFunc(2));  
 var harmonyFunc2=() => 'Welcome to the Matrix,Neo';  
 alert(harmonyFunc2());  
 //These lyrics found themselves on Mozilla Developer Network from a Maroon5 Song  
 var a=["We're up all night 'till the sun",  
     "We're up all night to get some",  
     "We're up all night for good fun",  
     "We're up all night to get lucky"  
    ];  
 //defining an anonymous inner function...  
 var harmonyFunc3=a.map(s=>s.length);  
 alert(JSON.stringify(harmonyFunc3));  
 var PersonOriginal=function()  
 {  
   this.age=0;  
   setInterval(()=>{  
     if(this.age<24)  
     {  
       console.log(age);  
       this.age++;//this refers to person  
     }  
   },1000);  
 }  
 //cannot create constructors using the harmony functional notation  
 //something to remember when you are creating brand new objects...this  
 //is because it does not have a sense of this...evil smiley face  
 var Person=() => {  
   this.age=0;  
   setInterval(()=>{  
     if(this.age<24)  
     {  
       console.log(age);  
       this.age++;//this refers to person  
     }  
   },1000);  
 }  
 var p=new Person();  

Does this allow me to use call and apply and continue passing an object around just for it's context?Will this allow me to do recursion without using named functions which leads me to worry about hoisting.If not,I could use fancy combinator logic that I am a few(much more than a few) light years away from understanding.

 var memoize=(fn,context) =>{  
   var cache={};  
   return param =>{  
    if(!cache[param])  
    {  
     cache[param]=fn.call(context,param);  
    }  
    return cache[param];  
   }    
 };  
 var factorial=n => {  
   if(n==0)  
   {  
     return 1;  
   }  
   else  
   {  
     return n* factorial(n-1);  
   }  
 }  
 alert(memoize(factorial)(6,null));  

This works,so we have recursion without having to resort to named functions(which get hoisted) because named function expressions do not work in IE<=8.The next logical step was to test for
hoisting ,so I moved the alert to the top of the script.It says function not defined,similarly for factorial.

I think passing an object around for it's context is a Java-like move for a language trying to move away from Java.We could instead use a property attached to the object that uniquely represents the property which is even more Java like.It is interesting to notice how Android duplicates this pattern providing each Activity with a Context that is accessible via the this keyword.It then uses the context to call other contexts like another Activity or a shared resource like the Location Service.It is also interesting how you can refer to the enclosing context from a Thread in an Activity or a Service using getBaseContext and the application using getApplicationContext from anywhere.Here,this is a reference to Context object.

 LocationManager lm=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);  
 startActivity(new Intent(this,XYZActi ity.class);  
 getBaseContext();  
 getApplicationContext();  

I also managed to write a function that creates DOM elements using JavaScript this is a badly structured example which does not concern itself with Public Enemy #1,know to the enterprise as The ONE and commonly referred to as Internet Explorer. By writing this function,I think I understand why Backbone use mixins(so I have been told) for creating new Views.If I had a chance to do it all over again,I would pass it an object instead.


 define(function () {  
   function isArray(arg)  
   {  
     return arg && arg instanceof Array;  
   }  
   function isObject(obj)  
   {  
     return obj && obj instanceof Object;  
   }  
   return {  
     createSimpleElement:function(name,value)  
     {  
       var res=document.createElement(''+name);  
       res.innerHTML=value;   
       return res;  
     },  
     createFindableElement:function(name,value,id,classes)  
     {  
       var self=this;   
       var res=self.createSimpleElement(name,value);  
       if(isArray(id))  
       {  
        res.id=''+id[0];  
       }  
       else if(!isObject(res))  
       {  
        res.id=''+id;  
       }      
       if (classes && typeof classes === 'string')  
       {  
         res.className += classes;  
       }   
       else if (isArray(classes))  
       {  
         for (i = 0; i < classes.length; i++)  
         {  
           res.className += ' ' + classes[i];  
         }  
       }  
       return res;  
     },  
     createStyledElement:function(name,value,id,classes,styles)  
     {  
       var self=this;  
       var res=self.createFindableElement(name,value,id,classes);  
       if(isObject(styles))  
       {  
        for (i in styles)  
         {  
           if (styles.hasOwnProperty(i))  
           {  
             res.style[i] = styles[i];  
           }  
         }  
       }  
       return res;  
     },  
     createElement: function (name, value,id,classes, styles, events, addTo)  
     {  
       var i = 0;  
       var self=this;  
       var res=self.createStyledElement(name,value,id,classes,styles,events,addTo);  
       if (events && events instanceof Object)  
       {  
         for (i in events)  
         {  
           if (events.hasOwnProperty(i));  
           {  
             res.addEventListener(i, events[i], false);  
           }  
         }  
       }  
       addTo.appendChild(res);  
       return res;  
     }  
   }  
 });  

I was trying to demonstrate an example of how to use the DOM API to generate new elements while using requirejs without making use of jquery.The design criteria was simple,allow creating an element by it's name and value.Add a class or a set of classes and an id to it which makes it more easy to find and assign styles to from other places.The idea was allow passing styles and events in as objects and currying the function for all the values which I later realized was a bad idea.So,instead of a single function I created a group of functions to handle this.

Thanks for reading guys and I cannot believe I created a multi-lingual programming post(pats self really hard on the back and grimaces in pain).

Friday, February 21, 2014

A few cool Javascript functions

For me,learning Javascript has been an extra-curricular activity,my work has never required me to use JavaScript at any time.In fact,as an app developer working on native Android apps,I am almost completely sealed off from it.So,I have never been obliged to learn to write code to handle DOM events or use jQuery and some of it's plugins to do cool things.

This left me free to just relax,unwind and experience new levels of puzzlement(http://www.merriam-webster.com/dictionary/puzzlement),bewilderment,embarrasment and frustration while exploring the language using blogs,books and the occasional video as my resources.Although it seems simple to access,the language had hidden layers giving the programmer a billion ways to shoot himself in the foot.And just like Android's million Runtime errors it appealed to me.And finally,the idea that a function isnt set in stone,that you could modify how it is called,who calls it and even what it is called on using other functions.

These are some interesting functions I have learnt about:

1.foreach,map and mapWith:


1:  var foreach=function(arr,fn)  
2:  {  
3:            var i;  
4:            for(i=0;i<arr.length;i++)  
5:            {  
6:                 fn(arr[i]);  
7:            }  
8:  };  
9:  var map=function(fn,arr)  
10:  {  
11:       var res=[];  
12:       foreach(arr,function(elem){  
13:            res.push(fn(elem));  
14:       });       
15:       return res;  
16:  };  
17:  var mapwith=function(fn)  
18:  {  
19:       return function(arr)  
20:       {  
21:            return map(fn,arr);  
22:       }  
23:  };  

The first two functions I encountered in Eloquent Javascript,the third I found in Javascript Allonge.This is the kind of tool that I dreamed of possessing when I first started programming,the ability to take an arbitrarily large array,process it and return the results as an array.I try and use these functions as much as possible.In fact,whenever I see an array in Javascript,I cant help but think of map and mapWith.

I have come to understand that Array.prototype now has a map method which is much simpler to use because it is called like this:


 var numbers = [1, 4, 9];  
 var roots = numbers.map(Math.sqrt);  

2.partial application and flip

Once upon a time,I saw a freaking crazy video featuring libraries and code I had no clue about but the idea was so cool that I decided to learn enough JavaScript to understand how to do it.The video was a talk about how underscore js' partial application,autocurry and certain other functions were not to the liking of the speaker Brian Lonsdorf's liking.This was another tool I wanted when I was learning to program,so it was another dream come true for me.



1:  var autoCurry=function(fn)  
2:  {  
3:       var n=fn.length;  
4:       return function()  
5:       {  
6:            var args=[];  
7:            var _slice=Array.prototype.slice;  
8:            function argsCollector()  
9:            {  
10:                 //if this function were not a named function,it's name would have to be looked up in the enclosing environment   
11:                 //instead of within itself...  
12:                 args=args.concat(_slice.apply(arguments));  
13:                 if(args.length>=n)  
14:                 {  
15:                      return fn.apply(null,args);  
16:                 }  
17:                 return argsCollector;  
18:            }  
19:            return argsCollector.apply(null,_slice.apply(arguments));  
20:       }  
21:  };  

I found this function in a gist on Github(dont exactly remember where).I also understand that the arguments Array-like-object inherits from Array.prototype since ES5 and therfore can have Array method calls performed on it.

Then there is my version,I got stuck on this for a long time because I was not updating the Array after concatenation.



1:  var myCurry=function(fn)  
2:  {  
3:       var len=fn.length;  
4:       var _slice=Array.prototype.slice;  
5:       var args=_slice.call(arguments,1);  
6:       console.log(args.length);  
7:       return function next()  
8:       {  
9:            var rem=_slice.call(arguments,0)  
10:            //args.concat(rem);//concat returns a new Array and returns another Array...  
11:            //Array.prototype.push.call(args,rem);  
12:            args=args.concat(rem);  
13:            console.log(args.length);  
14:            if(len<=args.length)  
15:                 return fn.apply(null,args);  
16:            else  
17:                 return next;  
18:       }  
19:  }  

There are versions of this function in underscorejs and wujs libraries as well,I took a look at the wu js  implementation while reading Angus Croll's blog and it really confused me but they have an interesting idea of calling it with a length parameter which means you can use


 var len=length || fn.length;  


There is also a version of this function written by John  Resig in the book Secrets of the JavaScript Ninja that someone posted on stackoverflow:



1:  Function.prototype.partial = function() {  
2:     var fn = this, args = Array.prototype.slice.call(arguments);  
3:     return function() {  
4:      var arg = 0;  
5:      for (var i = 0; i < args.length && arg < arguments.length; i++) {  
6:       if (args[i] === undefined) {  
7:        args[i] = arguments[arg++]; //This line is where the confusion is  
8:       }  
9:      }  
10:      return fn.apply(this, args);  
11:     };  
12:   };  

This function is called on another function either as a method or using call or apply,the function on which this has been called becomes this and is stored in fn.The interesting part is that if any of the arguments supplied to partial is undefined,it gets replaced by an argument supplied to the function.On the other hand it does not check for function's length.

I also loved the flip function which allows you to flip the arguments of a function,this is another function that I always wanted to do,just because it was cool,not much for practical utility of it.I found an implementation in the excellent Javascript Allonge:


1:  var flip=function(fn)  
2:  {  
3:    return function(first)  
4:    {  
5:      return function(second)  
6:      {  
7:        fn.call(null,second,first);  
8:      }  
9:    }  
10:  };  

This function uses only two parameters,to extend it to have more than two parameters .This is a function I created so that I could flip a function with multiple arguments conveniantly.I decided not to curry till all the arguments of a function are obtained,instead I decided to append undefined to the end of the array representing arguments in case there were fewer arguments than required.But before I could do this I flipped the array representing the arguments so that the function could theoretically run with enough parameters.I am still agonizing over slicing the array to the length specified.



1:  var flip2=function(fn,length)  
2:  {  
3:    var len=length || fn.length;  
4:    var args=Array.prototype.slice.call(arguments,1);  
5:    return function()  
6:    {  
7:     args=args.concat(Array.prototype.slice.call(arguments,0));  
8:     var missingArgs,argPadding;  
9:     if(args.length<=len)  
10:     {  
11:      missingArgs=Math.max(0,len-args.length-1);  
12:      argPadding=new Array(missingArgs);  
13:      args.reverse();  
14:      args=args.concat(argPadding);  
15:     }  
16:     else  
17:      args.reverse();  
18:     fn.apply(null,args);  
19:    }  
20:  };  

This function was also influenced by an implementation of partial application in the first recipes section of Javascript Allonge.

3.serial

I was watching a Node presentation given  by Nick Nisi  at the Nebraska Javascript Group on Youtube,amon other things he was also talking about an npm library called comb which has a function called serial which will take an array of functions as it's input and return(I'm guessing) an array of values(some of which could be functions),I decided to take a stab at writing it.Here is a rather simplistic implementation of serial which I managed to complete before I was again inuandated with work.


1:  var serial = function serial(funcs, params) {  
2:   //it does not execute all the functions unless you have specified enough or more than enough parameters.   
3:   //it would be nice to return all the values as an array.  
4:   //wont work if any of the functions use arguments in their call(ofcourse),so this cannot be used with a lot of stuff  
5:   var i, args, key,  
6:   max = Math.min(funcs.length, params.length),  
7:    res = [];  
8:   for (i = 0; i < max; i++) {  
9:    args = [];  
10:    if (params[i] != null) {  
11:     for (key in params[i]) {  
12:      if (params[i].hasOwnProperty(key)) {  
13:       //would be nice to map values here and parameters in the function...  
14:       console.log(params[i]['' + key]);  
15:       args.push(params[i]['' + key]);  
16:      }  
17:     }  
18:    }  
19:    res.push(funcs[i].apply(null, args));  
20:    args = [];  
21:   }  
22:   return res;  
23:  };  

As specifed in the comments along with the code this function only executes a function if an object consisting of parameters is provided for it.If a function does not have enough arguments the result is not obtained.

I guess we could return the autocurry function in order to ensure that the remaining arguments are passed to the function before it is executed but that would mean that the existing argument set is discarded and not applied to the function,which then has no option but to start anew.The function will return undefined in case it depends entirely upon the arguments array-like-object for it's execution.




1:  serial([function()  
2:      {  
3:        return 'Hello world'  
4:      },  
5:      function(x,y)  
6:      {  
7:        return x+y;  
8:      },  
9:      function(x,y,z)  
10:      {  
11:        return x+y+z;  
12:      },  
13:      function()  
14:      {  
15:        var res;  
16:        var args=Array.prototype.slice(arguments,null);  
17:        for(var i=0;i<args.length;i++)  
18:        {  
19:          res+=args[i];  
20:        }  
21:        return res;  
22:      }],  
23:      [null,  
24:       {x:2,y:3},  
25:       {x:2,y:4},  
26:       {x:2,y:3,z:5}  
27:       ]);  

I would also like to map the arguments to the function as they were passed.Now,as you might already have guessed the arguments are passed based on a first-come first-serve,I do not care about your name way but it would just be nice(atleast in my opinion) if we could do mapping of arguments to the function by name.


For that I have discovered this function(thank you Stack Overflow) whose input is a function which it converts to a string and uses a regular expression to isolate the values between ( and ) and splits them based on the , charecter.


1:  var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;  
2:  var getParamNames=function getParamNames(func) {  
3:   var fnStr = func.toString().replace(STRIP_COMMENTS, '')  
4:   var result = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(/([^\s,]+)/g)  
5:   if (result === null) result = []  
6:   return result  
7:  };  


1:  var serial=function serial(funcs,params)  
2:  {  
3:   var i,args,key,  
4:   max=Math.min(funcs.length,params.length),res=[];  
5:   for(i=0;i<max;i++)  
6:   {  
7:     args=[];  
8:     if(params[i]!=null)  
9:     {  
10:      for(key in params[i])  
11:     {  
12:       if(params[i].hasOwnProperty(key))  
13:       {  
14:         //would be nice to map values here and parameters in the function...  
15:         console.log(params[i][''+key]);  
16:         args.push(params[i][''+key]);  
17:       }  
18:     }  
19:     }  
20:     if(funcs[i].length>args.length)  
21:     {  
22:      //this will start applying the function anew with new arguments  
23:      res.push(mycurry(funcs[i]));  
24:     }  
25:     else  
26:     {  
27:      res.push(funcs[i].apply(null,args));   
28:     }  
29:      args=[];   
30:   }  
31:   return res;  
32:  };  

The only issue I percieve with this function  is that it requires that the arguments be passed anew.Any previous arguments that we might have passed to it before are sent to a deep dark abyss.You could unwind the args arrays and pass it to the autocurry function or you could instead do this horrifyingly tortuously(http://www.thefreedictionary.com/tortuously) which is different from  torturous(lesson learned!!!) chained thing.But hey,it works.

  res.push(mycurry.apply(null,[funcs[i]].concat(args)));  

Some of the functions I represented here might not be the most used or the most useful functions but they are fun ideas and dreams turned into reality.I wanted to write about so many other functions but these were the functions that came to mind when I conceived of this blog post.

Update:

Here is a function that maps the arguments of a function to the properties of an object.If a property matching the parameter name cannot be found,it instead places undefined there.Here is the function:


1:  var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;  
2:  var getParamNames=function getParamNames(func) {  
3:   var fnStr = func.toString().replace(STRIP_COMMENTS, '')  
4:   var result = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(/([^\s,]+)/g)  
5:   if (result === null) result = []  
6:   return result  
7:  };  
8:  //pick properties from an object based on a function's arguments  
9:  var chooseArguments=function chooseArguments(fn)  
10:  {  
11:   var fn_args=getParamNames(fn);  
12:   return function(obj)  
13:   {  
14:    var i,res=[],key;  
15:    for(i=0;i<fn_args.length;i++)  
16:    {  
17:     if(obj[fn_args[i]]!=null)  
18:     {  
19:      res.push(obj[fn_args[i]]);  
20:     }  
21:      else  
22:        res.push(void 0);  
23:    }  
24:     return res;  
25:   }  
26:  }  
27:  var checkAdd=chooseArguments(function(x,y){return x+y});  
28:  var args_add=checkAdd({z:10,y:3});  
29:  alert(args_add);  

This function does not play nicely with the currying function as we always have enough arguments,although some of these arguments are undefined.So,we need a new currying function that can only replaces undefined values in your array of arguments,an initial version looks like this:


1:  var replaceUndefinedArgs=function(arr)  
2:  {  
3:    var i,j=0;  
4:    var args=Array.prototype.slice.call(arguments,1);  
5:    for(i=0;i<arr.length;i++)  
6:    {  
7:      if(arr[i]==null)  
8:      {  
9:        if(j<args.length)  
10:        {  
11:          arr[i]=args[j];  
12:          j++;  
13:        }  
14:      }    
15:    }  
16:  //arr is copied by reference so a mutation to arr ripples through space and time...so no need //to return arr  
17:  };    

I am an unfortunate soul because the word what-if scares me and drives me to do some crazy stuf.So here it is,WHAT IF you did not pass enough arguments to dispel undefined from the array.You must find out how many arguments you need to curry for in the initial array. Ensure that the function keeps returning another function until the exact number of arguments has been reached.

This is a function that keeps querying for more arguments until it has enough arguments to replace all the undefined values in your array,this is a version of the auto-currying function that just uses an array instead of a function,pretty straightforward by now,I guess.We dont return the array,of course because it has copied by reference and need not be returned.

1:  var replaceUndefinedArgs=function(arr)  
2:  {  
3:    var i,len=0;  
4:    for(i=0;i<arr.length;i++)  
5:    {  
6:      if(arr[i]==null)  
7:        len++;  
8:    }    
9:    var args=Array.prototype.slice.call(arguments,1);  
10:    return function next()  
11:    {  
12:      var j=0;  
13:      args=args.concat(Array.prototype.slice.call(arguments,0));  
14:      if(len>0 && args.length<len)  
15:      {  
16:       return next;  
17:      }  
18:      else  
19:      {  
20:       for(i=0;i<arr.length;i++)  
21:       {  
22:         if(arr[i]==null)  
23:         {  
24:          arr[i]=args[j];  
25:          j++;  
26:         }    
27:       }  
28:      }    
29:    }     
30:  };  

So,I guess this is kind of a generic pattern in functional programming to do,return a function,task it with doing something.This function takes care of odd-user behaviour and other environmental factors.When the function has exactly what you need,you can do what you originally intented to to.

Now these functions are ready to be added to serial,so that we can map arguments to values,setting undefined when no value is found,if nessecary we can force these undefined values to have values by currying for them.

Sunday, February 16, 2014

Javascript inheritance:A cautionary tale

I am currently working on a project that uses the Google Maps V3 API as a frontend.I had to create Polygons and display it on the map,sounds simple enough right.I took a look at the samples and did this:
 var polyPoints=[];  
      polyPoints.splice(0,0,new google.maps.LatLng(-34.9290,138.6010),new google.maps.LatLng(-37.8136,144.9631),new google.maps.LatLng(-27.4679,153.0278));  
 var polygon=new google.maps.Polygon({  
   paths: polyPoints,  
   strokeColor: '#FF0000',  
   strokeOpacity: 0.8,  
   strokeWeight: 2,  
   fillColor: '#FF0000',  
   fillOpacity: 0.35  
  });  

I was trying to be clever,see how I take something very simple and twist it around.I had just discovered that you could add items to an Array using slice and I wanted to use it everywhere.In a moment we will see how this tendancy of mine leads me into trouble.

I had just learnt to use functions as constructors and here,standing right before me was a case where this idea could be applied to:

 var configurePolygonOptions=function configurePolygonOptions(strokeColor,strokeWeight,strokeOpacity,fillColor,fillOpacity)  
 {  
      this.strokeColor=strokeColor;  
      this.strokeWeight=strokeWeight;  
      this.strokeOpacity=strokeOpacity;  
      this.fillColor=fillColor;  
      this.fillOpacity=fillOpacity;  
 };  

An object is then instantiated using the new keyword which calls a function using the constructor form and sets this to the object created and  the object's constructor property to be the function itself.However this object can only be used to initialize the Polygon's properties and goes no further than that(as I later found out).By the time this key piece of information reached the evil genius(a movie cliche bound to fail) had decided to go overboard and do this:


 configurePolygonOptions.prototype.setStrokeColor=function setStrokeColor(color)  
 {  
      this.strokeColor=color;  
 };  
 configurePolygonOptions.prototype.setStrokeWeight=function setStrokeWeight(weight)  
 {  
      this.strokeWeight=weight;  
 };  
 configurePolygonOptions.prototype.setStrokeOpacity=function setStrokeOpacity(weight)  
 {  
      this.strokeWeight=strokeWeight;  
 };  
 configurePolygonOptions.prototype.setFillColor=function setFillColor(color)  
 {  
      this.fillColor=color;  
 };  
 configurePolygonOptions.prototype.setFillOpacity=function setFillOpacity(opacity)  
 {  
      this.fillOpacity=opacity;  
 };  
 configurePolygonOptions.prototype.setProperty=function setProperty(prop,value)  
 {  
      this[prop]=value;  
 };  
 configurePolygonOptions.prototype.setPaths=function setPathsForPolygon(paths)   
  {    
    this.paths=paths;   
    console.log('The points have been added to polygon options');   
  };   
  configurePolygonOptions.prototype.setEditable=function(edit)   
  {   
    this.editable=edit;   
  };   
  configurePolygonOptions.prototype.setDraggable=function(drag)   
  {   
    this.draggable=drag;   
  };   

So,all this code is useless,but then I look at the API for drawing a circle and a rectangle and say to myself "How about trying out that inheritance concept you just learnt about?"


 var createRectangle=function createRectangle(strokeColor,strokeWeight,strokeOpacity,fillColor,fillOpacity)  
 {  
           configurePolygonOptions.apply(this,[strokeColor,strokeWeight,strokeOpacity,fillColor,fillOpacity]);  
 };  
 createRectangle.prototype=Object.create(configurePolygonOptions.prototype);  
 createRectangle.prototype.constructor=createRectangle;  
 createRectangle.prototype.setBounds=function(bounds)  
 {  
      console.log('setting bounds');  
      this.bounds=bounds;  
 };  
      var configureCircle=function configureCircle(strokeColor,strokeWeight,strokeOpacity,fillColor,fillOpacity)  
     {  
           configurePolygonOptions.apply(this,[strokeColor,strokeWeight,strokeOpacity,fillColor,fillOpacity]);  
           //configurePolygonOptions.call(this);  
};  
configureCircle.prototype=Object.create(configurePolygonOptions.prototype);  
configureCircle.prototype.constructor=configureCircle;  
configureCircle.prototype.setCenter=function(center)  
{  
     this.center=center;  
};  
configureCircle.prototype.setRadius=function(radius)  
{  
     this.radius=radius;  
};  

There was so much extra code but with no apparent problems,so I had to go create one,I noticed a map parameter within the object used  for Circle and Rectangle,I should have passed it in as an extra parameter and let it slide but I thought what if I could add a setMap method to configurePolygonOptions.prototype  and I would automatically inherit it(just like JAVA)

And here it is,after adding this code in,I found that Polygons would not be rendered on the map:



 configurePolygonOptions.prototype.setMap=function(map)  
 {  
      this.map=map;  
 };  
 var createPolygon=function createPolygon(options)  
 {  
      var pgon= new google.maps.Polygon(options);  
      console.log('created a polygon based on options provided');  
      return pgon;  
 };  
 var addPolygonToMap=function addPolygonToMap(poly)  
 {  
      poly.setMap(map);  
      console.log('added polygon to map');  
 };  

After trying a few different things like putting console.log methods evrywhere regardless of their relative,yelling at the computer,I posted a question on stackoverflow.When you create an instance of the Google Maps v3 API's Polygon object using an object you pass it,instead of protecting it's private members it instead allows overriding any properties the object has.(Yeah,blame the API and not yourself for not using the API the way you were meant to) and I had overridden the setMap method of Polygon which Circle and Rectangle did not have.

Should Google's API have protected the properties inside their object and only offer them for modification using methods like say,they would in Java?I do not know the answer to that,coming from a OO background,I would like that but...is it for everyone?

Lessons learned:

1.Keep your code simple,dont show off.
2.Use an API how it is meant to be.
3.Inheritance is evil.Use with care.(Are mixins evil too?)

Please comment and let me know what you think.