19 JavaScript one-liners that will make you look like a pro

In today's article, I want to share with you 19 one-line JS tricks that can help us improve our work efficiency and at the same time, make us look more professional.

Now, let's enter today's content, spend some time every day, and learn some JS knowledge.

1. Generate a random string

We can use Math.random to generate a random string, which is handy when we need a unique ID.

const randomString = () => Math.random().toString(36).slice(2)randomString() // gi1qtdego0brandomString() // f3qixv40motrandomString() // eeelv1pm3ja

2. Escape HTML special characters

If you know about XSS, one of the solutions is to escape HTML strings.

const escape = (str) => str.replace(/[&<>"']/g, (m) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[m]))escape('<div class="medium">Hi Medium.</div>') // &lt;div class=&quot;medium&quot;&gt;Hi Medium.&lt;/div&gt

3. Capitalize the first character of each word in the string

This method is used to capitalize the first character of each word in the string.

const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase())uppercaseWords('hello world'); // 'Hello World'

Also, here, I would like to thank Christopher Strolia-Davis, who also shared with me his simpler method, the code is as follows:

const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase())

4. Convert the string to camelCase

const toCamelCase = (str) => str.trim().replace(/[-_\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''));toCamelCase('background-color'); // backgroundColortoCamelCase('-webkit-scrollbar-thumb'); // WebkitScrollbarThumbtoCamelCase('_hello_world'); // HelloWorldtoCamelCase('hello_world'); // helloWorld

5. Delete duplicate values ​​in the array

Removing duplicates from an array is very necessary, and using "Set" makes it very easy.

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]

6. Flatten an array

We are often tested in interviews and this can be done in two ways.

const flat = (arr) =>    [].concat.apply(        [],        arr.map((a) => (Array.isArray(a) ? flat(a) : a))    )// Orconst flat = (arr) => arr.reduce((a, b) => (Array.isArray(b) ? [...a, ...flat(b)] : [...a, b]), [])flat(['cat', ['lion', 'tiger']]) // ['cat', 'lion', 'tiger']

7. Remove false values ​​from the array

Using this method you will be able to filter out all spurious values ​​in the 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. Check if a number is even or odd

A super simple task that can be solved by using the modulo operator (%).

const isEven = num => num % 2 === 0isEven(2) // trueisEven(1) // false

9. Get a random integer between two numbers

This method is used to get a random integer between two numbers.

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

10. Get the average value of the parameters

We can use the reduce method to get the average of the parameters we provide in this function.

const average = (...args) => args.reduce((a, b) => a + b) / args.length;average(1, 2, 3, 4, 5);   // 3

11. Truncate the number to a fixed decimal point

Using the Math.pow() method, it is possible to truncate a number to a certain decimal point that we provide in the function.

const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)round(1.005, 2) //1.01round(1.555, 2) //1.56

12. Calculate the difference in days between two dates

Sometimes we need to calculate the number of days between two dates, and one line of code can do it.

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

13. Get the day of the year from the date

If we want to know what day of the year a certain date is, we only need one line of code to do it.

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

14. Generate a random hex color

If you need a random color value, this function will do the trick.

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

15. Convert RGB color to hexadecimal

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

16. Clear all cookies

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

17. Detect dark mode

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches

18. Swap two variables

[foo, bar] = [bar, foo]

19. Pause for a while

const pause = (millis) => new Promise(resolve => setTimeout(resolve, millis))const fn = async () => {  await pause(1000)  console.log('fatfish') // 1s later}fn()

At last

The above are the 19 single-line code knowledge about JS that I shared with you today. I hope it will be helpful to you, and I hope you can learn something new from it.

Tags: Javascript Front-end programming language

Posted by fj1200 on Sat, 17 Dec 2022 21:28:41 +0300