DEV Community

Cover image for Javascript snippets you need to know right now ๐Ÿ”ฅ - #2
Abhiraj Bhowmick
Abhiraj Bhowmick

Posted on • Originally published at abhiraj.mdx.one

Javascript snippets you need to know right now ๐Ÿ”ฅ - #2

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.

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 = []
Enter fullscreen mode Exit fullscreen mode

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'] ]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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 ]
Enter fullscreen mode Exit fullscreen mode

8๏ธโƒฃ currentURL
This snippet returns the current URL.

const currentURL = () => window.location.href;

currentURL(); // 'https://abhiraj.mdx.one'
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”Ÿ 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
Enter fullscreen mode Exit fullscreen mode

Thank you for reading. Stay tuned for part 3.


Signup for my newsletter below to never miss out on my blogs and tech news.

Abhiraj's Dev-letter

Until next time,
Abhiraj

Top comments (0)