Skip to content

Instantly share code, notes, and snippets.

@omichelsen
Last active November 20, 2021 16:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omichelsen/610fb8797573b1ca9384cbe9aed72d72 to your computer and use it in GitHub Desktop.
Save omichelsen/610fb8797573b1ca9384cbe9aed72d72 to your computer and use it in GitHub Desktop.
JavaScript cheat sheet
// Random 0 to max (excl)
const random = (max) => Math.floor(Math.random() * max)
// Random between (min incl, max excl)
const random = (min, max) => Math.floor(Math.random() * (max - min) + min)
// Fill array
const arr = new Array(42).fill(0).map(() => random(1, 5))
// Remove duplicates from Array (tip: fallback using indexOf)
let chars = ['A', 'B', 'A', 'C', 'B']
let uniqueChars = [...new Set(chars)]
// Empty an array
A.length = 0 // A.splice(0) or A.splice(0, A.length)
// Remove/replace element from array in place
[1, 2, 3, 4].splice(1, 1, 42) // returns item (2) -> [1, 42, 3, 4]
// Shallow copy portion of array
[1, 2, 3, 4].slice(2) // returns from index to end [3, 4]
// Date add
Date.now() + 1000 * 60 * x // x minutes
Date.now() + 1000 * 60 * 60 * x // x hours
Date.now() + 1000 * 60 * 60 * 24 * x // x days
// Even/odd numbers
for (let i = 0; i < 10; i++)
i % 2 // even === 0
// Divisible by 3
1 % 3 === 0 // 1 false
2 % 3 === 0 // 2 false
3 % 3 === 0 // 0 true
// Sort is in-place and by default uses UTF-16 code order
// sort by value (numeric)
[0, 3, 1, 2].sort((a, b) => a - b)
// case insensitive sort by name (string)
['AbE', 'Ben', 'aBe'].sort((a, b) => {
const nameA = a.toUpperCase(); // ignore upper and lowercase
const nameB = b.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) return -1;
if (nameA > nameB) return 1;
return 0; // names must be equal
});
// Fetch
fetch('https://...', {
method: 'post',
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
body: JSON.stringify({ asdf: 42 })
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment