Wednesday, June 8, 2016

10 Lodash Features You Can Replace with ES6

[author_more]

This article was peer reviewed by Mark Brown. Thanks to all of SitePoint's peer reviewers for making SitePoint content the best it can be!

Lodash is the most depended on npm package right now, but if you're using ES6, you might not actually need it. In this article, we're going to look at using native collection methods with arrow functions and other new ES6 features to help us cut corners around many popular use cases.

1. Map, Filter, Reduce

These collection methods make transforming data a breeze and with near universal support, we can pair them with arrow functions to help us write terse alternatives to the implementations offered by Lodash.

_.map([1, 2, 3], function(n) { return n * 3; });
// [3, 6, 9]
_.reduce([1, 2, 3], function(total, n) { return total + n; }, 0);
// 6
_.filter([1, 2, 3], function(n) { return n <= 2; });
// [1, 2]

// becomes

[1, 2, 3].map(n => n * 3);
[1, 2, 3].reduce((total, n) => total + n);
[1, 2, 3].filter(n => n <= 2);

It doesn't stop here either, if we're using an ES6 polyfill, we can also use find, some, every and reduceRight too.

2. Head & Tail

Destructuring syntax allows us to get the head and tail of a list without utility functions.

_.head([1, 2, 3]);
// 1
_.tail([1, 2, 3]);
// [2, 3]

// becomes

const [head, ...tail] = [1, 2, 3];

It's also possible to get the initial elements and the last element in a similar way.

_.initial([1, 2, 3]);
// -> [1, 2]
_.last([1, 2, 3]);
// 3

// becomes

const [last, ...initial] = [1, 2, 3].reverse();

If you find it annoying that reverse mutates the data structure, then you can use the spread operator to clone the array before calling reverse.

const xs = [1, 2, 3];
const [last, ...initial] = [...xs].reverse();

3. Rest & Spread

The rest and spread functions allow us to define and invoke functions that accept a variable number of arguments. ES6 introduced dedicated syntaxes for both of these operations.

var say = _.rest(function(what, names) {
  var last = _.last(names);
  var initial = _.initial(names);
  var finalSeparator = (_.size(names) > 1 ? ', & ' : '');
  return what + ' ' + initial.join(', ') +
    finalSeparator + _.last(names);
});

say('hello', 'fred', 'barney', 'pebbles');
// "hello fred, barney, & pebbles"

// becomes

const say = (what, ...names) => {
  const [last, ...initial] = names.reverse();
  const finalSeparator = (names.length > 1 ? ', &' : '');
  return `${what} ${initial.join(', ')} ${finalSeparator} ${last}`;
};

say('hello', 'fred', 'barney', 'pebbles');
// "hello fred, barney, & pebbles"

Continue reading %10 Lodash Features You Can Replace with ES6%


by Dan Prince via SitePoint

No comments:

Post a Comment