3

🔟 Short and Sweet JavaScript One-Liners for Mastery ⚡️🚀

 7 months ago
source link: https://dev.to/arjuncodess/short-and-sweet-javascript-one-liners-for-mastery-m74
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

🌟 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! 🤗


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK