From a96ca3daf89678bba812e0ef8d4e6973d63922c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Feje=C5=A1?= Date: Sat, 7 Apr 2018 18:42:43 +0200 Subject: [PATCH] minification for archive.html --- docs/archive.html | 196 +++++---------------------------------------- docs/beginner.html | 2 +- docs/index.html | 65 +++++++-------- scripts/web.js | 22 ++++- 4 files changed, 72 insertions(+), 213 deletions(-) diff --git a/docs/archive.html b/docs/archive.html index e841ac185..f319124cf 100644 --- a/docs/archive.html +++ b/docs/archive.html @@ -1,28 +1,4 @@ - - - - - - - - Snippets for Beginners - 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 101a5db4c..162c1f056 100644 --- a/docs/beginner.html +++ b/docs/beginner.html @@ -93,7 +93,7 @@
-

Beginner snippets

+

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.


diff --git a/docs/index.html b/docs/index.html index 3fd8cfb4e..8ce2b51d1 100644 --- a/docs/index.html +++ b/docs/index.html @@ -76,42 +76,39 @@
-

createElement

-

Creates an element from a string (without appending it to the document). -If the given string contains multiple elements, only the first one will be returned.

-

Use document.createElement() to create a new element. -Set its innerHTML to the string supplied as the argument. -Use ParentNode.firstElementChild to return the element version of the string.

-
const createElement = str => {
-  const el = document.createElement('div');
-  el.innerHTML = str;
-  return el.firstElementChild;
-};
-
const el = createElement(
-  `<div class="container">
-    <p>Hello!</p>
-  </div>`
-);
-console.log(el.className); // 'container'
+      

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)
+  );
+
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']
 
-

isSymbol

-

Checks if the given argument is a symbol.

-

Use typeof to check if a value is classified as a symbol primitive.

-
const isSymbol = val => typeof val === 'symbol';
-
isSymbol(Symbol('x')); // true
+

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

scrollToTop

-

Smooth-scrolls to the top of the page.

-

Get distance from top using document.documentElement.scrollTop or document.body.scrollTop. -Scroll by a fraction of the distance from the top. Use window.requestAnimationFrame() to animate the scrolling.

-
const scrollToTop = () => {
-  const c = document.documentElement.scrollTop || document.body.scrollTop;
-  if (c > 0) {
-    window.requestAnimationFrame(scrollToTop);
-    window.scrollTo(0, c - c / 8);
-  }
-};
-
scrollToTop();
+

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"
 

diff --git a/scripts/web.js b/scripts/web.js index 93f3c0406..e81a6c840 100644 --- a/scripts/web.js +++ b/scripts/web.js @@ -322,8 +322,26 @@ 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) {