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
- varary = [2, 4, 2, 5, 4, 7];
- varsortAry = ary.sort();
-
- for (vari = 0; i < sortAry.length; i++)
- {
- for (var j = i + 1; j < sortAry.length; j++)
- {
- if (sortAry[i] === sortAry[j])
- {
- deletesortAry[i];
- }
- }
- }
- console.log(sortAry);
-
- varfinalAry = sortAry.filter(function(v)
- {
- return v != undefined
- })
- console.log(finalAry);
Using Loadash.js
- varary = [2,4,2,5,4,7];
- varsortAry = ary.sort();
- console.log(_.uniq(sortAry));
- Outcome: reduced lot much code by using _.uniq function of Loadash.js
Case 2: Find a user who based on criteria,
Naive method - var users = [
- {
- 'user': 'Peter',
- 'age': 36,
- 'isMember': true
- },
- {
- 'user': 'Chris',
- 'age': 40,
- 'isMember': false
- },
- {
- 'user': 'Alan',
- 'age': 20,
- 'isMember': true
- }];
- for (vari in users)
- {
- if (users[i].age > 38)
- {
- var user = users[i];
- break;
- }
- }
- console.log(user);
Using Loadash.js - var users = [
- {
- 'user': 'Peter',
- 'age': 36,
- 'isMember': true
- },
- {
- 'user': 'Chris',
- 'age': 40,
- 'isMember': false
- },
- {
- 'user': 'Alan',
- 'age': 20,
- 'isMember': true
- }];
- _.find(users, function(o)
- {
- return o.age > 38;
- });
- Outcome: reduced lot much code by using _.find
- function of Loadash.js
Case 3: Loop over collection.
Naive method - for(vari=0;i<users.length;i++){
- console.log(users[i]);
- }
Loadash.js - _.times(users.length, function(index){
- console.log(users[index]);
- });
- 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 - varstr="hello world";
- _.truncate(str, {'length':7});
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.
- var fruits =['apple','orange','banana','pomegranate'];
- _.shuffle(fruits);
Note: The output of _.shuffle could vary because it uses a random permutation Fisher-Yates
algorithm.
Case 6: Gets a random selection.
- var fruits =['apple','orange','banana','pomegranate'];
- _.sample(fruits);
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.
- _.map(users, 'user');
-
- _.map(users, function(u){varobj=u.user; return obj.toUpperCase();});
-
Reduce function has similar arguments but it applies reduce approach to get a single value. Example - we want to sum numbergreater than 20.
- _.reduce([10, 15, 20, 35, 30, 45], function (accumulator, value) {
- if (value > 20)
- return accumulator + value;
- else
- return 0;
- });
Case 8: String template is very common for substitution of data.
Naïve method - var name='Andriana';
- var interest='Programming';
- varstr="Hello, "+name+". Your interest is "+interest;
- console.log(str);
Loadash.js - vartpl = _.template('Hello, <%= name %>. Your interest is <%= interest%>');
- tpl({
- name: 'Andriana', interest: 'Programming'});
- console.log(tpl);
Summary
I am an ardent fan of Lodash.js and developers must try to solve problems quickly. Please share your feedback / comments.