Skip to content

Instantly share code, notes, and snippets.

@mheob
Last active September 1, 2022 13:50
Show Gist options
  • Save mheob/40a13f17654eff6c68302286ec483371 to your computer and use it in GitHub Desktop.
Save mheob/40a13f17654eff6c68302286ec483371 to your computer and use it in GitHub Desktop.
JS - Helpful Snippets
// Detect if dark mode
const isDarkMode = () => globalThis.matchMedia?.("(prefers-color-scheme:dark)").matches ?? false;
isDarkMode();
// ---------------------------------------------------------------
// Copy to clipboard
const copyToClipboard = (text) => navigator?.clipboard?.writeText(text) ?? false;
copyToClipboard("Hello World!");
// ---------------------------------------------------------------
// Make items in an array unique
const uniqueArray = (array) => [...new Set(array)];
uniqueArray([1, 2, 3, 4, 5, 1, 2, 3, 4, 5]); // [1, 2, 3, 4, 5]
// ---------------------------------------------------------------
// Get random number
const getRandomNumber = (min, max) => ~~(Math.random() * (max - min + 1)) + min;
getRandomNumber(1, 10); // Random number between 1 and 10
// ---------------------------------------------------------------
// Get random hex color
const getRandomHexColor = () => "#" + ((Math.random() * 0xffffff) << 0).toString(16);
getRandomHexColor(); // Random hex color
// ---------------------------------------------------------------
// Shuffle array
const shuffleArray = (array) => array.sort(() => Math.random() - 0.5);
shuffleArray([1, 2, 3, 4, 5]); // Randomly shuffled array
// ---------------------------------------------------------------
// Loop a function x times
const loop = (x, fn) => [...Array(x)].forEach(fn);
loop(10, () => console.log("Hello World!"));
// ---------------------------------------------------------------
// Get random element from array
const getRandomElement = (array) => array[~~(Math.random() * array.length)];
getRandomElement([1, 2, 3, 4, 5]); // Random element from array
// ---------------------------------------------------------------
// Get random string
const getRandomString = (length) =>
[...Array(length)]
.map(() => String.fromCharCode(~~(Math.random() * 26) + 97))
.join("");
getRandomString(10); // Random string with 10 characters
// ---------------------------------------------------------------
// Get random boolean
const getRandomBoolean = () => Math.random() >= 0.5;
getRandomBoolean(); // Random boolean
// ---------------------------------------------------------------
// Get cookie
const getCookie = (name) => ("; " + document.cookie).split(`; ${name}=`).pop().split(";")[0];
getCookie("name"); // Value of cookie "name"
// ---------------------------------------------------------------
// Clear all cookies
const clearCookies = () =>
document.cookie
.split(";")
.forEach(
(c) =>
(document.cookie = c
.replace(/^ +/, "")
.replace(/=.*/, "=;expires=Thu, 01 Jan 1970 00:00:00 UTC"))
);
clearCookies(); // Clear all cookies
// ---------------------------------------------------------------
// Scroll to top of element
const scrollToTop = (element) => element.scrollIntoView({ behavior: "smooth" });
scrollToTop(document.querySelector("#element"));
// ---------------------------------------------------------------
// Get average of numbers
const avg = (...numbers) => numbers.reduce((a, b) => a + b, 0) / numbers.length;
avg(1, 2, 3, 4, 5); // 3
// ---------------------------------------------------------------
// Validate email
const validateEmail = (email) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
validateEmail("obama@gmail.com"); // true
// ---------------------------------------------------------------
// Validate object
const validateObject = (object, rules) => Object.keys(rules).every((key) => rules[key](object[key]));
const rules = {
name: (name) => name.length > 0,
email: (email) => validateEmail(email),
password: (password) => password.length > 0,
};
validateObject({ name: "", email: "", password: "" }, rules); // false
// ---------------------------------------------------------------
// Chunk array
const chunkArray = (array, chunkSize) =>
[...Array(Math.ceil(array.length / chunkSize))].map((_, index) =>
array.slice(index * chunkSize, (index + 1) * chunkSize)
);
chunkArray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3); // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
// ---------------------------------------------------------------
// RGB to HEX
const rgbToHex = (r, g, b) => "#" + ((r << 16) + (g << 8) + b).toString(16).padStart(6, "0");
rgbToHex(255, 0, 0); // #ff0000
// ---------------------------------------------------------------
// Compare two objects
const compareObjects = (obj1, obj2) => {
const c = Object.keys(obj1);
const n = Object.keys(obj2);
return c.length === n.length && c.every((c) => obj1[c] === obj2[c]);
};
compareObjects({ a: 1, b: 2 }, { a: 1, b: 2 }); // true
// ---------------------------------------------------------------
// Get selected text
const getSelectedText = () => window.getSelection().toString();
getSelectedText(); // Selected text
// ---------------------------------------------------------------
// Get object of query params in the url
const getQueryParams = (url) => new URLSearchParams(url.split("?")[1]);
getQueryParams("https://example.com?a=1&b=2"); // { a: "1", b: "2" }
// ---------------------------------------------------------------
// Convert number to word
const numToWord = (number) => number.toLocaleString("en-US", { notation: "compact" });
numToWord(1000000); // "1M"
// ---------------------------------------------------------------
// Count number of duplicates in array
const countDuplicates = (c) => {
const t = {};
return c.forEach((c) => (t[c] = (t[c] || 0) + 1)), t;
};
countDuplicates([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); // { 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1 }
// ---------------------------------------------------------------
// Generate tree from depth
const generateTree = (depth) => [...Array(depth)].map(() => ({ tree: generateTree(depth - 1) }));
generateTree(3); // [{ tree: [{ tree: [{ tree: [] }, { tree: [] }] }, { tree: [{ tree: [] }, { tree: [] }] }] }, { tree: [{ tree: [] }, { tree: [] }] }]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment