Wednesday, February 16, 2022

Javascript one liners

 


Shuffle Array

While using algorithms that require some degree of randomization, you will often find shuffling arrays quite a 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);// Testing
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(shuffleArray(arr));

Copy to Clipboard

In web apps, copy to clipboard is rapidly rising in popularity due to its convenience for the user.
const copyToClipboard = (text) =>
navigator.clipboard?.writeText && navigator.clipboard.writeText(text);
// Testing
copyToClipboard("Hello World!");







No comments: