diff --git a/docs/archive.html b/docs/archive.html index d4e97f0ec..f319124cf 100644 --- a/docs/archive.html +++ b/docs/archive.html @@ -1,28 +1,4 @@ - - - - - - - - Snippets Archive - 30 seconds of code - - - - - - - - - - - Snippets Archive - 30 seconds of code - - - -
-

logo 30 seconds of code

-

Curated collection of useful JavaScript snippets
that you can understand in 30 seconds or less.

- -
-
-
-
-

Snippets Archive

-

These snippets, while useful and interesting, didn't quite make it into the repository due to either having very specific use-cases or being outdated. However we felt like they might still be useful to some readers, so here they are.


-
-
- -

binarySearch

-

Use recursion. Similar to Array.indexOf() that finds the index of a value within an array. -The difference being this operation only works with sorted arrays which offers a major performance boost due to it's logarithmic nature when compared to a linear search or Array.indexOf().

-

Search a sorted array by repeatedly dividing the search interval in half. -Begin with an interval covering the whole array. -If the value of the search is less than the item in the middle of the interval, recurse into the lower half. Otherwise recurse into the upper half. -Repeatedly recurse until the value is found which is the mid or you've recursed to a point that is greater than the length which means the value doesn't exist and return -1.

-
const binarySearch = (arr, val, start = 0, end = arr.length - 1) => {
+      }

logo 30 seconds of code

Curated collection of useful JavaScript snippets
that you can understand in 30 seconds or less.

Snippets Archive

These snippets, while useful and interesting, didn't quite make it into the repository due to either having very specific use-cases or being outdated. However we felt like they might still be useful to some readers, so here they are.


binarySearch

Use recursion. Similar to Array.indexOf() that finds the index of a value within an array. The difference being this operation only works with sorted arrays which offers a major performance boost due to it's logarithmic nature when compared to a linear search or Array.indexOf().

Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search is less than the item in the middle of the interval, recurse into the lower half. Otherwise recurse into the upper half. Repeatedly recurse until the value is found which is the mid or you've recursed to a point that is greater than the length which means the value doesn't exist and return -1.

const binarySearch = (arr, val, start = 0, end = arr.length - 1) => {
   if (start > end) return -1;
   const mid = Math.floor((start + end) / 2);
   if (arr[mid] > val) return binarySearch(arr, val, start, mid - 1);
@@ -114,12 +65,7 @@ Repeatedly recurse until the value is found which is the mid or you've recursed
 };
 
binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 6); // 2
 binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 21); // -1
-
-

cleanObj

-

Removes any properties except the ones specified from a JSON object.

-

Use Object.keys() method to loop over given JSON object and deleting keys that are not included in given array. -If you pass a special key,childIndicator, it will search deeply apply the function to inner objects, too.

-
const cleanObj = (obj, keysToKeep = [], childIndicator) => {
+

cleanObj

Removes any properties except the ones specified from a JSON object.

Use Object.keys() method to loop over given JSON object and deleting keys that are not included in given array. If you pass a special key,childIndicator, it will search deeply apply the function to inner objects, too.

const cleanObj = (obj, keysToKeep = [], childIndicator) => {
   Object.keys(obj).forEach(key => {
     if (key === childIndicator) {
       cleanObj(obj[key], keysToKeep, childIndicator);
@@ -131,31 +77,12 @@ If you pass a special key,childIndicator, it will search deeply app
 };
 
const testObj = { a: 1, b: 2, children: { a: 1, b: 2 } };
 cleanObj(testObj, ['a'], 'children'); // { a: 1, children : { a: 1}}
-
-

collatz

-

Applies the Collatz algorithm.

-

If n is even, return n/2. Otherwise, return 3n+1.

-
const collatz = n => (n % 2 === 0 ? n / 2 : 3 * n + 1);
+

collatz

Applies the Collatz algorithm.

If n is even, return n/2. Otherwise, return 3n+1.

const collatz = n => (n % 2 === 0 ? n / 2 : 3 * n + 1);
 
collatz(8); // 4
-
-

countVowels

-

Retuns number of vowels in provided string.

-

Use a regular expression to count the number of vowels (A, E, I, O, U) in a string.

-
const countVowels = str => (str.match(/[aeiou]/gi) || []).length;
+

countVowels

Retuns number of vowels in provided string.

Use a regular expression to count the number of vowels (A, E, I, O, U) in a string.

const countVowels = str => (str.match(/[aeiou]/gi) || []).length;
 
countVowels('foobar'); // 3
 countVowels('gym'); // 0
-
-

factors

-

Returns the array of factors of the given num. -If the second argument is set to true returns only the prime factors of num. -If num is 1 or 0 returns an empty array. -If num is less than 0 returns all the factors of -int together with their additive inverses.

-

Use Array.from(), Array.map() and Array.filter() to find all the factors of num. -If given num is negative, use Array.reduce() to add the additive inverses to the array. -Return all results if primes is false, else determine and return only the prime factors using isPrime and Array.filter(). -Omit the second argument, primes, to return prime and non-prime factors by default.

-

Note:- Negative numbers are not considered prime.

-
const factors = (num, primes = false) => {
+

factors

Returns the array of factors of the given num. If the second argument is set to true returns only the prime factors of num. If num is 1 or 0 returns an empty array. If num is less than 0 returns all the factors of -int together with their additive inverses.

Use Array.from(), Array.map() and Array.filter() to find all the factors of num. If given num is negative, use Array.reduce() to add the additive inverses to the array. Return all results if primes is false, else determine and return only the prime factors using isPrime and Array.filter(). Omit the second argument, primes, to return prime and non-prime factors by default.

Note:- Negative numbers are not considered prime.

const factors = (num, primes = false) => {
   const isPrime = num => {
     const boundary = Math.floor(Math.sqrt(num));
     for (var i = 2; i <= boundary; i++) if (num % i === 0) return false;
@@ -178,20 +105,10 @@ Omit the second argument, primes, to return prime and non-prime fac
 factors(12, true); // [2,3]
 factors(-12); // [2, -2, 3, -3, 4, -4, 6, -6, 12, -12]
 factors(-12, true); // [2,3]
-
-

fibonacciCountUntilNum

-

Returns the number of fibonnacci numbers up to num(0 and num inclusive).

-

Use a mathematical formula to calculate the number of fibonacci numbers until num.

-
const fibonacciCountUntilNum = num =>
+

fibonacciCountUntilNum

Returns the number of fibonnacci numbers up to num(0 and num inclusive).

Use a mathematical formula to calculate the number of fibonacci numbers until num.

const fibonacciCountUntilNum = num =>
   Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
 
fibonacciCountUntilNum(10); // 7
-
-

fibonacciUntilNum

-

Generates an array, containing the Fibonacci sequence, up until the nth term.

-

Create an empty array of the specific length, initializing the first two values (0 and 1). -Use Array.reduce() to add values into the array, using the sum of the last two values, except for the first two. -Uses a mathematical formula to calculate the length of the array required.

-
const fibonacciUntilNum = num => {
+

fibonacciUntilNum

Generates an array, containing the Fibonacci sequence, up until the nth term.

Create an empty array of the specific length, initializing the first two values (0 and 1). Use Array.reduce() to add values into the array, using the sum of the last two values, except for the first two. Uses a mathematical formula to calculate the length of the array required.

const fibonacciUntilNum = num => {
   let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
   return Array.from({ length: n }).reduce(
     (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),
@@ -199,15 +116,7 @@ Uses a mathematical formula to calculate the length of the array required.

); };
fibonacciUntilNum(10); // [ 0, 1, 1, 2, 3, 5, 8 ]
-
-

howManyTimes

-

Returns the number of times num can be divided by divisor (integer or fractional) without getting a fractional answer. -Works for both negative and positive integers.

-

If divisor is -1 or 1 return Infinity. -If divisor is -0 or 0 return 0. -Otherwise, keep dividing num with divisor and incrementing i, while the result is an integer. -Return the number of times the loop was executed, i.

-
const howManyTimes = (num, divisor) => {
+

howManyTimes

Returns the number of times num can be divided by divisor (integer or fractional) without getting a fractional answer. Works for both negative and positive integers.

If divisor is -1 or 1 return Infinity. If divisor is -0 or 0 return 0. Otherwise, keep dividing num with divisor and incrementing i, while the result is an integer. Return the number of times the loop was executed, i.

const howManyTimes = (num, divisor) => {
   if (divisor === 1 || divisor === -1) return Infinity;
   if (divisor === 0) return 0;
   let i = 0;
@@ -221,14 +130,7 @@ Return the number of times the loop was executed, i.

howManyTimes(100, 2.5); // 2 howManyTimes(100, 0); // 0 howManyTimes(100, -1); // Infinity -
-

httpDelete

-

Makes a DELETE request to the passed URL.

-

Use XMLHttpRequest web api to make a delete request to the given url. -Handle the onload event, by running the provided callback function. -Handle the onerror event, by running the provided err function. -Omit the third argument, err to log the request to the console's error stream by default.

-
const httpDelete = (url, callback, err = console.error) => {
+

httpDelete

Makes a DELETE request to the passed URL.

Use XMLHttpRequest web api to make a delete request to the given url. Handle the onload event, by running the provided callback function. Handle the onerror event, by running the provided err function. Omit the third argument, err to log the request to the console's error stream by default.

const httpDelete = (url, callback, err = console.error) => {
   const request = new XMLHttpRequest();
   request.open("DELETE", url, true);
   request.onload = () => callback(request);
@@ -238,15 +140,7 @@ Omit the third argument, err to log the request to the console's er
 
httpDelete('https://website.com/users/123', request => {
   console.log(request.responseText);
 }); // 'Deletes a user from the database'
-
-

httpPut

-

Makes a PUT request to the passed URL.

-

Use XMLHttpRequest web api to make a put request to the given url. -Set the value of an HTTP request header with setRequestHeader method. -Handle the onload event, by running the provided callback function. -Handle the onerror event, by running the provided err function. -Omit the last argument, err to log the request to the console's error stream by default.

-
const httpPut = (url, data, callback, err = console.error) => {
+

httpPut

Makes a PUT request to the passed URL.

Use XMLHttpRequest web api to make a put request to the given url. Set the value of an HTTP request header with setRequestHeader method. Handle the onload event, by running the provided callback function. Handle the onerror event, by running the provided err function. Omit the last argument, err to log the request to the console's error stream by default.

const httpPut = (url, data, callback, err = console.error) => {
     const request = new XMLHttpRequest();
     request.open("PUT", url, true);
     request.setRequestHeader('Content-type','application/json; charset=utf-8');
@@ -259,42 +153,24 @@ Omit the last argument, err to log the request to the console's err
 httpPut('https://website.com/users/123', data, request => {
   console.log(request.responseText);
 }); // 'Updates a user's password in database'
-
-

isArmstrongNumber

-

Checks if the given number is an Armstrong number or not.

-

Convert the given number into an array of digits. Use the exponent operator (**) to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return true otherwise false.

-
const isArmstrongNumber = digits =>
+

isArmstrongNumber

Checks if the given number is an Armstrong number or not.

Convert the given number into an array of digits. Use the exponent operator (**) to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return true otherwise false.

const isArmstrongNumber = digits =>
   (arr => arr.reduce((a, d) => a + parseInt(d) ** arr.length, 0) == digits)(
     (digits + '').split('')
   );
 
isArmstrongNumber(1634); // true
 isArmstrongNumber(56); // false
-
-

isSimilar

-

Determines if the pattern matches with str.

-

Use String.toLowerCase() to convert both strings to lowercase, then loop through str and determine if it contains all characters of pattern and in the correct order. -Adapted from here.

-
const isSimilar = (pattern, str) =>
+

isSimilar

Determines if the pattern matches with str.

Use String.toLowerCase() to convert both strings to lowercase, then loop through str and determine if it contains all characters of pattern and in the correct order. Adapted from here.

const isSimilar = (pattern, str) =>
 	[...str].reduce(
 		(matchIndex, char) => char.toLowerCase() === (pattern[matchIndex]  || '').toLowerCase() ? matchIndex + 1 : matchIndex, 0
 	) === pattern.length ? true : false;
 
isSimilar('rt','Rohit'); // true
 isSimilar('tr','Rohit'); // false
-
-

JSONToDate

-

Converts a JSON object to a date.

-

Use Date(), to convert dates in JSON format to readable format (dd/mm/yyyy).

-
const JSONToDate = arr => {
+

JSONToDate

Converts a JSON object to a date.

Use Date(), to convert dates in JSON format to readable format (dd/mm/yyyy).

const JSONToDate = arr => {
   const dt = new Date(parseInt(arr.toString().substr(6)));
   return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`;
 };
 
JSONToDate(/Date(1489525200000)/); // "14/3/2017"
-
-

levenshteinDistance

-

Calculates the Levenshtein distance between two strings.

-

Calculates the number of changes (substitutions, deletions or additions) required to convert string1 to string2. -Can also be used to compare two strings as shown in the second example.

-
const levenshteinDistance  = (string1, string2) => {
+

levenshteinDistance

Calculates the Levenshtein distance between two strings.

Calculates the number of changes (substitutions, deletions or additions) required to convert string1 to string2. Can also be used to compare two strings as shown in the second example.

const levenshteinDistance  = (string1, string2) => {
     if(string1.length === 0) return string2.length;
     if(string2.length === 0) return string1.length;
     let matrix = Array(string2.length + 1).fill(0).map((x,i) => [i]);
@@ -314,13 +190,7 @@ Can also be used to compare two strings as shown in the second example.

levenshteinDistance('30-seconds-of-code','30-seconds-of-python-code'); // 7
 const compareStrings = (string1,string2) => (100 - levenshteinDistance(string1,string2) / Math.max(string1.length,string2.length));
 compareStrings('30-seconds-of-code', '30-seconds-of-python-code'); // 99.72 (%)
-
-

quickSort

-

QuickSort an Array (ascending sort by default).

-

Use recursion. -Use Array.filter and spread operator (...) to create an array that all elements with values less than the pivot come before the pivot, and all elements with values greater than the pivot come after it. -If the parameter desc is truthy, return array sorts in descending order.

-
const quickSort = ([n, ...nums], desc) =>
+

quickSort

QuickSort an Array (ascending sort by default).

Use recursion. Use Array.filter and spread operator (...) to create an array that all elements with values less than the pivot come before the pivot, and all elements with values greater than the pivot come after it. If the parameter desc is truthy, return array sorts in descending order.

const quickSort = ([n, ...nums], desc) =>
   isNaN(n)
     ? []
     : [
@@ -330,23 +200,10 @@ If the parameter desc is truthy, return array sorts in descending o
       ];
 
quickSort([4, 1, 3, 2]); // [1,2,3,4]
 quickSort([4, 1, 3, 2], true); // [4,3,2,1]
-
-

removeVowels

-

Returns all the vowels in a str replaced by repl.

-

Use String.replace() with a regexp to replace all vowels in str. -Omot repl to use a default value of ''.

-
const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi,repl);
+

removeVowels

Returns all the vowels in a str replaced by repl.

Use String.replace() with a regexp to replace all vowels in str. Omot repl to use a default value of ''.

const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi,repl);
 
removeVowels("foobAr"); // "fbr"
 removeVowels("foobAr","*"); // "f**b*r"
-
-

solveRPN

-

Solves the given mathematical expression in reverse polish notation. -Throws appropriate errors if there are unrecognized symbols or the expression is wrong. The valid operators are :- +,-,*,/,^,** (^&** are the exponential symbols and are same). This snippet does not supports any unary operators.

-

Use a dictionary, OPERATORS to specify each operator's matching mathematical operation. -Use String.replace() with a regular expression to replace ^ with **, String.split() to tokenize the string and Array.filter() to remove empty tokens. -Use Array.forEach() to parse each symbol, evaluate it as a numeric value or operator and solve the mathematical expression. -Numeric values are converted to floating point numbers and pushed to a stack, while operators are evaluated using the OPERATORS dictionary and pop elements from the stack to apply operations.

-
const solveRPN = rpn => {
+

solveRPN

Solves the given mathematical expression in reverse polish notation. Throws appropriate errors if there are unrecognized symbols or the expression is wrong. The valid operators are :- +,-,*,/,^,** (^&** are the exponential symbols and are same). This snippet does not supports any unary operators.

Use a dictionary, OPERATORS to specify each operator's matching mathematical operation. Use String.replace() with a regular expression to replace ^ with **, String.split() to tokenize the string and Array.filter() to remove empty tokens. Use Array.forEach() to parse each symbol, evaluate it as a numeric value or operator and solve the mathematical expression. Numeric values are converted to floating point numbers and pushed to a stack, while operators are evaluated using the OPERATORS dictionary and pop elements from the stack to apply operations.

const solveRPN = rpn => {
   const OPERATORS = {
     '*': (a, b) => a * b,
     '+': (a, b) => a + b,
@@ -376,23 +233,10 @@ Numeric values are converted to floating point numbers and pushed to a sta
 };
 
solveRPN('15 7 1 1 + - / 3 * 2 1 1 + + -'); // 5
 solveRPN('2 3 ^'); // 8
-
-

speechSynthesis

-

Performs speech synthesis (experimental).

-

Use SpeechSynthesisUtterance.voice and window.speechSynthesis.getVoices() to convert a message to speech. -Use window.speechSynthesis.speak() to play the message.

-

Learn more about the SpeechSynthesisUtterance interface of the Web Speech API.

-
const speechSynthesis = message => {
+

speechSynthesis

Performs speech synthesis (experimental).

Use SpeechSynthesisUtterance.voice and window.speechSynthesis.getVoices() to convert a message to speech. Use window.speechSynthesis.speak() to play the message.

Learn more about the SpeechSynthesisUtterance interface of the Web Speech API.

const speechSynthesis = message => {
   const msg = new SpeechSynthesisUtterance(message);
   msg.voice = window.speechSynthesis.getVoices()[0];
   window.speechSynthesis.speak(msg);
 };
 
speechSynthesis('Hello, World'); // // plays the message
-
-
-
- -
- - - +

\ No newline at end of file diff --git a/docs/beginner.html b/docs/beginner.html index 162c1f056..06f319cca 100644 --- a/docs/beginner.html +++ b/docs/beginner.html @@ -1,28 +1,4 @@ - - - - - - - - Snippets for Beginners - 30 seconds of code - - - - - - - - - - - Snippets for Beginners - 30 seconds of code - - - -
-

logo 30 seconds of code

-

Curated collection of useful JavaScript snippets
that you can understand in 30 seconds or less.

- -
-
-
-
-

Snippets for Beginners

-

The following section is aimed towards individuals who are at the start of their web developer journey. Each snippet in the next section is simple yet very educational for newcomers. This section is by no means a complete resource for learning modern JavaScript. However, it is enough to grasp some common concepts and use cases. We also strongly recommend checking out MDN web docs as a learning resource.


-
-
- -

currentURL

-

Returns the current URL.

-

Use window.location.href to get current URL.

-
const currentURL = () => window.location.href;
+      }

logo 30 seconds of code

Curated collection of useful JavaScript snippets
that you can understand in 30 seconds or less.

Snippets for Beginners

The following section is aimed towards individuals who are at the start of their web developer journey. Each snippet in the next section is simple yet very educational for newcomers. This section is by no means a complete resource for learning modern JavaScript. However, it is enough to grasp some common concepts and use cases. We also strongly recommend checking out MDN web docs as a learning resource.


currentURL

Returns the current URL.

Use window.location.href to get current URL.

const currentURL = () => window.location.href;
 
currentURL(); // 'https://google.com'
-
-

everyNth

-

Returns every nth element in an array.

-

Use Array.filter() to create a new array that contains every nth element of a given array.

-
const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);
+

everyNth

Returns every nth element in an array.

Use Array.filter() to create a new array that contains every nth element of a given array.

const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);
 
everyNth([1, 2, 3, 4, 5, 6], 2); // [ 2, 4, 6 ]
-
-

factorial

-

Calculates the factorial of a number.

-

Use recursion. -If n is less than or equal to 1, return 1. -Otherwise, return the product of n and the factorial of n - 1. -Throws an exception if n is a negative number.

-
const factorial = n =>
+

factorial

Calculates the factorial of a number.

Use recursion. If n is less than or equal to 1, return 1. Otherwise, return the product of n and the factorial of n - 1. Throws an exception if n is a negative number.

const factorial = n =>
   n < 0
     ? (() => {
         throw new TypeError('Negative numbers are not allowed!');
       })()
     : n <= 1 ? 1 : n * factorial(n - 1);
 
factorial(6); // 720
-
-

fibonacci

-

Generates an array, containing the Fibonacci sequence, up until the nth term.

-

Create an empty array of the specific length, initializing the first two values (0 and 1). -Use Array.reduce() to add values into the array, using the sum of the last two values, except for the first two.

-
const fibonacci = n =>
+

fibonacci

Generates an array, containing the Fibonacci sequence, up until the nth term.

Create an empty array of the specific length, initializing the first two values (0 and 1). Use Array.reduce() to add values into the array, using the sum of the last two values, except for the first two.

const fibonacci = n =>
   Array.from({ length: n }).reduce(
     (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),
     []
   );
 
fibonacci(6); // [0, 1, 1, 2, 3, 5]
-
-

filterNonUnique

-

Filters out the non-unique values in an array.

-

Use Array.filter() for an array containing only the unique values.

-
const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));
+

filterNonUnique

Filters out the non-unique values in an array.

Use Array.filter() for an array containing only the unique values.

const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));
 
filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1,3,5]
-
-

gcd

-

Calculates the greatest common divisor between two or more numbers/arrays.

-

The inner _gcd function uses recursion. -Base case is when y equals 0. In this case, return x. -Otherwise, return the GCD of y and the remainder of the division x/y.

-
const gcd = (...arr) => {
+

gcd

Calculates the greatest common divisor between two or more numbers/arrays.

The inner _gcd function uses recursion. Base case is when y equals 0. In this case, return x. Otherwise, return the GCD of y and the remainder of the division x/y.

const gcd = (...arr) => {
   const _gcd = (x, y) => (!y ? x : gcd(y, x % y));
   return [...arr].reduce((a, b) => _gcd(a, b));
 };
 
gcd(8, 36); // 4
 gcd(...[12, 8, 32]); // 4
-
-

getMeridiemSuffixOfInteger

-

Converts an integer to a suffixed string, adding am or pm based on its value.

-

Use the modulo operator (%) and conditional checks to transform an integer to a stringified 12-hour format with meridiem suffix.

-
const getMeridiemSuffixOfInteger = num =>
+

getMeridiemSuffixOfInteger

Converts an integer to a suffixed string, adding am or pm based on its value.

Use the modulo operator (%) and conditional checks to transform an integer to a stringified 12-hour format with meridiem suffix.

const getMeridiemSuffixOfInteger = num =>
   num === 0 || num === 24
     ? 12 + 'am'
     : num === 12 ? 12 + 'pm' : num < 12 ? num % 12 + 'am' : num % 12 + 'pm';
@@ -164,133 +89,50 @@ Otherwise, return the GCD of y and the remainder of the division getMeridiemSuffixOfInteger(11); // "11am"
 getMeridiemSuffixOfInteger(13); // "1pm"
 getMeridiemSuffixOfInteger(25); // "1pm"
-
-

hasClass

-

Returns true if the element has the specified class, false otherwise.

-

Use element.classList.contains() to check if the element has the specified class.

-
const hasClass = (el, className) => el.classList.contains(className);
+

hasClass

Returns true if the element has the specified class, false otherwise.

Use element.classList.contains() to check if the element has the specified class.

const hasClass = (el, className) => el.classList.contains(className);
 
hasClass(document.querySelector('p.special'), 'special'); // true
-
-

isDivisible

-

Checks if the first numeric argument is divisible by the second one.

-

Use the modulo operator (%) to check if the remainder is equal to 0.

-
const isDivisible = (dividend, divisor) => dividend % divisor === 0;
+

isDivisible

Checks if the first numeric argument is divisible by the second one.

Use the modulo operator (%) to check if the remainder is equal to 0.

const isDivisible = (dividend, divisor) => dividend % divisor === 0;
 
isDivisible(6, 3); // true
-
-

isEven

-

Returns true if the given number is even, false otherwise.

-

Checks whether a number is odd or even using the modulo (%) operator. -Returns true if the number is even, false if the number is odd.

-
const isEven = num => num % 2 === 0;
+

isEven

Returns true if the given number is even, false otherwise.

Checks whether a number is odd or even using the modulo (%) operator. Returns true if the number is even, false if the number is odd.

const isEven = num => num % 2 === 0;
 
isEven(3); // false
-
-

isPrime

-

Checks if the provided integer is a prime number.

-

Check numbers from 2 to the square root of the given number. -Return false if any of them divides the given number, else return true, unless the number is less than 2.

-
const isPrime = num => {
+

isPrime

Checks if the provided integer is a prime number.

Check numbers from 2 to the square root of the given number. Return false if any of them divides the given number, else return true, unless the number is less than 2.

const isPrime = num => {
   const boundary = Math.floor(Math.sqrt(num));
   for (var i = 2; i <= boundary; i++) if (num % i === 0) return false;
   return num >= 2;
 };
 
isPrime(11); // true
-
-

last

-

Returns the last element in an array.

-

Use arr.length - 1 to compute the index of the last element of the given array and returning it.

-
const last = arr => arr[arr.length - 1];
+

last

Returns the last element in an array.

Use arr.length - 1 to compute the index of the last element of the given array and returning it.

const last = arr => arr[arr.length - 1];
 
last([1, 2, 3]); // 3
-
-

lcm

-

Returns the least common multiple of two or more numbers.

-

Use the greatest common divisor (GCD) formula and the fact that lcm(x,y) = x * y / gcd(x,y) to determine the least common multiple. -The GCD formula uses recursion.

-
const lcm = (...arr) => {
+

lcm

Returns the least common multiple of two or more numbers.

Use the greatest common divisor (GCD) formula and the fact that lcm(x,y) = x * y / gcd(x,y) to determine the least common multiple. The GCD formula uses recursion.

const lcm = (...arr) => {
   const gcd = (x, y) => (!y ? x : gcd(y, x % y));
   const _lcm = (x, y) => x * y / gcd(x, y);
   return [...arr].reduce((a, b) => _lcm(a, b));
 };
 
lcm(12, 7); // 84
 lcm(...[1, 3, 4, 5]); // 60
-
-

maxN

-

Returns the n maximum elements from the provided array. If n is greater than or equal to the provided array's length, then return the original array(sorted in descending order).

-

Use Array.sort() combined with the spread operator (...) to create a shallow clone of the array and sort it in descending order. -Use Array.slice() to get the specified number of elements. -Omit the second argument, n, to get a one-element array.

-
const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n);
+

maxN

Returns the n maximum elements from the provided array. If n is greater than or equal to the provided array's length, then return the original array(sorted in descending order).

Use Array.sort() combined with the spread operator (...) to create a shallow clone of the array and sort it in descending order. Use Array.slice() to get the specified number of elements. Omit the second argument, n, to get a one-element array.

const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n);
 
maxN([1, 2, 3]); // [3]
 maxN([1, 2, 3], 2); // [3,2]
-
-

minN

-

Returns the n minimum elements from the provided array. If n is greater than or equal to the provided array's length, then return the original array(sorted in ascending order).

-

Use Array.sort() combined with the spread operator (...) to create a shallow clone of the array and sort it in ascending order. -Use Array.slice() to get the specified number of elements. -Omit the second argument, n, to get a one-element array.

-
const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);
+

minN

Returns the n minimum elements from the provided array. If n is greater than or equal to the provided array's length, then return the original array(sorted in ascending order).

Use Array.sort() combined with the spread operator (...) to create a shallow clone of the array and sort it in ascending order. Use Array.slice() to get the specified number of elements. Omit the second argument, n, to get a one-element array.

const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);
 
minN([1, 2, 3]); // [1]
 minN([1, 2, 3], 2); // [1,2]
-
-

nthElement

-

Returns the nth element of an array.

-

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

-
const nthElement = (arr, n = 0) => (n > 0 ? arr.slice(n, n + 1) : arr.slice(n))[0];
+

nthElement

Returns the nth element of an array.

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

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

randomIntegerInRange

-

Returns a random integer in the specified range.

-

Use Math.random() to generate a random number and map it to the desired range, using Math.floor() to make it an integer.

-
const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
+

randomIntegerInRange

Returns a random integer in the specified range.

Use Math.random() to generate a random number and map it to the desired range, using Math.floor() to make it an integer.

const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
 
randomIntegerInRange(0, 5); // 2
-
-

reverseString

-

Reverses a string.

-

Use the spread operator (...) and Array.reverse() to reverse the order of the characters in the string. -Combine characters to get a string using String.join('').

-
const reverseString = str => [...str].reverse().join('');
+

reverseString

Reverses a string.

Use the spread operator (...) and Array.reverse() to reverse the order of the characters in the string. Combine characters to get a string using String.join('').

const reverseString = str => [...str].reverse().join('');
 
reverseString('foobar'); // 'raboof'
-
-

sample

-

Returns a random element from an array.

-

Use Math.random() to generate a random number, multiply it by length and round it of to the nearest whole number using Math.floor(). -This method also works with strings.

-
const sample = arr => arr[Math.floor(Math.random() * arr.length)];
+

sample

Returns a random element from an array.

Use Math.random() to generate a random number, multiply it by length and round it of to the nearest whole number using Math.floor(). This method also works with strings.

const sample = arr => arr[Math.floor(Math.random() * arr.length)];
 
sample([3, 7, 9, 11]); // 9
-
-

similarity

-

Returns an array of elements that appear in both arrays.

-

Use Array.filter() to remove values that are not part of values, determined using Array.includes().

-
const similarity = (arr, values) => arr.filter(v => values.includes(v));
+

similarity

Returns an array of elements that appear in both arrays.

Use Array.filter() to remove values that are not part of values, determined using Array.includes().

const similarity = (arr, values) => arr.filter(v => values.includes(v));
 
similarity([1, 2, 3], [1, 2, 4]); // [1,2]
-
-

sum

-

Returns the sum of two or more numbers/arrays.

-

Use Array.reduce() to add each value to an accumulator, initialized with a value of 0.

-
const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0);
+

sum

Returns the sum of two or more numbers/arrays.

Use Array.reduce() to add each value to an accumulator, initialized with a value of 0.

const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0);
 
sum(...[1, 2, 3, 4]); // 10
-
-

tail

-

Returns all elements in an array except for the first one.

-

Return Array.slice(1) if the array's length is more than 1, otherwise, return the whole array.

-
const tail = arr => (arr.length > 1 ? arr.slice(1) : arr);
+

tail

Returns all elements in an array except for the first one.

Return Array.slice(1) if the array's length is more than 1, otherwise, return the whole array.

const tail = arr => (arr.length > 1 ? arr.slice(1) : arr);
 
tail([1, 2, 3]); // [2,3]
 tail([1]); // [1]
-
-

truncateString

-

Truncates a string up to a specified length.

-

Determine if the string's length is greater than num. -Return the string truncated to the desired length, with '...' appended to the end or the original string.

-
const truncateString = (str, num) =>
+

truncateString

Truncates a string up to a specified length.

Determine if the string's length is greater than num. Return the string truncated to the desired length, with '...' appended to the end or the original string.

const truncateString = (str, num) =>
   str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str;
 
truncateString('boomerang', 7); // 'boom...'
-
-
-
- -
- - - +

\ No newline at end of file diff --git a/docs/index.html b/docs/index.html index db7503e7e..a85fa3212 100644 --- a/docs/index.html +++ b/docs/index.html @@ -76,32 +76,71 @@
-

difference

-

Returns the difference between two arrays.

-

Create a Set from b, then use Array.filter() on a to only keep values not contained in b.

-
const difference = (a, b) => {
-  const s = new Set(b);
-  return a.filter(x => !s.has(x));
+      

binomialCoefficient

+

Evaluates the binomial coefficient of two integers n and k.

+

Use Number.isNaN() to check if any of the two values is NaN. +Check if k is less than 0, greater than or equal to n, equal to 1 or n - 1 and return the appropriate result. +Check if n - k is less than k and switch their values accordingly. +Loop from 2 through k and calculate the binomial coefficient. +Use Math.round() to account for rounding errors in the calculation.

+
const binomialCoefficient = (n, k) => {
+  if (Number.isNaN(n) || Number.isNaN(k)) return NaN;
+  if (k < 0 || k > n) return 0;
+  if (k === 0 || k === n) return 1;
+  if (k === 1 || k === n - 1) return n;
+  if (n - k < k) k = n - k;
+  let res = n;
+  for (let j = 2; j <= k; j++) res *= (n - j + 1) / j;
+  return Math.round(res);
 };
-
difference([1, 2, 3], [1, 2, 4]); // [3]
+
binomialCoefficient(8, 2); // 28
 
-

hasFlags

-

Check if the current process's arguments contain the specified flags.

-

Use Array.every() and Array.includes() to check if process.argv contains all the specified flags. -Use a regular expression to test if the specified flags are prefixed with - or -- and prefix them accordingly.

-
const hasFlags = (...flags) =>
-  flags.every(flag => process.argv.includes(/^-{1,2}/.test(flag) ? flag : '--' + flag));
-
// node myScript.js -s --test --cool=true
-hasFlags('-s'); // true
-hasFlags('--test', 'cool=true', '-s'); // true
-hasFlags('special'); // false
+

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)
 
-

isPlainObject

-

Checks if the provided value is an object created by the Object constructor.

-

Check if the provided value is truthy, use typeof to check if it is an object and Object.constructor to make sure the constructor is equal to Object.

-
const isPlainObject = val => !!val && typeof val === 'object' && val.constructor === Object;
-
isPlainObject({ a: 1 }); // true
-isPlainObject(new Map()); // false
+

runAsync

+

Runs a function in a separate thread by using a Web Worker, allowing long running functions to not block the UI.

+

Create a new Worker using a Blob object URL, the contents of which should be the stringified version of the supplied function. +Immediately post the return value of calling the function back. +Return a promise, listening for onmessage and onerror events and resolving the data posted back from the worker, or throwing an error.

+
const runAsync = fn => {
+  const worker = new Worker(
+    URL.createObjectURL(new Blob([`postMessage((${fn})());`]), {
+      type: 'application/javascript; charset=utf-8'
+    })
+  );
+  return new Promise((res, rej) => {
+    worker.onmessage = ({ data }) => {
+      res(data), worker.terminate();
+    };
+    worker.onerror = err => {
+      rej(err), worker.terminate();
+    };
+  });
+};
+
const longRunningFunction = () => {
+  let result = 0;
+  for (let i = 0; i < 1000; i++) {
+    for (let j = 0; j < 700; j++) {
+      for (let k = 0; k < 300; k++) {
+        result = result + i + j + k;
+      }
+    }
+  }
+  return result;
+};
+/*
+  NOTE: Since the function is running in a different context, closures are not supported.
+  The function supplied to `runAsync` gets stringified, so everything becomes literal.
+  All variables and functions must be defined inside.
+*/
+runAsync(longRunningFunction).then(console.log); // 209685000000
+runAsync(() => 10 ** 3).then(console.log); // 1000
+let outsideVariable = 50;
+runAsync(() => typeof outsideVariable).then(console.log); // 'undefined'
 

diff --git a/scripts/web.js b/scripts/web.js index 472b3e361..e52df1529 100644 --- a/scripts/web.js +++ b/scripts/web.js @@ -281,8 +281,24 @@ try { beginnerOutput += `${beginnerEndPart}`; - // Generate 'beginner.html' file - fs.writeFileSync(path.join(docsPath, 'beginner.html'), beginnerOutput); + // Generate and minify 'beginner.html' file + const minifiedBeginnerOutput = minify(beginnerOutput, { + collapseBooleanAttributes: true, + collapseWhitespace: true, + decodeEntities: false, + minifyCSS: true, + minifyJS: true, + keepClosingSlash: true, + processConditionalComments: true, + removeAttributeQuotes: false, + removeComments: true, + removeEmptyAttributes: false, + removeOptionalTags: false, + removeScriptTypeAttributes: false, + removeStyleLinkTypeAttributes: false, + trimCustomFragments: true + }); + fs.writeFileSync(path.join(docsPath, 'beginner.html'), minifiedBeginnerOutput); console.log(`${chalk.green('SUCCESS!')} beginner.html file generated!`); } catch (err) { @@ -330,8 +346,27 @@ try { archivedOutput += `${archivedEndPart}`; - // Generate 'beginner.html' file - fs.writeFileSync(path.join(docsPath, 'archive.html'), archivedOutput); + + + // Generate and minify 'archive.html' file + const minifiedArchivedOutput = minify(archivedOutput, { + collapseBooleanAttributes: true, + collapseWhitespace: true, + decodeEntities: false, + minifyCSS: true, + minifyJS: true, + keepClosingSlash: true, + processConditionalComments: true, + removeAttributeQuotes: false, + removeComments: true, + removeEmptyAttributes: false, + removeOptionalTags: false, + removeScriptTypeAttributes: false, + removeStyleLinkTypeAttributes: false, + trimCustomFragments: true + }); + + fs.writeFileSync(path.join(docsPath, 'archive.html'), minifiedArchivedOutput); console.log(`${chalk.green('SUCCESS!')} archive.html file generated!`); } catch (err) {