25 Killer One-Liners in JavaScript
author

Jon Snow

20 April 2023

25 Killer One-Liners in JavaScript


1. Generate a random string

const randomString = () => Math.random().toString(36).slice(2)

randomString() // gi1qtdego0b
randomString() // f3qixv40mot
randomString() // eeelv1pm3ja

2. Detect Dark Mode

const prefersDarkMode = window.matchMedia( "(prefers-color-scheme: dark)").matches; 
console.log(prefersDarkMode);

3. Extract Domain name from an email

const email = "selemondev19@gmail.com";
const extractDomain = (email) => email.split('@')[1]; 
console.log(extractDomain(email)); // "gmail.com"


4. Remove duplicate values in an array

const removeDuplicates = (arr) => [...new Set(arr)]

console.log(removeDuplicates([1, 2, 2, 3, 3, 4, 4, 5, 5, 6])) // [1, 2, 3, 4, 5, 6]

5. Redirecting user

const redirect = (url) =>  window.location.href = url;
redirect("https://www.example.com");

6. Flatten an array

const flat = (arr) => arr.flat();
flat(['cat', ['lion', 'tiger']]); // ['cat', 'lion', 'tiger']


7. Remove falsy values from array

const removeFalsy = (arr) => arr.filter(Boolean)

removeFalsy([0, 'a string', '', NaN, true, 5, undefined, 'another string', false]) // ['a string', true, 5, 'another string']

8. Get a random integer between two numbers

const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)

random(1, 50) // 25
random(1, 50) // 34

9. Truncate a number to a fixed decimal point

const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)

round(1.005, 2) //1.01
round(1.555, 2) //1.56

10 Calculate the number of different days between two dates

const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));

diffDays(new Date("2021-11-3"), new Date("2022-2-1"))  // 90

11. Get the day of the year from a date

const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24))

dayOfYear(new Date()) // 74


12. Generate a random hex colour

const randomColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`

randomColor() // #9dae4f
randomColor() // #6ef10e

13. Convert RGB colour to hex

const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)

rgbToHex(255, 255, 255)  // '#ffffff'

14. Clear all cookies

const clearCookies = () => document.cookie.split(';').forEach((c) => (document.cookie = c.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`)))

15. Check if a string is a palindrome

const isPalindrome = str => str === str.split('').reverse().join('');

console.log(isPalindrome('racecar')); // true
console.log(isPalindrome('hello')); // false

16. Get the first n elements of an array

const take = (arr, n) => arr.slice(0, n);

console.log(take([1, 2, 3, 4, 5], 3)); // [1, 2, 3]


17. Get the last n elements of an array

const takeRight = (arr, n) => arr.slice(-n);

console.log(takeRight([1, 2, 3, 4, 5], 3)); // [3, 4, 5]

18. Check if an object is empty

const isEmpty = obj => Object.keys(obj).length === 0;

console.log(isEmpty({})); // true
console.log(isEmpty({ name: 'John' })); // false


19. Shuffle an array

const shuffle = arr => arr.sort(() => Math.random() - 0.5);

console.log(shuffle([1, 2, 3, 4, 5])); // [2, 5, 1, 4, 3] (output will vary)

20. Get the current time in hh:mm:ss format

const getTime = () => new Date().toLocaleTimeString();

console.log(getTime()); // "9:30:42 PM" (output will vary based on current time)

21. Check if a string contains a substring

const contains = (str, substr) => str.includes(substr);

console.log(contains('hello world', 'world')); // true
console.log(contains('hello', 'world')); // false

22. Remove all vowels from a string

const removeVowels = (str) => str.replace(/[aeiou]/gi, '')

removeVowels('hello world') // 'hll wrld'


23. Convert a string to title case

const toTitleCase = (str) => str.replace(/\w\S*/g, (txt) => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase())

toTitleCase('the quick brown fox jumps over the lazy dog') // 'The Quick Brown Fox Jumps Over The Lazy Dog'

24. Get the current time in a specific timezone

const currentTimeInTimezone = (timezone) => new Date().toLocaleTimeString('en-US', {timeZone: timezone})

currentTimeInTimezone('Europe/London') // "8:28:00 AM" (for the current time in London)

25. Convert a string to kebab-case

const toKebabCase = (str) => str.toLowerCase().replace(/\s+/g, '-')

toKebabCase('Hello World') // 'hello-world'
toKebabCase('This is a Test') // 'this-is-a-test'

Thank You ❤❤


Share:  
https://www.democoding.in/blog...

Related Post

programming meme
Code Snippet

Codepen Ideas