π 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;
}
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
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));
1οΈβ£ Get the Largest Element of an Array:
const getLargest = (arr) => arr.reduce((largest, num) => Math.max(largest, num));
2οΈβ£ Shuffle an Array:
const shuffleArray = (arr) => arr.sort(() => Math.random() - 0.5);
3οΈβ£ Group an Array By an Object Property:
const groupBy = (arr, groupFn) => arr.reduce((grouped, obj) => ({ ...grouped, [groupFn(obj)]: [...(grouped[groupFn(obj)] || []), obj] }), {});
4οΈβ£ Reverse a String:
const reverseString = (str) => str.split('').reverse().join('');
5οΈβ£ Generate a Random Hex Color:
const randomHexColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`;
6οΈβ£ Check if Two Arrays Contain the Same Values:
const areEqual = (arr1, arr2) => arr1.sort().join(',') === arr2.sort().join(',');
7οΈβ£ Remove Duplicates from an Array:
const removeDuplicates = (arr) => [...new Set(arr)];
8οΈβ£ Conditional Flow Control with Nested Ternaries:
const getNumWord = (num) => num === 1 ? 'one' : num === 2 ? 'two' : num === 3 ? 'three' : num === 4 ? 'four' : 'unknown';
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);
π 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)
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):
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:6 - Check if Two Arrays Contain the Same Values
The provided function doesn't work in some situations:
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:
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.Although you very much seem like a nerd, but your approach is much nicer and smarter
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 thereduce
version will work for either.@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 theMath.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.Here's the code if anyone wants to copy/paste to fiddle with it:
An excerpt from this great blog
Thnx! Very, very helpful!
Thanks! I appreciate that comment.
This is super cool ! I didnβt realise you could do this !
Thanks, this will help me all I need is to practice using them more.
Exactly! Happy Coding!
I prefer this way
Some comments may only be visible to logged-in visitors. Sign in to view all comments.