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)