Skip to content

Instantly share code, notes, and snippets.

@eduardosilva
Created May 11, 2022 12:43
Show Gist options
  • Save eduardosilva/02856a8197adfaa096ccc2762b46a54b to your computer and use it in GitHub Desktop.
Save eduardosilva/02856a8197adfaa096ccc2762b46a54b to your computer and use it in GitHub Desktop.
Killers One-Liners in JavaScript

Killer one-liners Javascript

Shuffle Array

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

const copyToClipboard = (text) =>
  navigator.clipboard?.writeText && navigator.clipboard.writeText(text);
// Testing
copyToClipboard("Hello World!");

Scroll To Top

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

Scroll To Bottom

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

Sleep Function

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

Go Back to the Previous Page

const navigateBack = () => history.back();
// Or
const navigateBack = () => history.go(-1);

Compare Objects

const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
// examples
isEqual({ a: 1, b: 2 }, { a: 1, b: 2 }); // true
isEqual({ a: 1, b: 2 }, { a: 1, b: 3 }); // false
// works with arrays too
isEqual([1, 2, 3], [1, 2, 3]); // true
isEqual([1, 2, 3], [1, 2, 4]); // false

Generate Random id

const uuid = () =>
  ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) =>
    (
      c ^
      (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
    ).toString(16)
  );

Get Selected Text

const getSelectedText = () => window.getSelection().toString();

Check if an Element is Focused

const hasFocus = (element) => element === document.activeElement;

Count by the Properties of an Array of Objects

const countElementsByProp = (arr, prop) =>
  arr.reduce(
    (prev, curr) => ((prev[curr[prop]] = ++prev[curr[prop]] || 1), prev),
    {}
  );
// example
countElementsByProp(
  [
    { manufacturer: "audi", model: "q8", year: "2019" },
    { manufacturer: "audi", model: "rs7", year: "2020" },
    { manufacturer: "ford", model: "mustang", year: "2019" },
    { manufacturer: "ford", model: "explorer", year: "2020" },
    { manufacturer: "bmw", model: "x7", year: "2020" },
  ],
  "manufacturer"
); // { 'audi': 2, 'ford': 2, 'bmw': 1 }

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment