DEV Community

Arjun Vijay Prakash
Arjun Vijay Prakash

Posted on • Updated on

๐Ÿ”Ÿ Short and Sweet JavaScript One-Liners for Mastery โšก๏ธ๐Ÿš€

๐ŸŒŸ Introduction

When it comes to programming finding solutions often involves approaches, each with its own advantages and disadvantages in terms of length, performance, algorithmic complexity and readability.

This article explores One-Liner Short and Sweet Codes for Mastery in JavaScript showcasing how the language's built-in methods can be used to create elegant and efficient code.


What is a One Liner?

Before we dive into the article, it's important to understand 'what actually qualifies as a one-liner'.

A true one-liner refers to a code solution implemented within a statement in a specific programming language without relying on external tools or utilities.

1. "single statement": A one-liner condenses the solution into a statement ensuring clarity and brevity while still being easy to read.

2. "specific programming language": The term "one-liner" is specific to each programming language since high-level code gets translated into lower-level languages, for execution.

For example, here is another one-liner that also adds the sum of two squares, this time in JavaScript:

function square_number(a) {
    return a * a;
}
Enter fullscreen mode Exit fullscreen mode

Letโ€™s see what it looks like, after compilation to assembly language:

section .text
global square_number

square_number:
    push ebp
    mov ebp, esp
    mov eax, [ebp+8]
    imul eax, eax
    pop ebp
    ret
Enter fullscreen mode Exit fullscreen mode

This assembly program is clearly made up of multiple code statements.

If we were to imagine the machine language program that corresponds to it it would probably be even longer.

Therefore describing the function as a line is only accurate when considering JavaScript specifically.

3. "no third party utilities": A one-liner relies on the built-in features of the language, avoiding any external dependencies and providing a self-contained solution.


List Starts Here:

0๏ธโƒฃ Get the Smallest Element of an Array:

const getSmallest = (arr) => arr.reduce((smallest, num) => Math.min(smallest, num));
Enter fullscreen mode Exit fullscreen mode

1๏ธโƒฃ Get the Largest Element of an Array:

const getLargest = (arr) => arr.reduce((largest, num) => Math.max(largest, num));
Enter fullscreen mode Exit fullscreen mode

2๏ธโƒฃ Shuffle an Array:

const shuffleArray = (arr) => arr.sort(() => Math.random() - 0.5);
Enter fullscreen mode Exit fullscreen mode

3๏ธโƒฃ Group an Array By an Object Property:

const groupBy = (arr, groupFn) => arr.reduce((grouped, obj) => ({ ...grouped, [groupFn(obj)]: [...(grouped[groupFn(obj)] || []), obj] }), {});
Enter fullscreen mode Exit fullscreen mode

4๏ธโƒฃ Reverse a String:

const reverseString = (str) => str.split('').reverse().join('');
Enter fullscreen mode Exit fullscreen mode

5๏ธโƒฃ Generate a Random Hex Color:

const randomHexColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`;
Enter fullscreen mode Exit fullscreen mode

6๏ธโƒฃ Check if Two Arrays Contain the Same Values:

const areEqual = (arr1, arr2) => arr1.sort().join(',') === arr2.sort().join(',');
Enter fullscreen mode Exit fullscreen mode

7๏ธโƒฃ Remove Duplicates from an Array:

const removeDuplicates = (arr) => [...new Set(arr)];
Enter fullscreen mode Exit fullscreen mode

8๏ธโƒฃ Conditional Flow Control with Nested Ternaries:

const getNumWord = (num) => num === 1 ? 'one' : num === 2 ? 'two' : num === 3 ? 'three' : num === 4 ? 'four' : 'unknown';
Enter fullscreen mode Exit fullscreen mode

9๏ธโƒฃ Generate a Random UUID:

const generateRandomUUID = (a) => a ? (a ^ ((Math.random() * 16) >> (a / 4))).toString(16) : ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, generateRandomUUID);
Enter fullscreen mode Exit fullscreen mode

๐Ÿ™Œ Final Thoughts

Weโ€™ve looked at concise JavaScript solutions to common programming problems.

Along the way, we came across situations where a solution required statements transformed into a single line by utilizing various built-in methods and language features.

Although these compressed solutions might sacrifice some performance and readability, using them can demonstrate your expertise and mastery of the programming language.

I hope you liked the article! โค๏ธ

Connect with me: linktree

Happy Coding! ๐Ÿš€
Thanks for 14015! ๐Ÿค—

Top comments (13)

Collapse
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ • Edited

A few issues and points here:

0,1 - Get the Smallest/Largest Element of an Array:

As Tamimul pointed out, this can be much shorter - although shorter again from his version (there's little point wrapping an inbuilt function in another function - this will just add overhead):

Math.min(...arr)
Math.max(...arr)
Enter fullscreen mode Exit fullscreen mode

2 - Shuffle an array

Whilst this works, it's inefficient and will show bias in the shuffling. The Fisher-Yates shuffle is a far better way to do this.

3 - Group an array by an object property

This is built in to JS - Object.groupBy - and enjoys broad support on most modern browsers.

4 - Reverse a string

The version shown will break with strings such as "Hello world ๐Ÿ˜Š". The following version has issues of it's own, but is much better:

const reverseString = str => [...str].reverse().join``
Enter fullscreen mode Exit fullscreen mode

6 - Check if Two Arrays Contain the Same Values

The provided function doesn't work in some situations:

console.log(areEqual(['a', 'b'], ['a,b'])  // true!?!
Enter fullscreen mode Exit fullscreen mode

8 - Conditional Flow Control with Nested Ternaries

Nested ternaries are never a good idea - very poor readability. Also, your code is a really bizarre way of achieving it's goal. Why not just:

const getNumWord = i => ['one', 'two', 'three', 'four'][i-1] || 'unknown'
Enter fullscreen mode Exit fullscreen mode
Collapse
 
lionelrowe profile image
lionel-rowe

Whoah somehow I never clocked that Math.random() - 0.5 would give biased results when passed as a sorting function, though I guess it's obvious with the benefit of hindsight.

Collapse
 
shadow_m2 profile image
Mohammad Bagheri

Although you very much seem like a nerd, but your approach is much nicer and smarter

Collapse
 
lionelrowe profile image
lionel-rowe

Depends how big your arrays are. This will work fine for a 100,000 element array but throw RangeError: Maximum call stack size exceeded for a million elements... whereas the reduce version will work for either.

Collapse
 
greenteaisgreat profile image
Nathan G Bornstein

@lionelrowe this is super interesting! I ended up using console.time() to check and see the execution time for both of these methods and while the Math.max(...arr) version ended up performing faster than the .reduce() method, you're 100% right. For me, it capped out if I put 130,000 elements into my array.

So while the Math.max() way is more efficient, I'm guessing JavaScript's callstack can handle only so many execution contexts.
Image description

Here's the code if anyone wants to copy/paste to fiddle with it:

const testArr = Array(120000).fill(5); 
testArr.push(6); 

const mathMax = (arr) => Math.max(...arr);

const reduceMax = (arr) => arr.reduce((smallest, num) => Math.max(smallest, num));

console.time(mathMax(testArr));
console.timeEnd(mathMax(testArr)); 


console.time(reduceMax(testArr));
console.timeEnd(reduceMax(testArr));
Enter fullscreen mode Exit fullscreen mode
Collapse
 
hari03 profile image
Hariharan • Edited

An excerpt from this great blog

In this case, we create an array for 2.000.000 elements. Array elements are stored in the heap, and therefore the function receives only the reference to the array.

When we use apply or spread operator javascript converts each element from your Iterable object to a separate argument. And therefore you may pass not a reference, but a lot of primitive values.

Collapse
 
valeria-d-23 profile image
Valeria-D-23

Thnx! Very, very helpful!

Collapse
 
arjuncodess profile image
Arjun Vijay Prakash

Thanks! I appreciate that comment.

Collapse
 
_ndeyefatoudiop profile image
Ndeye Fatou Diop

This is super cool ! I didnโ€™t realise you could do this !

Collapse
 
officialphaqwasi profile image
Isaac Klutse

Thanks, this will help me all I need is to practice using them more.

Collapse
 
arjuncodess profile image
Arjun Vijay Prakash

Exactly! Happy Coding!

Collapse
 
mrretro profile image
retro • Edited

I prefer this way

1. const getSmallest = arr => Math.min(...arr)
2. const getLargest = arr => Math.max(...arr)
Enter fullscreen mode Exit fullscreen mode

Some comments may only be visible to logged-in visitors. Sign in to view all comments.