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.

Javascript snippets you need to know right now 🔥 – #1
Abhiraj Bho…


This content originally appeared on DEV Community and was authored by Abhiraj Bhowmick

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

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.

Abhiraj's Dev-letter

Until next time,
Abhiraj


This content originally appeared on DEV Community and was authored by Abhiraj Bhowmick


Print Share Comment Cite Upload Translate Updates
APA

Abhiraj Bhowmick | Sciencx (2021-11-17T10:13:06+00:00) Javascript snippets you need to know right now 🔥 – #2. Retrieved from https://www.scien.cx/2021/11/17/javascript-snippets-you-need-to-know-right-now-%f0%9f%94%a5-2/

MLA
" » Javascript snippets you need to know right now 🔥 – #2." Abhiraj Bhowmick | Sciencx - Wednesday November 17, 2021, https://www.scien.cx/2021/11/17/javascript-snippets-you-need-to-know-right-now-%f0%9f%94%a5-2/
HARVARD
Abhiraj Bhowmick | Sciencx Wednesday November 17, 2021 » Javascript snippets you need to know right now 🔥 – #2., viewed ,<https://www.scien.cx/2021/11/17/javascript-snippets-you-need-to-know-right-now-%f0%9f%94%a5-2/>
VANCOUVER
Abhiraj Bhowmick | Sciencx - » Javascript snippets you need to know right now 🔥 – #2. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/11/17/javascript-snippets-you-need-to-know-right-now-%f0%9f%94%a5-2/
CHICAGO
" » Javascript snippets you need to know right now 🔥 – #2." Abhiraj Bhowmick | Sciencx - Accessed . https://www.scien.cx/2021/11/17/javascript-snippets-you-need-to-know-right-now-%f0%9f%94%a5-2/
IEEE
" » Javascript snippets you need to know right now 🔥 – #2." Abhiraj Bhowmick | Sciencx [Online]. Available: https://www.scien.cx/2021/11/17/javascript-snippets-you-need-to-know-right-now-%f0%9f%94%a5-2/. [Accessed: ]
rf:citation
» Javascript snippets you need to know right now 🔥 – #2 | Abhiraj Bhowmick | Sciencx | https://www.scien.cx/2021/11/17/javascript-snippets-you-need-to-know-right-now-%f0%9f%94%a5-2/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.