JS one-liners š»
Mar 1, 2019
I am a huge fan of Arrow functions. They have changed the way we write code. They have cured the cloudy behaviour of this. They let us define functions without function keyword š
. This article collates one-linersāāāwritten using arrow functionsāāāwith their explanations.
Remove Duplicates from Array
Interviewer often asks candidates to write a function which removes duplicates from an array. This can be done in many ways. Weāll discuss only those which are relevant to this post.
const removeDuplicates = arr => arr.filter((item, index) => index === arr.indexOf(item));As you can see we are using filter and indexOf methods of the Array class. We get the index of the item using indexOf method and compare it with the current index. If both are equal then the item is unique else its repeated.
To remove duplicates we can also use Set data structures. We create a set from the array and then convert set back to the array using spread operator or Array.from method.
// Using spread operator.const removeDuplicates1 = array => [...new Set(array)];// Using Array.from methodconst removeDuplicates2 = array => Array.from(new Set(array));Flatten Array
Flattening an array means converting a multi-dimension array to one-dimensional array. eg.
// 2-dimensional array.[[1, 2, 3], [4, 5, 6]]// After flattening[1, 2, 3, 4, 5, 6]// Multi-dimentional array[1, [2, [3, 4, [5], 6], 7], 8], 9]// After flattening[1, 2, 3, 4, 5, 6, 7, 8, 9]We can use Array.concat method with spread operator to flatten an array.
// Flattens an array(doesn't flatten deeply).const flatten = array => [].concat(...array);This approach flattens an array at only one level. Below function fully flattens an array.
const flattenDeep = arr => arr.reduce( (fArr, item) => fArr.concat(Array.isArray(item) ? flatten(item) : item), [] );Merge Arrays
To merge arrays we can use Array.concat method with spread operator.
// Merge arraysconst merge = (...arrays) => [].concat(...arrays);Pipe (Function Composition)
We often need to āpipeā the output of one function as an input to another function. Hereās a simple implementation of the pipe function using Function Composition.
// Pipe fnconst pipe = (...fns) => arg => fns.reduce((v, fn) => fn(v), arg);
// Exampleconst addTwo = x => x + 2;const double = x => x * 2;const square = x => x * x;const fn = pipe(addTwo, double, square);console.log(fn(1)); // square(double(addTwo(1))) -> 36Compose(Pipe reverse)
Just like the pipe function, compose also supplies the output of one function as an input to another but it does it in reverse order.
const compose = (...fns) => fns.reduce((a, b) => (...args) => a(b(...args)));
// Exampleconst addTwo = x => x + 2;const double = x => x * 2;const square = x => x * x;const fn = compose(addTwo, double, square);console.log(fn(1)); // -> 4 addTwo(double(square(1)))Range Function
You might have used range function of Lodash. Hereās a one-liner implementation of range using Array.from method. It generate range from start to end (exclusive). It also takes an optional step parameter.
// Generates range [start, end) with stepconst range = (start, end, step = 1) => Array.from( { length: Math.ceil((end - start) / step) }, (_, i) => start + i * step );Color Function
Generates a random hex color code.
// Generates random hex color code.const color = () => '#' + Math.floor(Math.random() * 0xffffff) .toString(16) .padEnd(6, '0');Conclusion
Before we conclude thereās one thing that should be kept it mind while writing one-liners. One-liners do more things with less code, which tempts people to write more one-liners. But sometimes, writing less code makes it less readable and hard to debug. So if you are writing code which you feel should or can be broken into multiple lines. Just go ahead and do it. Youāll thank yourself later š.
One liners are great but one should always make sure that they donāt take a toll on the legibility of code.
Hereās the gist of all the one-liners used in this post. If thereās any one-liner which should be added to the list, please feel free to share. Iāll add it. Thanks for Reading šš».
Hi, I am Hitesh.
I build things and ship some of them.