So how's it going?
Welcome to the 2nd edition of 50 essential JS snippets, you need to know, read the first edition below if you missed it.
Javascript snippets you need to know right now ๐ฅ - #1
Abhiraj Bhowmick ใป Nov 10 '21 ใป 2 min read
Let's get started.
1๏ธโฃ allEqual
This snippet checks whether all elements of the array are equal.
const allEqual = arr => arr.every(val => val === arr[0]);
allEqual([1, 2, 3, 4, 5, 6]); // false
allEqual([1, 1, 1, 1]); // true
2๏ธโฃ approximatelyEqual
This snippet checks whether two numbers are approximately equal to each other, with a small difference.
const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon;
approximatelyEqual(Math.PI / 2.0, 1.5708); // true
3๏ธโฃ attempt
This snippet executes a function, returning either the result or the caught error object.
const attempt = (fn, ...args) => {
try {
return fn(...args);
} catch (e) {
return e instanceof Error ? e : new Error(e);
}
};
var elements = attempt(function(selector) {
return document.querySelectorAll(selector);
}, '>_>');
if (elements instanceof Error) elements = []; // elements = []
4๏ธโฃ bifurcateBy
This snippet splits values into two groups, based on a predicate function. If the predicate function returns a truthy value, the element will be placed in the first group. Otherwise, it will be placed in the second group.
You can use Array.prototype.reduce()and Array.prototype.push()to add elements to groups, based on the value returned by fnfor each element.
const bifurcateBy = (arr, fn) =>
arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]);
bifurcateBy(['beep', 'boop', 'foo', 'bar'], x => x[0] === 'b');
// [ ['beep', 'boop', 'bar'], ['foo'] ]
5๏ธโฃ bottomVisible
This snippet checks whether the bottom of a page is visible.
const bottomVisible = () =>
document.documentElement.clientHeight + window.scrollY >=
(document.documentElement.scrollHeight || document.documentElement.clientHeight);
bottomVisible(); // true
6๏ธโฃ castArray
This snippet converts a non-array value into array.
const castArray = val => (Array.isArray(val) ? val : [val]);
castArray('foo'); // ['foo']
castArray([1]); // [1]
7๏ธโฃ compact
This snippet removes false values from an array.
const compact = arr => arr.filter(Boolean);
compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]);
// [ 1, 2, 3, 'a', 's', 34 ]
8๏ธโฃ currentURL
This snippet returns the current URL.
const currentURL = () => window.location.href;
currentURL(); // 'https://abhiraj.mdx.one'
9๏ธโฃ defer
This snippet delays the execution of a function until the current call stack is cleared.
const defer = (fn, ...args) => setTimeout(fn, 1, ...args);
defer(console.log, 'a'), console.log('b'); // logs 'b' then 'a'
๐ degreesToRads
This code snippet can be used to convert a value from degrees to radians.
const degreesToRads = deg => (deg * Math.PI) / 180.0;
degreesToRads(90.0); // ~1.5708
Thank you for reading. Stay tuned for part 3.
Signup for my newsletter below to never miss out on my blogs and tech news.
Until next time,
Abhiraj
Top comments (0)