Seven killer JS lines of code

Array out of order When using algorithms that require some degree of randomization, you’ll often find shuffling arrays to be a fairly necessary skill.The following fragment shuffles an array in place with order n log n complexity.Const shuffleArray = (arr) => arr.sort(() => math.random () -0.5)./ / testing const arr = \ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10 \];The console. The log (shuffleArray (arr)).Copy to Clipboard In Web applications, copy to clipboard is rapidly gaining popularity because of its convenience to users.const copyToClipboard = (text) => navigator.clipboard?. WriteText && navigator. Clipboard. WriteText (text).// Test copyToClipboard(“Hello World!).Note: According to Caniuse, this method works for 93.08% of global users.So you must check whether the user’s browser supports the API.To support all users, you can take one input and copy its contents.Each language has its own implementation of a hash list, which in JavaScript is called a Set.You can easily get unique elements from an array using the Set data structure.Const getUnique = (arr) => […new Set(arr)\]// Test const arr = \[1, 1, 2, 3, 3, 4, 4, 5, 5];The console. The log (getUnique (arr)).Detect Dark Mode With the popularity of dark mode, it is ideal to switch your application to dark mode if users have dark mode enabled on their devices.Fortunately, you can use media queries to make this task easier.Matches) const isDarkMode = () => window.matchmedia && window.matchmedia (“((color-scheme: dark)”).matches// Test console.log(isDarkMode()).MatchMedia has 97.19 percent support, according to Caniuse.Scrolling to the Top Beginners often find themselves having trouble scrolling through elements correctly.The easiest way to scroll elements is to use the scrollIntoView method.Add behavior.”Smooth” for smooth scrolling animations.Const scrollToTop = (element) => element.scrollIntoView({behavior: “smooth”, block: “start”}).Just like scrollToTop, scrollToBottom can be easily implemented using scrollIntoView,Const scrollToBottom = (element) => element.scrollIntoView({behavior: “smooth”, block: “end”}).Generate random colors Does your application rely on random color generation?Const generateRandomHexColor = () => \ ‘#${math.floor (math.random () \* 0xffFFFF).toString(16)}\’;

Leave a Reply

Your email address will not be published.