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 @@ - - -
- - - - -Curated collection of useful JavaScript snippets
that you can understand in 30 seconds or less.
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.
Returns the current URL.
-Use window.location.href to get current URL.
const currentURL = () => window.location.href; + }
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.hrefto 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
-nis less than or equal to1, return1. -Otherwise, return the product ofnand the factorial ofn - 1. -Throws an exception ifnis a negative number.const factorial = n => +factorial
Calculates the factorial of a number.
Use recursion. If
nis less than or equal to1, return1. Otherwise, return the product ofnand the factorial ofn - 1. Throws an exception ifnis 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 (
-0and1). -UseArray.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 (
0and1). UseArray.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
-_gcdfunction uses recursion. -Base case is whenyequals0. In this case, returnx. -Otherwise, return the GCD ofyand the remainder of the divisionx/y.const gcd = (...arr) => { +gcd
Calculates the greatest common divisor between two or more numbers/arrays.
The inner
_gcdfunction uses recursion. Base case is whenyequals0. In this case, returnx. Otherwise, return the GCD ofyand the remainder of the divisionx/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
-amorpmbased 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
amorpmbased 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-yand the remainder of the divisiongetMeridiemSuffixOfInteger(11); // "11am" getMeridiemSuffixOfInteger(13); // "1pm" getMeridiemSuffixOfInteger(25); // "1pm" - hasClass
-Returns
-trueif the element has the specified class,falseotherwise.Use
-element.classList.contains()to check if the element has the specified class.const hasClass = (el, className) => el.classList.contains(className); +hasClass
Returns
trueif the element has the specified class,falseotherwise.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 to0.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 to0.const isDivisible = (dividend, divisor) => dividend % divisor === 0;isDivisible(6, 3); // true --isEven
-Returns
-trueif the given number is even,falseotherwise.Checks whether a number is odd or even using the modulo (
-%) operator. -Returnstrueif the number is even,falseif the number is odd.const isEven = num => num % 2 === 0; +isEven
Returns
trueif the given number is even,falseotherwise.Checks whether a number is odd or even using the modulo (
%) operator. Returnstrueif the number is even,falseif 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
-2to the square root of the given number. -Returnfalseif any of them divides the given number, else returntrue, unless the number is less than2.const isPrime = num => { +isPrime
Checks if the provided integer is a prime number.
Check numbers from
2to the square root of the given number. Returnfalseif any of them divides the given number, else returntrue, unless the number is less than2.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 - 1to 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 - 1to 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
-nmaximum elements from the provided array. Ifnis 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. -UseArray.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
nmaximum elements from the provided array. Ifnis 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. UseArray.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
-nminimum elements from the provided array. Ifnis 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. -UseArray.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
nminimum elements from the provided array. Ifnis 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. UseArray.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, usingMath.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, usingMath.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 (
-...) andArray.reverse()to reverse the order of the characters in the string. -Combine characters to get a string usingString.join('').const reverseString = str => [...str].reverse().join(''); +reverseString
Reverses a string.
Use the spread operator (
...) andArray.reverse()to reverse the order of the characters in the string. Combine characters to get a string usingString.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 bylengthand round it of to the nearest whole number usingMath.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 bylengthand round it of to the nearest whole number usingMath.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 ofvalues, determined usingArray.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 ofvalues, determined usingArray.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 of0.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 of0.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'slengthis more than1, 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'slengthis more than1, 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
-lengthis greater thannum. -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
lengthis greater thannum. 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...' --