diff --git a/docs/adapter.html b/docs/adapter.html index 19a7cdefe..9bc525747 100644 --- a/docs/adapter.html +++ b/docs/adapter.html @@ -136,7 +136,7 @@ Object.assig (async() => { console.log(await sum(5)); // 15 (after one second) })(); -

pipeFunctions

Performs left-to-right function composition.

Use Array.prototype.reduce() with the spread operator (...) to perform left-to-right function composition. The first (leftmost) function can accept one or more arguments; the remaining functions must be unary.

const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));
+

Recommended Resource - ES6: The Right Parts

Learn new ES6 JavaScript language features like arrow function, destructuring, generators & more to write cleaner and more productive, readable programs.

pipeFunctions

Performs left-to-right function composition.

Use Array.prototype.reduce() with the spread operator (...) to perform left-to-right function composition. The first (leftmost) function can accept one or more arguments; the remaining functions must be unary.

const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));
 
const add5 = x => x + 5;
 const multiply = (x, y) => x * y;
 const multiplyAndAdd5 = pipeFunctions(multiply, add5);
diff --git a/docs/browser.html b/docs/browser.html
index fa9679983..bd75caf02 100644
--- a/docs/browser.html
+++ b/docs/browser.html
@@ -229,7 +229,7 @@ hub.off
insertAfter(document.getElementById('myId'), '<p>after</p>'); // <div id="myId">...</div> <p>after</p>
 

insertBefore

Inserts an HTML string before the start of the specified element.

Use el.insertAdjacentHTML() with a position of 'beforebegin' to parse htmlString and insert it before the start of el.

const insertBefore = (el, htmlString) => el.insertAdjacentHTML('beforebegin', htmlString);
 
insertBefore(document.getElementById('myId'), '<p>before</p>'); // <p>before</p> <div id="myId">...</div>
-

isBrowserTabFocused

Returns true if the browser tab of the page is focused, false otherwise.

Use the Document.hidden property, introduced by the Page Visibility API to check if the browser tab of the page is visible or hidden.

const isBrowserTabFocused = () => !document.hidden;
+

Recommended Resource - JavaScript: The Hard Parts

Take your JavaScript to the next level. Gain an understanding of callbacks, higher order functions, closure, asynchronous and object-oriented JavaScript!

isBrowserTabFocused

Returns true if the browser tab of the page is focused, false otherwise.

Use the Document.hidden property, introduced by the Page Visibility API to check if the browser tab of the page is visible or hidden.

const isBrowserTabFocused = () => !document.hidden;
 
isBrowserTabFocused(); // true
 

nodeListToArray

Converts a NodeList to an array.

Use spread operator inside new array to convert a NodeList to an array.

const nodeListToArray = nodeList => [...nodeList];
 
nodeListToArray(document.childNodes); // [ <!DOCTYPE html>, html ]
diff --git a/docs/date.html b/docs/date.html
index 2d6d40266..6775d9244 100644
--- a/docs/date.html
+++ b/docs/date.html
@@ -133,7 +133,7 @@
 
isAfterDate(new Date(2010, 10, 21), new Date(2010, 10, 20)); // true
 

isBeforeDate

Check if a date is before another date.

Use the less than operator (<) to check if the first date comes before the second one.

const isBeforeDate = (dateA, dateB) => dateA < dateB;
 
isBeforeDate(new Date(2010, 10, 20), new Date(2010, 10, 21)); // true
-

isSameDate

Check if a date is the same as another date.

Use Date.prototype.toISOString() and strict equality checking (===) to check if the first date is the same as the second one.

const isSameDate = (dateA, dateB) => dateA.toISOString() === dateB.toISOString();
+

Recommended Resource - JavaScript: The Hard Parts

Take your JavaScript to the next level. Gain an understanding of callbacks, higher order functions, closure, asynchronous and object-oriented JavaScript!

isSameDate

Check if a date is the same as another date.

Use Date.prototype.toISOString() and strict equality checking (===) to check if the first date is the same as the second one.

const isSameDate = (dateA, dateB) => dateA.toISOString() === dateB.toISOString();
 
isSameDate(new Date(2010, 10, 20), new Date(2010, 10, 20)); // true
 

maxDate

Returns the maximum of the given dates.

Use Math.max.apply() to find the maximum date value, new Date() to convert it to a Date object.

const maxDate = (...dates) => new Date(Math.max.apply(null, ...dates));
 
const array = [
diff --git a/docs/function.html b/docs/function.html
index 2eb586514..0169d0581 100644
--- a/docs/function.html
+++ b/docs/function.html
@@ -232,7 +232,7 @@ Math.roundanagramsCached('javascript'); // takes a long time
 anagramsCached('javascript'); // returns virtually instantly since it's now cached
 console.log(anagramsCached.cache); // The cached anagrams map
-

negate

Negates a predicate function.

Take a predicate function and apply the not operator (!) to it with its arguments.

const negate = func => (...args) => !func(...args);
+

Recommended Resource - ES6: The Right Parts

Learn new ES6 JavaScript language features like arrow function, destructuring, generators & more to write cleaner and more productive, readable programs.

negate

Negates a predicate function.

Take a predicate function and apply the not operator (!) to it with its arguments.

const negate = func => (...args) => !func(...args);
 
[1, 2, 3, 4, 5, 6].filter(negate(n => n % 2 === 0)); // [ 1, 3, 5 ]
 

once

Ensures a function is called only once.

Utilizing a closure, use a flag, called, and set it to true once the function is called for the first time, preventing it from being called again. In order to allow the function to have its this context changed (such as in an event listener), the function keyword must be used, and the supplied function must have the context applied. Allow the function to be supplied with an arbitrary number of arguments using the rest/spread (...) operator.

const once = fn => {
   let called = false;
diff --git a/docs/index.html b/docs/index.html
index 4b119a1d3..dcbb46dad 100644
--- a/docs/index.html
+++ b/docs/index.html
@@ -308,7 +308,7 @@
 

nthElement

Returns the nth element of an array.

Use Array.prototype.slice() to get an array containing the nth element at the first place. If the index is out of bounds, return undefined. Omit the second argument, n, to get the first element of the array.

const nthElement = (arr, n = 0) => (n === -1 ? arr.slice(n) : arr.slice(n, n + 1))[0];
 
nthElement(['a', 'b', 'c'], 1); // 'b'
 nthElement(['a', 'b', 'b'], -3); // 'a'
-

offset

Moves the specified amount of elements to the end of the array.

Use Array.prototype.slice() twice to get the elements after the specified index and the elements before that. Use the spread operator(...) to combine the two into one array. If offset is negative, the elements will be moved from end to start.

const offset = (arr, offset) => [...arr.slice(offset), ...arr.slice(0, offset)];
+

Recommended Resource - ES6: The Right Parts

Learn new ES6 JavaScript language features like arrow function, destructuring, generators & more to write cleaner and more productive, readable programs.

offset

Moves the specified amount of elements to the end of the array.

Use Array.prototype.slice() twice to get the elements after the specified index and the elements before that. Use the spread operator(...) to combine the two into one array. If offset is negative, the elements will be moved from end to start.

const offset = (arr, offset) => [...arr.slice(offset), ...arr.slice(0, offset)];
 
offset([1, 2, 3, 4, 5], 2); // [3, 4, 5, 1, 2]
 offset([1, 2, 3, 4, 5], -2); // [4, 5, 1, 2, 3]
 

partition

Groups the elements into two arrays, depending on the provided function's truthiness for each element.

Use Array.prototype.reduce() to create an array of two arrays. Use Array.prototype.push() to add elements for which fn returns true to the first array and elements for which fn returns false to the second one.

const partition = (arr, fn) =>
diff --git a/docs/math.html b/docs/math.html
index ad21ae6e8..3c1594771 100644
--- a/docs/math.html
+++ b/docs/math.html
@@ -220,7 +220,7 @@ own individual rating by supplying it as the third argument.
 
luhnCheck('4485275742308327'); // true
 luhnCheck(6011329933655299); //  false
 luhnCheck(123456789); // false
-

maxBy

Returns the maximum value of an array, after mapping each element to a value using the provided function.

Use Array.prototype.map() to map each element to the value returned by fn, Math.max() to get the maximum value.

const maxBy = (arr, fn) => Math.max(...arr.map(typeof fn === 'function' ? fn : val => val[fn]));
+

Recommended Resource - JavaScript: From Fundamentals to Functional JS

Learn higher-order functions, closures, scope, master key functional methods like map, reduce and filter and promises and ES6+ asynchronous JavaScript.

maxBy

Returns the maximum value of an array, after mapping each element to a value using the provided function.

Use Array.prototype.map() to map each element to the value returned by fn, Math.max() to get the maximum value.

const maxBy = (arr, fn) => Math.max(...arr.map(typeof fn === 'function' ? fn : val => val[fn]));
 
maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 8
 maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 8
 

median

Returns the median of an array of numbers.

Find the middle of the array, use Array.prototype.sort() to sort the values. Return the number at the midpoint if length is odd, otherwise the average of the two middle numbers.

const median = arr => {
diff --git a/docs/node.html b/docs/node.html
index 90c095458..467d5d068 100644
--- a/docs/node.html
+++ b/docs/node.html
@@ -163,7 +163,7 @@ console.log<
 

isStream

Checks if the given argument is a stream.

Check if the value is different from null, use typeof to check if the value is of type object and the pipe property is of type function.

const isStream = val => val !== null && typeof val === 'object' && typeof val.pipe === 'function';
 
const fs = require('fs');
 isStream(fs.createReadStream('test.txt')); // true
-

isTravisCI

Checks if the current environment is Travis CI.

Checks if the current environment has the TRAVIS and CI environment variables (reference).

const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env;
+

Recommended Resource - JavaScript: The Hard Parts

Take your JavaScript to the next level. Gain an understanding of callbacks, higher order functions, closure, asynchronous and object-oriented JavaScript!

isTravisCI

Checks if the current environment is Travis CI.

Checks if the current environment has the TRAVIS and CI environment variables (reference).

const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env;
 
isTravisCI(); // true (if code is running on Travis CI)
 

isWritableStream

Checks if the given argument is a writable stream.

Check if the value is different from null, use typeof to check if the value is of type object and the pipe property is of type function. Additionally check if the typeof the _write and _writableState properties are function and object respectively.

const isWritableStream = val =>
   val !== null &&
diff --git a/docs/object.html b/docs/object.html
index 31acfc9ee..42e04dbd6 100644
--- a/docs/object.html
+++ b/docs/object.html
@@ -295,7 +295,7 @@ Foo.prototype.keys(source).every(key => obj.hasOwnProperty(key) && obj[key] === source[key]);
 
matches({ age: 25, hair: 'long', beard: true }, { hair: 'long', beard: true }); // true
 matches({ hair: 'long', beard: true }, { age: 25, hair: 'long', beard: true }); // false
-

matchesWith

Compares two objects to determine if the first one contains equivalent property values to the second one, based on a provided function.

Use Object.keys(source) to get all the keys of the second object, then Array.prototype.every(), Object.hasOwnProperty() and the provided function to determine if all keys exist in the first object and have equivalent values. If no function is provided, the values will be compared using the equality operator.

const matchesWith = (obj, source, fn) =>
+

Recommended Resource - ES6: The Right Parts

Learn new ES6 JavaScript language features like arrow function, destructuring, generators & more to write cleaner and more productive, readable programs.

matchesWith

Compares two objects to determine if the first one contains equivalent property values to the second one, based on a provided function.

Use Object.keys(source) to get all the keys of the second object, then Array.prototype.every(), Object.hasOwnProperty() and the provided function to determine if all keys exist in the first object and have equivalent values. If no function is provided, the values will be compared using the equality operator.

const matchesWith = (obj, source, fn) =>
   Object.keys(source).every(
     key =>
       obj.hasOwnProperty(key) && fn
diff --git a/docs/string.html b/docs/string.html
index 3f4daa477..6a4e98df3 100644
--- a/docs/string.html
+++ b/docs/string.html
@@ -193,7 +193,7 @@
 
pad('cat', 8); // '  cat   '
 pad(String(42), 6, '0'); // '004200'
 pad('foobar', 3); // 'foobar'
-

palindrome

Returns true if the given string is a palindrome, false otherwise.

Convert the string to String.prototype.toLowerCase() and use String.prototype.replace() to remove non-alphanumeric characters from it. Then, use the spread operator (...) to split the string into individual characters, Array.prototype.reverse(), String.prototype.join('') and compare it to the original, unreversed string, after converting it to String.prototype.toLowerCase().

const palindrome = str => {
+

Recommended Resource - JavaScript: From Fundamentals to Functional JS

Learn higher-order functions, closures, scope, master key functional methods like map, reduce and filter and promises and ES6+ asynchronous JavaScript.

palindrome

Returns true if the given string is a palindrome, false otherwise.

Convert the string to String.prototype.toLowerCase() and use String.prototype.replace() to remove non-alphanumeric characters from it. Then, use the spread operator (...) to split the string into individual characters, Array.prototype.reverse(), String.prototype.join('') and compare it to the original, unreversed string, after converting it to String.prototype.toLowerCase().

const palindrome = str => {
   const s = str.toLowerCase().replace(/[\W_]/g, '');
   return s === [...s].reverse().join('');
 };
diff --git a/docs/type.html b/docs/type.html
index 7f03d8ee4..56ffee018 100644
--- a/docs/type.html
+++ b/docs/type.html
@@ -146,7 +146,7 @@
 isObject({ a: 1 }); // true
 isObject({}); // true
 isObject(true); // false
-

isObjectLike

Checks if a value is object-like.

Check if the provided value is not null and its typeof is equal to 'object'.

const isObjectLike = val => val !== null && typeof val === 'object';
+

Recommended Resource - JavaScript: From Fundamentals to Functional JS

Learn higher-order functions, closures, scope, master key functional methods like map, reduce and filter and promises and ES6+ asynchronous JavaScript.

isObjectLike

Checks if a value is object-like.

Check if the provided value is not null and its typeof is equal to 'object'.

const isObjectLike = val => val !== null && typeof val === 'object';
 
isObjectLike({}); // true
 isObjectLike([1, 2, 3]); // true
 isObjectLike(x => x); // false
diff --git a/docs/utility.html b/docs/utility.html
index e0a51f31f..42a5afb7f 100644
--- a/docs/utility.html
+++ b/docs/utility.html
@@ -232,7 +232,7 @@ Logs: {
       return acc;
     }, {});
 
parseCookie('foo=bar; equation=E%3Dmc%5E2'); // { foo: 'bar', equation: 'E=mc^2' }
-

prettyBytes

Converts a number in bytes to a human-readable string.

Use an array dictionary of units to be accessed based on the exponent. Use Number.toPrecision() to truncate the number to a certain number of digits. Return the prettified string by building it up, taking into account the supplied options and whether it is negative or not. Omit the second argument, precision, to use a default precision of 3 digits. Omit the third argument, addSpace, to add space between the number and unit by default.

const prettyBytes = (num, precision = 3, addSpace = true) => {
+

Recommended Resource - JavaScript: From Fundamentals to Functional JS

Learn higher-order functions, closures, scope, master key functional methods like map, reduce and filter and promises and ES6+ asynchronous JavaScript.

prettyBytes

Converts a number in bytes to a human-readable string.

Use an array dictionary of units to be accessed based on the exponent. Use Number.toPrecision() to truncate the number to a certain number of digits. Return the prettified string by building it up, taking into account the supplied options and whether it is negative or not. Omit the second argument, precision, to use a default precision of 3 digits. Omit the third argument, addSpace, to add space between the number and unit by default.

const prettyBytes = (num, precision = 3, addSpace = true) => {
   const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
   if (Math.abs(num) < 1) return num + (addSpace ? ' ' : '') + UNITS[0];
   const exponent = Math.min(Math.floor(Math.log10(num < 0 ? -num : num) / 3), UNITS.length - 1);