Voice of a Developer: Save Coding Time With Lodash.js - Part 29

JavaScript is a language of Web. This series of articles will talk about my observations learned during my decade of software development experience with JavaScript.

Before moving further let us look at the previous articles of the JavaScript series:

In this article, we will explore functional programming aspects of JavaScript using a popular library called Loadash.js. It makes JavaScript easier. I use Lodash.js as Swiss Army knife to help me in breaking complex problems into smaller chunks and faster delivery.

Introduction

In day-to-day programming, we work on solving business problems and working with arrays, numbers, objects, strings etc. Loadash.js works great with these:

  • Arrays, objects & strings
  • Testing values
  • Creating composite functions

This library is released with MIT license Download.

Note: I am going to refer 4.12 of this library.

Use cases

I will demonstrate benefit of using Lodash.js to simply common problems. It also enhance developer experience to understand and read code better.

Case 1: Sort an array and get unique values.

Naive method

  1. varary = [2, 4, 2, 5, 4, 7];  
  2. varsortAry = ary.sort(); // [2, 2, 4, 4, 5, 7]  
  3. //run two loops to traverse and match each element, e.g., 2 ===2; 2===4  
  4. for (vari = 0; i < sortAry.length; i++)  
  5. {  
  6.     for (var j = i + 1; j < sortAry.length; j++)  
  7.     {  
  8.         if (sortAry[i] === sortAry[j]) //equal value and same type operator  
  9.         {  
  10.             deletesortAry[i]; //delete element and place 'undefined'  
  11.         }  
  12.     }  
  13. }  
  14. console.log(sortAry); // [undefined × 1, 2, undefined × 1, 4, 5, 7]   
  15. //Now we can remove undefined via using filter function  
  16. varfinalAry = sortAry.filter(function(v)  
  17. {  
  18.     return v != undefined  
  19. })  
  20. console.log(finalAry); // [2, 4, 5, 7]  
Using Loadash.js
  1. varary = [2,4,2,5,4,7];  
  2. varsortAry = ary.sort();  
  3. console.log(_.uniq(sortAry)); // [2, 4, 5, 7]  
  4. Outcome: reduced lot much code by using _.uniq function of Loadash.js  
Case 2: Find a user who based on criteria,

Naive method
  1. var users = [  
  2. {  
  3.     'user''Peter',  
  4.     'age': 36,  
  5.     'isMember'true  
  6. },  
  7. {  
  8.     'user''Chris',  
  9.     'age': 40,  
  10.     'isMember'false  
  11. },  
  12. {  
  13.     'user''Alan',  
  14.     'age': 20,  
  15.     'isMember'true  
  16. }];  
  17. for (vari in users)  
  18. {  
  19.     if (users[i].age > 38)  
  20.     {  
  21.         var user = users[i];  
  22.         break;  
  23.     }  
  24. }  
  25. console.log(user); // Object {user: "Chris", age: 40, active: false}  
Using Loadash.js
  1. var users = [  
  2. {  
  3.     'user''Peter',  
  4.     'age': 36,  
  5.     'isMember'true  
  6. },  
  7. {  
  8.     'user''Chris',  
  9.     'age': 40,  
  10.     'isMember'false  
  11. },  
  12. {  
  13.     'user''Alan',  
  14.     'age': 20,  
  15.     'isMember'true  
  16. }];  
  17. _.find(users, function(o)  
  18. {  
  19.     return o.age > 38;  
  20. }); //// Object {user: "Chris", age: 40, active: false}  
  21. Outcome: reduced lot much code by using _.find  
  22. function of Loadash.js  
Case 3: Loop over collection.

Naive method
  1. for(vari=0;i<users.length;i++){  
  2.    console.log(users[i]);  
  3. }  
Loadash.js
  1. _.times(users.length, function(index){  
  2.    console.log(users[index]);  
  3. });  
  4. Outcome:readability is better with loadash.js  
Case 4: Truncate a string.

I never wrote a code using Naïve method sojumping directly on Lodash.js implementation. This truncate feature is useful when you are dealing with large text of data and want to truncate it.

Loadash.js
  1. varstr="hello world"// below will truncate string accordingly  
  2. _.truncate(str, {'length':7}); // hell…  
Case 5: Shuffle a response.

If you have noticed in online assessments questions are shuffled for each candidate. Lodash.js offers awesome function to help with.
  1. var fruits =['apple','orange','banana','pomegranate'];  
  2. _.shuffle(fruits); // ["orange", "apple", "pomegranate", "banana"]  
Note: The output of _.shuffle could vary because it uses a random permutation Fisher-Yates algorithm.

Case 6: Gets a random selection.
  1. var fruits =['apple','orange','banana','pomegranate'];  
  2. _.sample(fruits); // pomegranate; this output could vary  
Case 7: Map and Reduce functions.

If you remember we explored map and reduce functions in Array methods in article 17.

Loadsh.js provides a convenient approach for both these functions, e.g., get names from users collection and we will use Map function.
  1. _.map(users, 'user'); // ["Peter", "Chris", "Alan"]  
  2. //To change all users name into UpperCase  
  3. _.map(users, function(u){varobj=u.user; return obj.toUpperCase();});  
  4. //["PETER", "CHRIS", "ALAN"]  
Reduce function has similar arguments but it applies reduce approach to get a single value. Example - we want to sum numbergreater than 20.
  1. _.reduce([10, 15, 20, 35, 30, 45], function (accumulator, value) {  
  2. if (value > 20)  
  3. return accumulator + value;   
  4. else  
  5. return 0;  
  6. }); // sum is 110  
Case 8: String template is very common for substitution of data.

Naïve method
  1. var name='Andriana';   
  2. var interest='Programming';   
  3. varstr="Hello, "+name+". Your interest is "+interest;  
  4. console.log(str); // Hello, Andriana. Your interest is Programming  
Loadash.js
  1. vartpl = _.template('Hello, <%= name %>. Your interest is <%= interest%>');  
  2. tpl({  
  3. name: 'Andriana', interest: 'Programming'});  
  4. console.log(tpl);//Hello, Andriana. Your interest is Programming  
Summary

I am an ardent fan of Lodash.js and developers must try to solve problems quickly. Please share your feedback / comments.

 

Up Next
    Ebook Download
    View all
    Learn
    View all