Nope, You don’t need lodash for that


I recently had to reduce the size of an Angular Web app for performance reasons. A quick run through the webpack bundle analyzer identified MomentJS and Lodash as the main culprits. Consequently, I had to eliminate both libraries and implement replacements in pure ES6.

The upside however is that it was easier than I thought! Thus, here are a couple of one-liners that might come handy or inspire you to new combinations. 

1. Make an array unique

let uniq = (arr) => [... new Set(arr)];

This trick leverages the new Set object in conjunction with the spread syntax for iterables.

2. Create a range of values

let range = (lower, upper)
   => Array.from(new Array(upper - lower + 1),
                 (v, i) => i + lower);

This approach bundles two steps:

  • First, use new Array(length) to create an array filled with undefined values
  • Then use the mapping function of Array.from to create the stepping function  that assigns the expected values from the starting offset.

3. Maximum and minimum values in arrays

Before it would be Math.max.apply(Math, arr) or _.max (if using lodash) however with the spread syntax, it becomes quite easy

Math.max(...arr)
Math.min(...arr)

// versus old style in ES5
Math.max.apply(Math, arr);

4. Filter falsy values out of an array

let nonFalsy = arr => arr.filter(Boolean);

5.  Head and Rest

The spread operator offers an excellent way to get the head and rest of an array. Reminds me of car and cdr from Scheme, you can get a quick dirty version as shown below.

let [head, ...rest] = arr;

let car = arr => {
    const [head, ...rest] = arr;
    return head;
};

let cdr = arr => {
    const [head, ...rest] = arr;
    return rest;
};

6. Array.fill

Fills an array with values.

let fillWithValues = (val, len)
    => new Array(len).fill(val);

And that’s about it; what other one-liners do you like? Share in the comments below!

Leave a Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.