we develop communication with weLaika Advertising

The treats of Lo-Dash

Tags: javascript, lodash, tools, library
Stefano Pau -

Increasingly I hear “Stop using jQuery, it’s too slow and heavy, use Lo-Dash”. Ok, I’ll use Lo-Dash… I’ve taken a small project, with a little bit of Javascript, trying to replace jQuery with Lo-Dash.

WRONG!

It’s indeed hard (but not impossible) to move from one library to another because they are designed to do different things. If we think about jQuery like the DOM manipulator, an handy set of tools for Javascript… then we must think about Lo-Dash like a Javascript language extension.

Lo-Dash is a low-level library, very light (the gzipped core-build is 4KB). It’s designed for general use, not for DOM manipulation, so we don’t have classic jQuery functions as .hide(), .show(), .animate().

But then, what can we write with Lo-Dash? Well, whatever! Lo-Dash has all the little goodies for data manipulation that are in all programming languages​: Strings, Arrays, Objects, Numbers, Dates… not the DOM.

To understand the real Lo-Dash power, you need to see some examples:

1. A simple loop

Javascript

1
2
3
    for(var foobar = 0; foobar < 5; foobar++) {
      //...something
    };

Lo-Dash (without to use a counter variable)

1
2
3
    _.times(5, function(){
      //...something
    });

2. Check variable type

Javascript

1
2
3
    if($.type(myVar) === "string"){
      //...something
    }

Lo-Dash

1
2
3
4
5
    _.isString(value)     //string
    _.isBoolean(value)    //boolean
    _.isEmpty(value)      //empty variable
    _.isElement(value)    // DOM element
    //...

3. Random number

Javascript

1
    Math.random(); // Return a random number between 0 (inclusive) and 1 (exclusive)

Lo-Dash

1
2
    _.random(7); // Return a random number between 0 to 7
    _.random(1, 7, true); // Return a random floating number between 1 and 7

4. Object matching

1
2
3
4
5
6
7
8
  var myObjects = [
    { 'foo': 1, 'bar': 2, 'foobar': 3 },

    { 'fu': 4, 'baz': 5 }
  ];

  _.filter(myObjects, _.matches({ 'foo': 1, 'bar': 2 }));
  // Return [{ 'foo': 1, 'bar': 2, 'foobar': 3 }]

5. Get a value from an object

1
2
3
4
5
6
7
8
9
10
11
    var myObjects = [{
                      "hero": "Ironman",
                      "universe": "Marvel",
                      "abilities": [{"su_strength": false}, {"su_intellect": true}]
                    },
                    {
                      "hero": "Hulk",
                      "universe": "Marvel",
                      "abilities": [{"su_strength": true}, {"su_intellect": false}]
                    }
                   ];

Javascript

1
2
3
    myObjects.map(function(hero){
        return hero.abilities[0].su_strength;
    });

Lo-Dash

1
    _.map(myObjects, 'abilities[0].su_strength');

6. Remove an object property

1
    var myObj = {"name": Gandalf, role: wizard, book: TheLoTR};

Javascript

1
2
3
4
5
6
7
8
    Object.prototype.removeProperty = function(myObj) {
      var that = this;
      myObj.forEach(function(key){
        delete(that[key]);
      });
    };

    myObj.removeProperty([role, book]);

Lo-Dash

1
    myObj = _.omit(myObj, [role, book]);

7. Greater than or qual

1
2
    _.gt(value, other);    // 'value' greater than 'other'
    _.gte(value, other);   // 'value' greater than or equal 'other'

8. Getting a random value (or values) from an array

1
    var myList = ['Cheesecake', 'Muffin', 'Cookies', 'Bread Pudding', 'Ice-Cream'];

Javascript

1
2
3
4
5
6
    function getSweet(aList){
      var randomIndex = Math.floor(Math.random() * (aList.length));
      return aList[randomIndex];
    }

    getSweet(myList);

Lo-Dash

1
2
3
    _.sample(myList); // for example: "Muffin"

    _.sample(myList, 3) // for example: ['Muffin', 'Cookies', 'Cheesecake']

9. Flatten array

1
    var myList = [[1, 2], [4, 6], [8, 10]];

Javascript

1
2
3
4
    var flattenArr = myList.reduce(function(a, b) {
      return a.concat(b);
    }, []);
    // => [1, 2, 4, 6, 8, 10]

Lo-Dash

1
2
3
4
5
6
7
8
9
10
11
12
    _.flatten(myList);
    // => [1, 2, 4, 6, 8, 10]

  // Recursively flattens array:

    newList = [1, [2, [4, [6, 8]], 10]];

    _.flatten(newList);
    // => [1, 2, [4, [6, 8]], 10]

    _flattenDeep(newList);
    // => [1, 2, 4, 6, 8, 10]

10. Inverted object

Create an object composed of the inverted keys and values of object:

1
2
3
4
    var myObject = { 'foo': 'bar', 'fu': 'baz' };

    _.invert(myObject);
    // => { 'bar': 'foo', 'baz': 'fu' }

But then, why use Lo-Dash? Because it allows us to write in a pleasant language and clear logic. It invites us to divide the code into smaller modules.

If you want discover all Lo-dash tricks, consults the documentation: click here!

welaika