未加星标

Functional JavaScript part 4: lodash

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二04 | 时间 2017 | 作者 红领巾 ] 0人收藏点击收藏

With this post we will finalize the part of this course devoted to array operations Vanilla javascript provides us with some higher order functions (such as forEach , filter , map and reduce ). However, there are actually many more such functions in the world of functional programming. Lodash is a library which extends your arsenal of higher order functions. Let’s have a look at how to use it in practice.

Exploring lodash

The best place to explore functions available in lodash is the documentation . You will notice that there are many expandable sections on the left hand side. For now let’s focus on Array and Collection .


Functional JavaScript part 4: lodash
Using lodash

Lodash methods are not available directly on the array object. It could be achieved with JavaScript’s prototypical inheritance but it’s not considered a good practice to extend native prototypes (actually, it’s disputable but lodash creators decided not to do this ).

Therefore, in order to use a lodash method we need to call it on the global _ object. You may note that this will make chaining less convenient but there is a cure for that we’ll look at it at the end of this post.

Let’s see a usage example:

var numbers = [1, 2, 3, 4, 5]; console.log(_.drop(numbers, 2));

Drop function takes an array and a number of elements to drop. It returns a new array that doesn’t contain the first n elements.

As a side note, it’s actually not a higher order function since it doesn’t take a function as argument.

Validation with every and any

Let’s consider the following requirement: we’re running a bike parts shop. W e are given a list of items in the customer’s shopping cart. We should validate that he is ordering at least one piece of each item.

All of the imperative approaches to this problem I can think of are a little clumsy. We could either:

count the items with quantity equal to 0 and check if the number is equal to zero have a separate function in which we iterate over the items and return early if we encounter one with quantity equal to 0

Let’s see how we can use lodash in order to solve it in an elegant way:

var basket = [ { name: "Cable Lock", quantity: 2 }, { name: "U Lock", quantity: 5 }, { name: "Tail Light", quantity: 0 } ]; if (!_.every(basket, item => item.quantity > 0)) { alert("You must order at least 1 piece of each item"); }

Function every takes a function that evaluates to true or false, applies this function on all elements and returns true only if the function was true on all elements. In other words, it checks whether every element satisfies given condition.

In fact, what we want to do is to check if it is not true that every element satisfies given condition. Therefore, we can check whether there are some elements that don’t satisfy our condition (the condition being quantity greater than 0).

if (_.some(basket, item => item.quantity == 0)) { alert("You must order at least 1 piece of each item"); }

Which results in even cleaner and more readable code. Doesn’t it feel a bit like writing in natural language?

Grouping with groupBy

Here comes another requirement! We’ve received a list of available products from some backend API. It would be nice to display them in separate boxes based on the category they belong to.

The imperative solution is particularly verbose:

var products = [ { name: "Cable Lock", category: "Safety" }, { name: "U Lock", category: "Safety" }, { name: "Tail Light", category: "Basics" } ]; var productsByCategory = {}; for (var i = 0; i < products.length; i++) { var category = products[i].category; if (!productsByCategory.hasOwnProperty(category)) { productsByCategory[category] = []; } productsByCategory[category].push(products[i]); } console.log(productsByCategory);

We create an empty object ( productsByCategory ) in which we will store the results keys will represent categories and for each key we will store an array of products.

Next, we iterate over the products. For each product we check whether we already have an entry in the productsByCategory object. If we don’t then we need to create it and initialize it with an empty array. Finally, we add the product to the list under its category.

The result will look like this:

{Safety: Array(2), Basics: Array(1)}

I bet you’re expecting the functional version to be much simpler and it is. Yes, it’s a single line again.

var productsByCategory = _.groupBy(products, product => product.category);

The function takes an array and a function which determines how to group the elements of that array. The grouping functions is evaluated for each element. Those elements for which the same value is returned are packed into separate groups. Finally, an object is returned with keys equal to unique values returned by the grouping function applied on all of the elements.


Functional JavaScript part 4: lodash

The grouping function does not have to be a simple property selector we can put any sort of expression in it. For example, it’s trivial to split products into groups based on the length of their names:

var productsByNameLength = _.groupBy(products, product => { if (product.name.length < 10) return "short"; if (product.name.length >= 10 && product.name.length < 20) return "medium"; return "long"; }); Sorting with orderBy

The last useful function I’d like you to look at is orderBy . As the name suggests, it let’s you sort an array. Vanilla JavaScript already has a sort function built-in. orderBy is more convenient to use and more functional in its nature.

Firstly, while sort orders the array in-place, orderBy doesn’t modify the existing array but returns a fresh copy.

Secondly, sort takes a comparator function a function which takes two elements and compares them. orderBy is more consistent with other functions we’ve looked at it takes a function which selects the value to use for ordering.

Let’s say that we would like to have a fresh copy of our products array sorted by quantity. Without lodash we would need to do the following:

var sortedBasket = basket.slice(0); sortedBasket.sort((a, b) => a.quantity - b.quantity); console.log(sortedBasket); In the first line we use slice in order to clone the array. slice is for cutting out slices of an array. We can tell it to cut out the whole array as a slice which will give as a copy

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

主题: JavaScriptJava
分页:12
转载请注明
本文标题:Functional JavaScript part 4: lodash
本站链接:http://www.codesec.net/view/561327.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(9)