Skip to content

Instantly share code, notes, and snippets.

@mikowl
Last active June 29, 2024 17:39
Show Gist options
  • Save mikowl/5fa1a06c06264afaa544bb6b8af641b1 to your computer and use it in GitHub Desktop.
Save mikowl/5fa1a06c06264afaa544bb6b8af641b1 to your computer and use it in GitHub Desktop.
πŸ‘‘ Awesome one-liners you might find useful while coding.
// Inspired by https://twitter.com/coderitual/status/1112297299307384833 and https://tapajyoti-bose.medium.com/7-killer-one-liners-in-javascript-33db6798f5bf
// Remove any duplicates from an array of primitives.
const unique = [...new Set(arr)]
// Sleep in async functions. Use: await sleep(2000).
const sleep = (ms) => (new Promise(resolve => setTimeout(resolve, ms)));
// or
const sleep = util.promisify(setTimeout);
// Type this in your code to break chrome debugger in that line.
debugger;
// Just plain english.
[...].every(Number.isFinite);
// Returns all non-falsy values from an array.
[...].filter(Boolean)
// Array destructuring to see matching elements.
let [r, g, b, a] = [255, 0, 0, 255];
// Object destructuring to reduce multiple lines of code to a single line.
let {width, height} = resolution;
// Gets an item from the list and wraps around to the start if n is larger than the list.
items[n % items.length]
// Console.log in array function without adding curly braces.
const addFortyTwo = number => console.log(number) || number + 42
// Same as above
const add42 = n => (console.log(n), n + 42);
// Log variables with names. I love this trick with object ❀️
console.log({ a, b, c, d, e});
// Random hex color
const generateRandomHexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
// We love Javascript that's why instead of Math.floor we use
// Note: Use with caution, it won't work for big (>32bit) or negative numbers
~~anyNumber
// Shuffle Array
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
const copyToClipboard = (text) => navigator.clipboard?.writeText && navigator.clipboard.writeText(text);
copyToClipboard("Hello World!");
// Unique Elements
const getUnique = (arr) => [...new Set(arr)];
const arr = [1, 1, 2, 3, 3, 4, 4, 4, 5, 5];
console.log(getUnique(arr));
// Detect Dark Mode
const isDarkMode = () => window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
console.log(isDarkMode());
// Scroll to top of page
const scrollToTop = () => window.scrollTo({ top: 0, behavior: 'smooth' });
// Scroll to bottom of page
const scrollToBottom = () => window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
// Scroll to top of an element
const scrollToEl = (element) => element.scrollIntoView({ behavior: "smooth", block: "start" });
// Scroll to elements bottom
const scrollToElb = (element) => element.scrollIntoView({ behavior: "smooth", block: "end" });
// Check if an element is focused
const elem = document.querySelector(' .text-input');
const isFocus = elem == document.activeElemnt;
// Check if an array is empty
let arr = [1,2,3,4];
const arrIsEmpty = !(Array.isArray(arr) && arr.length > 0);
// Redirect user
const redirect = url => location.href = url // ex: recdirect("https://google.com")
// Go back to previous page
const navigateBack = () => history.back();
// Get selected text
const getSelectedText = () => window.getSelection().toString();
// Simple star rating ex: rating(5) will print β˜…β˜…β˜…β˜…β˜…
const rating = star => "β˜…".repeat(Math.max(0, Math.min(star, 5))).padEnd(5,"β˜†" );
// because this primeagen tweet:
// https://twitter.com/ThePrimeagen/status/1646204396655591439
// Check if is an array
const isArr = (arr) => Array.isArray(arr);
// Left pad function
const leftPad = (s, l, c = ' ') => c.repeat(l - s.length) + s;
// Check if num is positive
const isPosi = (num) => num > 0;
@benjamingr
Copy link

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

This can be

const sleep = util.promisify(setTimeout);

@martinsebastian
Copy link

martinsebastian commented Apr 3, 2019

In devtool console I often fancy console.log.bind(console) for pointless logging out args from callbacks.

Like somePromise().then(console.log.bind(console));

Most of the time I use it for REST requests or event observers or simply to test out some quick proof of concept when mutating data.

@lxsmnsyc
Copy link

lxsmnsyc commented Apr 4, 2019

You can also inline variable assignments and get the assigned value at the same time:

let flag;

const toggleFlag = () => ( flag = !flag );

console.log(toggleFlag()); // true
console.log(toggleFlag()); // false

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