Skip to content

Instantly share code, notes, and snippets.

@alxmtr
Created April 1, 2019 14:48
Show Gist options
  • Save alxmtr/b25f8656712b52bc8b2db4ce22628e99 to your computer and use it in GitHub Desktop.
Save alxmtr/b25f8656712b52bc8b2db4ce22628e99 to your computer and use it in GitHub Desktop.
JavaScript one-liners
// 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))
// Type this in your code to break chrome debugger in that line (breakpoint).
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 withour adding curly braces.
const addFortyTwo = number => console.log(number) || number + 42
// Same as above
const add42 = n => (console.log(n), number + 42)
// Log variables with names.
console.log({ a, b, c, d, e })
// Random hex color
'#' + Math.floor(Math.random() * 16777215).toString(16)
// Same as above
'#' + (Math.random() * 0xFFFFFF << 0).toString(16)
// Alternative to Math.floor
~~anyNumber
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment