MuTasim

One-Liner Brilliance

•⌛ 4 min read•

Hey there! So, I was hanging out in this cool place called LeetCode, where people share these super short and clever code solutions. It's like a secret language of programmers. They even crack jokes about waiting for that "magical one-liner in Python" that blows everyone's mind. Inspired by all the excitement, I thought, "Why not collect some awesome one-liners in JavaScript and share them with you?" So, here we are – let's dive into some neat and tiny pieces of code!

Copy to Clipboard:

./lib/utils.js
const copyToClipboard = (content) => navigator.clipboard.writeText(content);

This function allows you to copy text content to the user's clipboard. It utilizes the Clipboard API, which is now supported in modern browsers.

Use Case: Useful in web applications where you want to provide a quick way for users to copy a piece of text, such as a shareable link or code snippet.

Shuffle Array:

./lib/utils.js
const shuffleArray = (array) => array.sort(() => Math.random() - 0.5);

Shuffles the elements of an array randomly.

Use Case: Useful in scenarios where you want to randomize the order of elements, like creating randomized quizzes or shuffling a playlist.

Get Selected Text:

./lib/utils.js
const getSelectedText = () => window.getSelection().toString();

Retrieves the currently selected text in the browser window.

Use Case: Handy when you need to perform actions on the text selected by the user, such as highlighting, formatting, or triggering specific functionality.

Calculate Average:

./lib/utils.js
const average = (...args) => args.reduce((a, b) => a + b, 0) / args.length;

Computes the average of a list of numbers.

Use Case: Handy for calculating averages in scenarios like computing average scores, grades, or any other numerical data.

Remove Duplicates from Array:

./lib/utils.js
const uniqueArray = (arr) => [...new Set(arr)];

Removes duplicate elements from an array.

Use Case: Useful when you want to ensure uniqueness in a list, like removing duplicate items from a shopping cart or filtering unique tags.

Check if Number is Even:

./lib/utils.js
const isEven = (num) => num % 2 === 0;

Determines if a given number is even.

Use Case: Commonly used in algorithms or logic where you need to check for even or odd numbers, such as alternating row colors in a table.

Reverse a String:

./lib/utils.js
const reverseStr = (str) => str.split('').reverse().join('');

Reverses the characters in a string.

Use Case: Useful when you need to display text in a reversed order, such as in mirror writing or for certain visual effects.

Check if Object is Empty:

./lib/utils.js
const isEmpty = (obj) => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;

Checks if an object is empty.

Use Case: Helpful when you need to validate whether an object has any properties or if it's a newly initialized object.

Capitalize First Letter of String:

./lib/utils.js
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);

Capitalizes the first letter of a string.

Use Case: Commonly used in user interfaces to ensure consistent capitalization, like displaying names or titles.

Generate Random Number within a Range:

./lib/utils.js
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);

Generates a random integer within a specified range.

Use Case: Useful for creating randomization in games, generating unique IDs, or any scenario where randomness is needed.

Scroll to Top of the Page:

./lib/utils.js
const goToTop = () => window.scrollTo(0, 0);

Scrolls the window to the top of the page.

Use Case: Provides a convenient way for users to quickly return to the top of a long webpage without manual scrolling.

Deep Equality Check for Objects or Arrays:

./lib/utils.js
const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);

Checks if two objects or arrays are deeply equal.

Use Case: Helpful when comparing complex data structures, such as configuration objects or state objects, for equality.

Asynchronous Sleep Function:

./lib/utils.js
const sleep = (ms) => new Promise((res) => setTimeout(res, ms));

Delays execution by a specified number of milliseconds.

Use Case: Useful in scenarios where you want to introduce delays in asynchronous code, like animations or simulating loading times.

Insert Element into Array at a Specific Index:

./lib/utils.js
const insert = (arr, index, newItem) => [...arr.slice(0, index), newItem, ...arr.slice(index)];

Inserts a new element into an array at a specific index.

Use Case: Handy when you need to dynamically add or insert items into an array, such as maintaining a sorted list.

Get Type of the Operand's value.

./lib/utils.js
const typeOf = (obj) => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();

Returns the type of an object as a lowercase string.

Use Case: Useful for checking the type of a variable or object, especially when dealing with dynamic data or validating inputs.

Conclusion

Okay, we've just had a blast exploring these bite-sized JavaScript tricks. It's like finding the superhero moves in coding – short, sweet, and super effective! These one-liners show us that coding doesn't always have to be a big puzzle. Sometimes, a tiny line can do the trick. Whether you're a coding pro or just starting out, these little code gems remind us to keep it simple, have fun, and enjoy the beauty of solving problems with just a dash of code magic. So, next time you're coding away, remember – sometimes, less is more. Happy coding adventures!