Skip to main content

JavaScript: underscorejs with examples

In previous post I have mention about underscorejs library. And here is the another post to explain bit more about this library.

Some functions used in below example to improve readability 
function prop(name){
 return function(obj){
  return obj[name];
 }
}

function compareProp(prop, contextProp){
 return function(obj){
  return obj[prop] === this[contextProp];
 }
}

Find visible user and show it’s default view
Below is the list of JSON array with user object data. Now we want to show all visible user with it’s default view.
var ar = [{
 name: 'moe',
 age: 40,
 display: true,
 defaultView: 1,
 views: [ 
  { name: 'Admin', id: 1 }, 
    { name: 'Role1', id: 2 }, 
    { name: 'Role2', id: 3 } 
]},{
 name: 'larry',
 age: 50,
 display: false,
 defaultView: 1,
 views: [ 
  { name: 'Admin', id: 1 }, 
    { name: 'Role1', id: 2 }, 
    { name: 'Role2', id: 3 } 
]},{
 name: 'curly',
 age: 60,
 display: true,
 defaultView: 2,
 views: [ 
  { name: 'Admin', id: 1 }, 
    { name: 'Role1', id: 2 }, 
    { name: 'Role2', id: 3 } 
]}];

Output must be
["moe has default view of Admin", 
"curly has default view of Role1"]

Solution without underscorejs library
var data = [];
for(var i=0, il=ar.length; i<il; i++){
    var item = ar[i];
    if(item.display){
        var str = item.name + " has default view of ";
        for(var j=0, jl=item.views.length; j<jl; j++){
            var view = item.views[j];
            if(view.id === item.defaultView){
                str += view.name;
                data.push(str);
                break;
            }
        }
    }
}

And after using underscorejs library
var userDefaultView = function(user){ 
 return user.name + ' has default view of '+ _.find(user.views,compareProp('id','defaultView'),user).name;
}

by using filter and map
_.chain(ar)
    .filter(prop('display'))
    .map(userDefaultView).value();
Above method will iterate twice on the list, first for filtering and then for transforming, so performance will not be so good. Here is the better way of achieving the same thing by using reduce method.
_.reduce(ar, function(memo, user){
    if(user.display){ 
        memo.push(userDefaultView(user)); 
    }
    return memo;
}, []);
Parse array data based on it’s type
var data = [
 { value:"test string",  type:"string" },
 { value:"221132",   type:"int" },
 { value:"21112.21212",  type:"float" },
 { value:"2012-09-22T17:01Z", type:"date" },
 { value:"2012-09-22T17:01Z", type:"datetime" },
 { value:"test2 string",  type:"string" },
 { value:"True",   type:"boolean" },
 { value:"234.1214",  type:"int" },
 { value:"2000-09-22T04:20Z", type:"date" },
 { value:"False",   type:"boolean" }
];
and output must be
["test string",
221132,
21112.21212,
"9/22/2012",
"9/22/2012 17:01",
"test2 string",
true,
234,
"9/22/2000",
false]
some formatter functions
var formattor = function(){
 function stringFormattor(value)  { return value; }
 function intFormattor(value)  { return parseInt(value, 10); }
 function floatFormattor(value)  { return parseFloat(value, 10); }
 function dateFormattor(value)  { return Date.parse(value).toString("M/d/yyyy"); }
 function datetimeFormattor(value) { return Date.parse(value).toString("M/d/yyyy HH:mm"); }
 function booleanFormattor(value) { return value === "True"; }

 return {
  "string" : stringFormattor,
  "int"  : intFormattor,
  "float"  : floatFormattor,
  "date"  : dateFormattor,
  "datetime" : datetimeFormattor,
  "boolean" : booleanFormattor
 };
}();

And now our underscorejs solution
_.map(data, function(obj){ return formattor[obj.type](obj.value);});
It is really short and expressive code.

Normalize the data
In one of the scenario, we were dealing with large amount of data. And some time data list used to have nested array and it was causing the search too slow.  Our first implementation of search function had complexity of O(n) and it’s become O(n2) for another nested array and so on. It was so bad that, some time browser use to become unresponsive.
To overcome from this issue we decided to normalize the data array to single object and make elements unique property as key. And by doing this the search function complexity is reduce to perfect O(1).  Because after normalization we were simply accessing the property instead of find it.

For example if you want to get child “c2” in “p1” element then code will be: “data[‘p1’][‘c2’]”

Here is the raw data
var data = [{
 key: 'p1',
 name: 'parent-1',
 childs: [{key: 'c1',name: 'child-1'},{key: 'c2',name: 'child-2'},{key: 'c3',name: 'child-3'}]
},{
 key: 'p2',
 name: 'parent-2',
 childs: [{key: 'c3',name: 'child-3'},{key: 'c4',name: 'child-4'},{key: 'c5',name: 'child-5'}]
},{
 key: 'p3',
 name: 'parent-3',
 childs: [{key: 'c11',name: 'child-11'},{key: 'c12',name: 'child-12'},{key: 'c13',name: 'child-13'}]
},{
 key: 'p4',
 name: 'parent-4',
 childs: [{key: 'c12',name: 'child-12'},{key: 'c14',name: 'child-14'},{key: 'c11',name: 'child-11'}]
},{
 key: 'p5',
 name: 'parent-5',
 childs: [{key: 'c8',name: 'child-8'},{key: 'c1',name: 'child-1'},{key: 'c3',name: 'child-3'}]
},{
 key: 'p6',
 name: 'parent-6'
}];

And expected output after data normalization
{
 p1: {
  key: 'p1',
  name: 'parent-1',
  childs: {
   c1: {key: 'c1',name: 'child-1'},
   c2: {key: 'c2',name: 'child-2'},
   c3: {key: 'c3',name: 'child-3'}
  }
 }, 
...
}
Solution
var normalize = function(p1, p2){
    p1[p2.key] = p2;
    if(p2.childs){ p2.childs = _.reduce(p2.childs,normalize,{}); }
    return p1;
}

_.reduce(data, normalize, {});

Again it’s simple, small and readable code.

This is really elegant library with tons of utility functions as you start exploring it, you will find your project codebase much smaller and clean.

PS: Lo-Dash is a drop and replace library for underscorejs with extra features + performance + bug fixes.



Popular posts from this blog

ERROR: Ignored call to 'alert()'. The document is sandboxed, and the 'allow-modals' keyword is not set.

Recently I found this issue while writing code snippet in "JSFiddle". And after searching, found this was happening because of new feature added in "Chrome 46+". But at the same time Chrome doesn't have support for "allow-modals" property in "sandbox" attribute.

Chromium issue for above behavior:
https://codereview.chromium.org/1126253007

To make it work you have to add "allow-scripts allow-modals" in "sandbox" attribute, and use "window.alert" instead of "alert".



<!-- Sandbox frame will execute javascript and show modal dialogs --> <iframe sandbox="allow-scripts allow-modals" src="iframe.html"> </iframe>


Feature added: Block modal dialog inside a sandboxed iframe.
Link: https://www.chromestatus.com/feature/4747009953103872

Feature working Demo page:
https://googlechrome.github.io/samples/block-modal-dialogs-sandboxed-iframe/index.html



CSS Specificity

Many time different CSS rules overlap on one or more element. And some people always get confuse about, which rule will take higher priority then other and why? CSS Specificity is the answer of all these kind of questions.
As the name suggest, the CSS rule which is more specific to the element will take higher priority then other. Means something like “#some_id{}” will always take higher priority then “*{}” universal selector.  And if duplicate rules are define then the last rule will be applied to the element.

The following list of selectors is by increasing specificity:
Type selector (e.g., div) and pseudo-elements in selector (e.g., :after) Class selectors (e.g., .some_class), attributes selectors (e.g., [type=”radio”]) and pseudo-class selector (e.g., :hover) Id selectors (e.g., #some_id)


ID takes higher priority then Class, Type and Universal selector (Note: Universal selector has no effect on specificity, see below special conditions). 



If duplicate rules are given, then last…

Guava: Some useful IO utilities

Guava IO package provides very useful utility classes for input/ouput stream, byte stream, file handling and many more. Here are few example which show case how these utilities can make your code much cleaner, modular and more readable.Copy “InputStream” to “OutputStream InputStream is = CopyStreams.class.getResourceAsStream("test.txt"); OutputStream os = System.out; ByteStreams.copy(is, os);Changing InputStream to “byte[]” InputStream is = CopyStreams.class.getResourceAsStream("test.txt"); byte[] isBytes = ByteStreams.toByteArray(is); // Now if you want to get base64 encoded string then it will be like this String isBase64Str = new sun.misc.BASE64Encoder().encode(isBytes);Combining two files in one File input1 = new File("c:\\testio\\AWords.txt"); File input2 = new File("c:\\testio\\BWords.txt"); File output = new File("c:\\testio\\ABWords.txt"); …