diff --git a/docs/beginner.html b/docs/beginner.html index 4a6ded7d2..3e6c16604 100644 --- a/docs/beginner.html +++ b/docs/beginner.html @@ -17,7 +17,7 @@

logo 30 seconds of code

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

- +
@@ -27,6 +27,189 @@
-
+

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([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 =>
+  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 =>
+  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([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) => {
+  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 =>
+  num === 0 || num === 24
+    ? 12 + 'am'
+    : num === 12 ? 12 + 'pm' : num < 12 ? num % 12 + 'am' : num % 12 + 'pm';
+
getMeridiemSuffixOfInteger(0); // "12am"
+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(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(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(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 => {
+  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
+
+

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([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([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(['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(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('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([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([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(...[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([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) =>
+  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/scripts/web.js b/scripts/web.js index b72a14be6..6f74c8578 100644 --- a/scripts/web.js +++ b/scripts/web.js @@ -51,11 +51,11 @@ const snippetsPath = './snippets', docsPath = './docs'; // Set variables for script let snippets = {}, - beginnerSnippets = ['everyNth', 'filterNonUnique', 'last', 'maxN', 'minN', 'nthElement', 'sample', 'similarity', 'tail', 'currentURL', 'hasClass', 'getMeridiemSuffixOfInteger', 'factorial', 'fibonacci', 'gcd', 'isDivisible', 'isEven', 'isPrime', 'lcm', 'randomIntegerInRange', 'sum', 'reverseString', 'truncateString'], + beginnerSnippetNames = ['everyNth', 'filterNonUnique', 'last.md', 'maxN', 'minN', 'nthElement', 'sample', 'similarity', 'tail', 'currentURL', 'hasClass', 'getMeridiemSuffixOfInteger', 'factorial', 'fibonacci', 'gcd', 'isDivisible', 'isEven', 'isPrime', 'lcm', 'randomIntegerInRange', 'sum', 'reverseString', 'truncateString'], startPart = '', endPart = '', output = '', - startBegginerPart = '', + startBeginnerPart = '', endBegginerPart = '', beginnerOutput = '', pagesOutput = []; @@ -64,6 +64,7 @@ let snippets = {}, console.time('Webber'); // Synchronously read all snippets and sort them as necessary (case-insensitive) snippets = util.readSnippets(snippetsPath); + // Load static parts for the index.html file try { startPart = fs.readFileSync(path.join(staticPartsPath, 'page-start.html'), 'utf8'); @@ -171,6 +172,29 @@ try { // Add the static part beginnerOutput += `${startBeginnerPart + '\n'}`; + // Filter begginer snippets + const filteredBeginnerSnippets = Object.keys(snippets) + .filter(key => beginnerSnippetNames.map(name => name+'.md').includes(key)) + .reduce((obj, key) => { + obj[key] = snippets[key]; + return obj; + }, {}); + + console.log(filteredBeginnerSnippets); + for (let snippet of Object.entries(filteredBeginnerSnippets)) + beginnerOutput += + '
' + + md + .render(`\n${snippets[snippet[0]]}`) + .replace(/

/g, `${snippet[1].includes('advanced')?'advanced':''}

`) + .replace(/<\/h3>/g, '
') + .replace(/
([^\0]*?)<\/code><\/pre>/gm, (match, p1) => `
${Prism.highlight(unescapeHTML(p1), Prism.languages.javascript)}
`) + .replace(/<\/pre>\s+
📋 Copy to clipboard' +
+          '
'; + + beginnerOutput += '
' + // begginer snippet goes here. @@ -179,7 +203,7 @@ try { beginnerOutput += `${endBeginnerPart}`; - // Generate + // Generate 'beginner.html' file fs.writeFileSync(path.join(docsPath, 'beginner.html'), beginnerOutput); diff --git a/static-parts/beginner-page-start.html b/static-parts/beginner-page-start.html index c6bad26ea..aefd3736f 100644 --- a/static-parts/beginner-page-start.html +++ b/static-parts/beginner-page-start.html @@ -17,7 +17,7 @@

logo 30 seconds of code

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

- +