π Short and Sweet JavaScript One-Liners for Mastery β‘οΈπ
Arjun Vijay Prakash
Posted on February 6, 2024
π 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! π€
Posted on February 6, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.