From 6a425c6b2790e494a31239a2dc4270fc76d9792c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Feje=C5=A1?= Date: Sat, 7 Apr 2018 18:44:54 +0200 Subject: [PATCH] minification for beginner.html --- docs/beginner.html | 208 ++++++--------------------------------------- docs/index.html | 96 ++++++++++++++------- scripts/web.js | 21 ++++- 3 files changed, 108 insertions(+), 217 deletions(-) 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 8ce2b51d1..a85fa3212 100644 --- a/docs/index.html +++ b/docs/index.html @@ -76,39 +76,71 @@
-

get

-

Retrieve a set of properties indicated by the given selectors from an object.

-

Use Array.map() for each selector, String.replace() to replace square brackets with dots, String.split('.') to split each selector, Array.filter() to remove empty values and Array.reduce() to get the value indicated by it.

-
const get = (from, ...selectors) =>
-  [...selectors].map(s =>
-    s
-      .replace(/\[([^\[\]]*)\]/g, '.$1.')
-      .split('.')
-      .filter(t => t !== '')
-      .reduce((prev, cur) => prev && prev[cur], from)
+      

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);
+};
+
binomialCoefficient(8, 2); // 28
+
+

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

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'
+    })
   );
-
const obj = { selector: { to: { val: 'val to select' } }, target: [1, 2, { a: 'test' }] };
-get(obj, 'selector.to.val', 'target[0]', 'target[2].a'); // ['val to select', 1, 'test']
-
-

toDecimalMark

-

Use toLocaleString() to convert a float-point arithmetic to the Decimal mark form. It makes a comma separated string from a number.

-
const toDecimalMark = num => num.toLocaleString('en-US');
-
toDecimalMark(12305030388.9087); // "12,305,030,388.909"
-
-

toKebabCase

-

Converts a string to kebab case.

-

Break the string into words and combine them adding - as a separator, using a regexp.

-
const toKebabCase = str =>
-  str &&
-  str
-    .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
-    .map(x => x.toLowerCase())
-    .join('-');
-
toKebabCase('camelCase'); // 'camel-case'
-toKebabCase('some text'); // 'some-text'
-toKebabCase('some-mixed_string With spaces_underscores-and-hyphens'); // 'some-mixed-string-with-spaces-underscores-and-hyphens'
-toKebabCase('AllThe-small Things'); // "all-the-small-things"
-toKebabCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML'); // "i-am-listening-to-fm-while-loading-different-url-on-my-browser-and-also-editing-xml-and-html"
+  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 e81a6c840..5b8103bbf 100644 --- a/scripts/web.js +++ b/scripts/web.js @@ -273,8 +273,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) { @@ -341,6 +357,7 @@ try { removeStyleLinkTypeAttributes: false, trimCustomFragments: true }); + fs.writeFileSync(path.join(docsPath, 'archive.html'), minifiedArchivedOutput); console.log(`${chalk.green('SUCCESS!')} archive.html file generated!`);