7 Killer JS Lines of Code

JavaScript is the most critical pillar of web development.

This post contains code snippets hand-picked by sterile gloves and placed on a satin pillow.
A team of 50 people reviewed the code and made sure it was in a highly polished state before release. Our article publishing expert from Switzerland lit a candle and the crowd booed as he entered the code into the best gold-encrusted keyboard money can buy.
We all had a wonderful celebration with the whole party marching down the street to the cafe and the whole town of Kolkata waving "Good luck!" as the article was posted online.

Happy reading!

array out of order

When working with algorithms that require some level of randomization, you will often find that shuffling arrays is a fairly necessary skill. The following snippet shuffles an array in-place with O(n log n) complexity.

const shuffleArray = (arr) => arr.sort(() => Math.random() - 0.5) 。
// 测试
const arr = \[1, 2, 3, 4, 5, 6, 7, 8, 9, 10\];
console.log(shuffleArray(arr))。

copy to clipboard

In web applications, copy-to-clipboard is rapidly gaining popularity due to its convenience to the user.

const copyToClipboard = (text) =>
  navigator.clipboard?.writeText && navigator.clipboard.writeText(text)。
// 测试
copyToClipboard("Hello World!")。

Note: According to caniuse, this method works for 93.08% of global users. So it must be checked whether the user's browser supports the API. To support all users, you can use one input and copy its content.

Array deduplication

Each language has its own implementation of a hash list, in JavaScript it's called a Set. You can easily get unique elements from an array using the Set data structure.

const getUnique = (arr) => \[...new Set(arr)\]。
// 测试
const arr = \[1, 1, 2, 3, 3, 4, 4, 5, 5\];
console.log(getUnique(arr))。

Detect dark mode

With the popularity of dark mode, it is ideal to switch your app to dark mode if users have dark mode enabled in their device. Fortunately, media queries can be leveraged to make this task easy.

const isDarkMode = () =>
  window.matchMedia &&
  window.matchMedia("(prefers-color-scheme: dark)").matches。
// 测试
console.log(isDarkMode())。

According to caniuse, matchMedia has a 97.19% approval rating.

scroll to top

Beginners often find themselves struggling with scrolling elements correctly. The easiest way to scroll an element is to use the scrollIntoView method. Add behavior. "smooth" for smooth scrolling animations.

const scrollToTop = (element) =>
  element.scrollIntoView({ behavior: "smooth", block: "start" })。

scroll to bottom

Just like scrollToTop method, scrollToBottom method can also be easily implemented with scrollIntoView method, just switch the block value to end

const scrollToBottom = (element) =>
  element.scrollIntoView({ behavior: "smooth", block: "end" })。

Generate random colors

Does your application rely on random color generation? Look no further, the following code snippet will do what you want

const generateRandomHexColor = () =>
  \`#${Math.floor(Math.random() \* 0xffffff) .toString(16)}\`;

From: https://segmentfault.com/a/1190000041415254

Original: https://tapajyoti-bose.medium.com/7-killer-one-liners-in-javascript-33db6798f5bf

Guess you like

Origin blog.csdn.net/qq_36538012/article/details/123267453