Skip to content

Instantly share code, notes, and snippets.

@rob-kistner
Last active October 9, 2020 01:23
Show Gist options
  • Select an option

  • Save rob-kistner/9e8279145e2a0effcdcac7a9527b4218 to your computer and use it in GitHub Desktop.

Select an option

Save rob-kistner/9e8279145e2a0effcdcac7a9527b4218 to your computer and use it in GitHub Desktop.
Useful Javascript Snippets
/* -----------------------------------------
EXAMPLES:
all([4, 2, 3], x => x > 1); // true
all([1, 2, 3]); // true
------------------------------------------*/
const all = (arr, fn = Boolean) => arr.every(fn)
/* -----------------------------------------
EXAMPLES
allEqual([1, 2, 3, 4, 5, 6]); // false
allEqual([1, 1, 1, 1]); // true
------------------------------------------*/
const allEqual = arr => arr.every(val => val === arr[0])
/* -----------------------------------------
EXAMPLES
average(...[1, 2, 3]); // 2
average(1, 2, 3); // 2
------------------------------------------*/
const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length
/* -----------------------------------------
EXAMPLES
byteSize('😀'); // 4
byteSize('Hello World'); // 11
------------------------------------------*/
const byteSize = str => new Blob([str]).size
/* -----------------------------------------
This snippet removes falsy values from an array.
EXAMPLES:
compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]);
* [ 1, 2, 3, 'a', 's', 34 ]
------------------------------------------*/
const compact = arr => arr.filter(Boolean)
const dogs = [
{ name: 'Snickers', age: 2 },
{ name: 'hugo', age: 8 }
];
const justAVar = 'Hi, I\'m just a single variable';
function makeGreen() {
const p = document.querySelector('p');
p.style.color = '#BADA55';
p.style.fontSize = '50px';
}
// Regular
console.log('Hello');
// sticks it into an object and logs it
// so you can see the actual variable names
console.log({justAVar, dogs})
// Interpolated
const myvar1 = '🎱';
console.log('Hello, I am an %s String!', myvar1); // injecting a var
console.log(`Hello, I am an ${myvar1} String!`); // es6 version
// Styled: the %c turns on formatting
console.log('%cI am some great text', 'font-size: 24px; background-color: cyan; border-radius: 50px; padding: 0.25rem 2rem; margin: 1rem 0;');
// warning!
console.warn('Oh, noooooo!');
// Error :|
console.error('Oh, dammmmm!');
// Info
console.info('Crocodiles eat 3-4 people a year.');
// assert
// this won't throw anything because it's true
console.assert(1 === 1, 'That is wrong!');
// but this is not so it logs
const p = document.querySelector('p');
console.assert(p.classList.contains('ouch'), 'p tags do not include the \'ouch\' class.');
// clearing: this will clear the console whenever called
// console.clear();
// Viewing DOM Elements
// this shows everything about the specified element
console.dir(document.querySelector('#breakdown'));
// Grouping together
dogs.forEach(dog => {
// this collapses the group,
// just using console.group will show them opened
console.groupCollapsed(`${dog.name}`);
console.log(`This dog's name is: ${dog.name}`);
console.log(`and he is ${dog.age} years old.`)
console.groupEnd(`${dog.name}`);
});
// counting
console.count('Wes');
console.count('Wes');
console.count('Wes');
console.count('Steve');
console.count('Wes');
console.count('Wes');
console.count('Steve');
console.count('Steve');
console.count('Wes');
// table
// display data in tabular format
console.table(dogs);
// timing
// pass the same string passed into the first console.time into
// console.timeEnd and it'll tell you how long the operation took
console.time('fetching data...');
fetch('https://api.github.com/users/rob-kistner')
.then(data => data.json())
.then(data => {
console.timeEnd('fetching data...');
console.log(data);
});
/* -----------------------------------------
This snippet returns the current URL.
EXAMPLES:
currentURL(); // 'https://google.com'
------------------------------------------*/
const currentURL = () => window.location.href
/* -----------------------------------------
This snippet gets the day of the year from a Date object.
EXAMPLES:
dayOfYear(new Date()); // 272
------------------------------------------*/
const dayOfYear = date =>
Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24)
/* -----------------------------------------
Keeps a function from performing too often by
assigning a timeout period.
EXAMPLES
* el.addEventListener(function() {
* debounce(handleClick, 500)
* })
* function handleClick() {
* console.log('clicked')
* }
------------------------------------------*/
const debounce = function(func, wait, immediate) {
let timeout
return function() {
const context = this
const args = arguments
const later = function() {
timeout = null
if (!immediate) {
func.apply(context, args)
}
}
const callNow = immediate && !timeout
clearTimeout(timeout)
timeout = setTimeout(later, wait || 200)
if (callNow) {
func.apply(context, args)
}
}
}
/* -----------------------------------------
This snippet converts an angle from degrees to radians.
EXAMPLES:
degreesToRads(90.0); // ~1.5708
------------------------------------------*/
const degreesToRads = deg => (deg * Math.PI) / 180.0
/* -----------------------------------------
Taken from:
Fireship:
https://www.youtube.com/watch?v=Mus_vwhTCq0
------------------------------------------*/
/**
* Destructure in arguments
*
* By destructuring in the argument, you can
* just choose a few members of the object to
* work with an won't need to reference the
* object name directly
*
* i.e.: below, you wouldn't have to log 'animal.name',
* you'd just use 'name'
*/
const animal = {
name: 'Bingie',
type: 'Cat',
age: 11,
description: {
coat: 'mottled',
paws: 'white'
},
size: 'Large'
}
function showAnimal({name, age, size}) {
console.log('Here\'s the animal...')
console.log(name, age, size)
}
showAnimal(animal)
/* -----------------------------------------
This snippet returns the difference between two arrays.
EXAMPLES:
difference([1, 2, 3], [1, 2, 4]); // [3]
------------------------------------------*/
const difference = (a, b) => {
const s = new Set(b)
return a.filter(x => !s.has(x))
}
/* -----------------------------------------
This snippet returns the distance between two points.
EXAMPLES:
distance(1, 1, 2, 3); // 2.23606797749979
------------------------------------------*/
const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
/* -----------------------------------------
This snippet returns a new array with n elements removed from the left.
EXAMPLES:
drop([1, 2, 3]); // [2,3]
drop([1, 2, 3], 2); // [3]
drop([1, 2, 3], 42); // []
------------------------------------------*/
const drop = (arr, n = 1) => arr.slice(n);
/* -----------------------------------------
This snippet returns every nth element in an array.
EXAMPLES:
everyNth([1, 2, 3, 4, 5, 6], 2); // [ 2, 4, 6 ]
------------------------------------------*/
const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1)
/* -----------------------------------------
This snippet calculates the factorial of a number.
EXAMPLES
factorial(6); // 720
------------------------------------------*/
const factorial = n =>
n < 0
? (() => {
throw new TypeError('Negative numbers are not allowed!')
})()
: n <= 1
? 1
: n * factorial(n - 1)
/* -----------------------------------------
This snippet returns the last element for which the provided function returns a truthy value.
EXAMPLES:
findLast([1, 2, 3, 4], n => n % 2 === 1); // 3
------------------------------------------*/
const findLast = (arr, fn) => arr.filter(fn).pop()
/* -----------------------------------------
Reduce an array of objects (i.e.: json)
to find the next useable max number. In
this case, it's combing through the "id"s
------------------------------------------*/
let data = [
{ "id": "1", "firstname": "Fixdis", "lastname": "Problem" },
{ "id": "5", "firstname": "Ifits", "lastname": "Friendly" },
{ "id": "24", "firstname": "Mya", "lastname": "Crotch" },
{ "id": "81", "firstname": "Glenn", "lastname": "Tipton" },
{ "id": "23", "firstname": "This", "lastname": "Dude" },
];
const findMaxNum = ( data, fld ) => {
return data.reduce( ( prev, curr ) => {
return ( parseInt(prev[fld]) > parseInt(curr[fld]) ) ? prev : curr;
})[fld];
}
console.log(findMaxNum(data,"id"));
/* -----------------------------------------
EXAMPLES
getImages(document, true);
* ['image1.jpg', 'image2.png', 'image1.png', '...']
getImages(document, false);
* ['image1.jpg', 'image2.png', '...']
------------------------------------------*/
const getImages = (el, includeDuplicates = false) => {
const images = [...el.getElementsByTagName('img')].map(img => img.getAttribute('src'))
return includeDuplicates ? images : [...new Set(images)]
}
/* -----------------------------------------
This snippet returns the value of a CSS rule for the specified element.
EXAMPLES:
getStyle(document.querySelector('p'), 'font-size'); // '16px'
------------------------------------------*/
const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName]
/* -----------------------------------------
This snippet returns the head of a list.
EXAMPLES:
head([1, 2, 3]); // 1
head([]); // undefined
head(null); // undefined
head(undefined); // undefined
------------------------------------------*/
const head = arr => (arr && arr.length ? arr[0] : undefined)
/* -----------------------------------------
This snippet hides all the elements specified.
EXAMPLES
hide(document.querySelectorAll('img'));
* Hides all <img> elements on the page
------------------------------------------*/
const hide = (...el) => [...el].forEach(e => (e.style.display = 'none'))
/* -----------------------------------------
This snippet returns true if all the elements in values are included in arr, false otherwise.
EXAMPLES
* includesAll([1, 2, 3, 4], [1, 4]); // true
* includesAll([1, 2, 3, 4], [1, 5]); // false
------------------------------------------*/
const includesAll = (arr, values) => values.every(v => arr.includes(v))
/* -----------------------------------------
This snippet returns all the elements of an array except the last one.
EXAMPLES
* initial([1, 2, 3]); // [1,2]
------------------------------------------*/
const initial = arr => arr.slice(0, -1)
/* -----------------------------------------
This snippet checks whether a date is after another date.
EXAMPLES
* isAfterDate(new Date(2010, 10, 21), new Date(2010, 10, 20));
!@ true
------------------------------------------*/
const isAfterDate = (dateA, dateB) => dateA > dateB
/* -----------------------------------------
This snippet checks whether the given argument is a symbol.
EXAMPLES
* isSymbol(Symbol('x'));
! true
------------------------------------------*/
const isSymbol = val => typeof val === 'symbol'
/* -----------------------------------------
This snippet results in a boolean representation of a specific date.
EXAMPLES
* isWeekend();
! 2018-10-19 (if current date is 2018-10-18)
------------------------------------------*/
const isWeekend = (t = new Date()) => t.getDay() % 6 === 0
/* -----------------------------------------
This snippet calculates the midpoint between two pairs of (x,y) points.
EXAMPLES:
* midpoint([2, 2], [4, 4]); // [3, 3]
* midpoint([4, 4], [6, 6]); // [5, 5]
* midpoint([1, 3], [2, 4]); // [1.5, 3.5]
------------------------------------------*/
const midpoint = ([x1, y1], [x2, y2]) => [(x1 + x2) / 2, (y1 + y2) / 2]
/* -----------------------------------------
This snippet negates a predicate function.
Take a predicate function and apply the not operator (!) to it with its arguments.
EXAMPLES
* [1, 2, 3, 4, 5, 6].filter(negate(n => n % 2 === 0));
! [ 1, 3, 5 ]
------------------------------------------*/
const negate = func => (...args) => !func(...args)
/* -----------------------------------------
This snippet returns the powerset of a given array of numbers.
Use Array.prototype.reduce() combined with Array.prototype.map()
to iterate over elements and combine into an array
containing all combinations.
EXAMPLES
* powerset([1, 2]);
? [[], [1], [2], [2, 1]]
------------------------------------------*/
const powerset = arr => {
return arr.reduce((a, v) => {
return a.concat(a.map(r => {
[v].concat(r))
)}, [[]])
}
}
const randColor = () => {
return '#'+Math.random().toString(16).substr(-6);
};
/* -----------------------------------------
This snippet redirects to a specified URL.
Use window.location.href or window.location.replace()
to redirect to url. Pass a second argument to simulate
a link click (true – default) or an HTTP redirect (false).
EXAMPLES
* redirect('https://google.com');
------------------------------------------*/
const redirect = (url, asLink = true) =>
asLink ? (window.location.href = url) : window.location.replace(url)
/* -----------------------------------------
This snippet removes HTML/XML tags from string.
Use a regular expression to remove HTML/XML tags from a string.
EXAMPLES
* stripHTMLTags('<p><em>lorem</em> <strong>ipsum</strong></p>');
? 'lorem ipsum'
------------------------------------------*/
const stripHTMLTags = str => str.replace(/<[^>]*>/g, '')
/* -----------------------------------------
This snippet returns every element that
exists in any of the two arrays once.
Create a Set with all values of a and b
and convert to an array.
EXAMPLES
* union([1, 2, 3], [4, 3, 2]);
? [1, 2, 3, 4]
------------------------------------------*/
const union = (a, b) => Array.from(new Set([...a, ...b]))
/* -----------------------------------------
This snippet returns all unique values of an array.
Use ES6 Set and the ...rest operator to discard
all duplicated values.
EXAMPLES
* uniqueElements([1, 2, 2, 3, 4, 4, 5]);
? [1, 2, 3, 4, 5]
------------------------------------------*/
const uniqueElements = arr => [...new Set(arr)]
@rob-kistner
Copy link
Author

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