All posts tagged “Javascript”

Underscore.js 101 – _.filter and _.contains

Underscore.js one of the powerful utility JS libraries out there. In this post am goin to explain some of the functions and how they can be mixed and matched to get our required functionality.

_.filter:

_.filter it looks through the list we pass and returns all the values that are truthy as per the iterator.

var odds = _.filter([1,2,3,4,5,6], function(num){ return num % 2 !== 0})
// [1, 3, 5]

returns all the odd number on the list.

Lets take an example you have a list of strings.

var langs = ['Ruby', 'RoR', 'Python', 'Django', 'Java', 'Javascript', 'Node.js'];

You want to extract the items based on the starting letter in a word

_.filter(arr, function(i){var startLetter = i.slice(); return startLetter[0] === 'R'}) // ["Ruby", "RoR"]

for searching between more than one letter you may have to do something like this

_.filter(arr, function(i){var startLetter = i.slice(); return startLetter[0] === 'R' || startLetter[0] === 'P'}) // ["Ruby", "RoR", "Python"]

It will become more complex if we are goin to add more letters to support in this, we can minimize the complexity with one more function Underscore provides us.

_.contains:

_.contains returns true if the passed value is present in array.

_.contains([1, 2, 3], 3); // true

this can be used in our existing filter function to reduce the long list of OR conditions

_.filter(arr, function(i){var startLetter = i.slice(); return _.contains(['R', 'P'],startLetter[0])}) // ["Ruby", "RoR", "Python"]

this is easy to maintain and scalable.

Conversions in Javascript

Using Javascript has an ease, you can achieve the same result by doing it in different ways. Here am going to discuss about the performance implications of the same. Lets start with string to number conversion. The usual way of string to number conversion is done using parseInt. However there are someother ways it can be done as well

var n1 = parseInt("12");
var n2 = Number("12");
var n3 = +"12";
var n4 = ~~(1*"12");

All of the above does the same job and n1==n2==n3==n4. So, of all the ways we have to see which one is the ideal way to do that. This is where performance is a big consideration. In this jsperf test we can see which one performs well. Of four of them the last wicked way performs well in all browsers except chrome and safari webkit browsers(I don’t know why). At the end the best way is to use the parseInt, somebody might prefer using +”Value” for ease of typing. However should know the performance benefits of the other ways. Similarly, string conversion

var date = new Date();
var ds = date.toString();
var dr = date+"";

In this case ds==dr, the way toString works is faster in most cases.

Brain Effing Javascript

Javascript has always been fascinating to me in so many ways, because it packs in so many things for a language that has been developed in 2 weeks (there were improvements after that). Look at this

JavaScript

  var truthy = true;
  if(truthy === !+[]){
    console.log("It's Truthy");
  }

Put this in the console and it prints the value. It’s ’cause

!+[] === true

javascript interprets the combination of these special characters into actual values. Similary

!!+[] === false

And also you can get numbers like this

+[] === 0
+!+[] === 1
!+[]+!+[] === 2
....

We can create all the numbers by adding !+[] like that. Using this, if you want your fellow programmer to go mad you can do something like this

JavaScript

 
var l = +!+[];
for (var i = +[]; i <= !+[] + !+[]; i++) {
    l = l + (+!+[]);
    console.log(l);
}

with these special character combinations, a complete program can be written in javascript.

Further reading:

http://patriciopalladino.com/blog/2012/08/09/non-alphanumeric-javascript.html

jQuery AnimationEnd Plugin – Provides a callback when a CSS3 animation is complete on an element

There will be some instances where in we have to do something after a CSS3 animation is complete on a particular element. This plugin will come in handy on those cases.

Plugin attaches to the animationEnd and transitionEnd events, fired when an animation is complete and provides a callback.

Javascript

$.fn.animationEnd = function(callback) {
        return this.each(function(){
          var $this = $(this);
              $this.bind("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd transitionend webkitTransitionEAnind oTransitionEnd MSTransitionEnd", function() {
                if (typeof callback == 'function') {
                    callback.call(this); // brings the scope to the callback
                };
            });
        })
        
    };

In the demo, I have a case where we want to remove the class which provides the css3 styles, at the animation end so that we can add the class again to trigger the animation.

Demo

Suggestions are welcome to improve this plugin.Please, point out mistakes as well.