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 @@ - - -
- - - - -Curated collection of useful JavaScript snippets
that you can understand in 30 seconds or less.
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.
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) => { + }
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 orArray.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
-nis even, returnn/2. Otherwise, return3n+1.const collatz = n => (n % 2 === 0 ? n / 2 : 3 * n + 1); +collatz
Applies the Collatz algorithm.
If
nis even, returnn/2. Otherwise, return3n+1.const collatz = n => (n % 2 === 0 ? n / 2 : 3 * n + 1);collatz(8); // 4 --countVowels
-Retuns
-numberof vowels in provided string.Use a regular expression to count the number of vowels
-(A, E, I, O, U)in astring.const countVowels = str => (str.match(/[aeiou]/gi) || []).length; +countVowels
Retuns
numberof vowels in provided string.Use a regular expression to count the number of vowels
(A, E, I, O, U)in astring.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 totruereturns only the prime factors ofnum. -Ifnumis1or0returns an empty array. -Ifnumis less than0returns all the factors of-inttogether with their additive inverses.Use
-Array.from(),Array.map()andArray.filter()to find all the factors ofnum. -If givennumis negative, useArray.reduce()to add the additive inverses to the array. -Return all results ifprimesisfalse, else determine and return only the prime factors usingisPrimeandArray.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 totruereturns only the prime factors ofnum. Ifnumis1or0returns an empty array. Ifnumis less than0returns all the factors of-inttogether with their additive inverses.Use
Array.from(),Array.map()andArray.filter()to find all the factors ofnum. If givennumis negative, useArray.reduce()to add the additive inverses to the array. Return all results ifprimesisfalse, else determine and return only the prime factors usingisPrimeandArray.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(0andnuminclusive).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(0andnuminclusive).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 (
-0and1). -UseArray.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 (
0and1). UseArray.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
-numcan be divided bydivisor(integer or fractional) without getting a fractional answer. -Works for both negative and positive integers.If
-divisoris-1or1returnInfinity. -Ifdivisoris-0or0return0. -Otherwise, keep dividingnumwithdivisorand incrementingi, 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
numcan be divided bydivisor(integer or fractional) without getting a fractional answer. Works for both negative and positive integers.If
divisoris-1or1returnInfinity. Ifdivisoris-0or0return0. Otherwise, keep dividingnumwithdivisorand incrementingi, 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
-DELETErequest to the passed URL.Use
-XMLHttpRequestweb api to make adeleterequest to the givenurl. -Handle theonloadevent, by running the providedcallbackfunction. -Handle theonerrorevent, by running the providederrfunction. -Omit the third argument,errto log the request to the console's error stream by default.const httpDelete = (url, callback, err = console.error) => { +httpDelete
Makes a
DELETErequest to the passed URL.Use
XMLHttpRequestweb api to make adeleterequest to the givenurl. Handle theonloadevent, by running the providedcallbackfunction. Handle theonerrorevent, by running the providederrfunction. Omit the third argument,errto 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,errto log the request to the console's erhttpDelete('https://website.com/users/123', request => { console.log(request.responseText); }); // 'Deletes a user from the database' --httpPut
-Makes a
-PUTrequest to the passed URL.Use
-XMLHttpRequestweb api to make aputrequest to the givenurl. -Set the value of anHTTPrequest header withsetRequestHeadermethod. -Handle theonloadevent, by running the providedcallbackfunction. -Handle theonerrorevent, by running the providederrfunction. -Omit the last argument,errto log the request to the console's error stream by default.const httpPut = (url, data, callback, err = console.error) => { +httpPut
Makes a
PUTrequest to the passed URL.Use
XMLHttpRequestweb api to make aputrequest to the givenurl. Set the value of anHTTPrequest header withsetRequestHeadermethod. Handle theonloadevent, by running the providedcallbackfunction. Handle theonerrorevent, by running the providederrfunction. Omit the last argument,errto 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,-errto 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, returntrueotherwisefalse.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, returntrueotherwisefalse.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
-patternmatches withstr.Use
-String.toLowerCase()to convert both strings to lowercase, then loop throughstrand determine if it contains all characters ofpatternand in the correct order. -Adapted from here.const isSimilar = (pattern, str) => +isSimilar
Determines if the
patternmatches withstr.Use
String.toLowerCase()to convert both strings to lowercase, then loop throughstrand determine if it contains all characters ofpatternand 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
-string1tostring2. -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
string1tostring2. 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.filterand 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 parameterdescis truthy, return array sorts in descending order.const quickSort = ([n, ...nums], desc) => +quickSort
QuickSort an Array (ascending sort by default).
Use recursion. Use
Array.filterand 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 parameterdescis truthy, return array sorts in descending order.const quickSort = ([n, ...nums], desc) => isNaN(n) ? [] : [ @@ -330,23 +200,10 @@ If the parameterdescis 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
-strreplaced byrepl.Use
-String.replace()with a regexp to replace all vowels instr. -Omotreplto use a default value of''.const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi,repl); +removeVowels
Returns all the vowels in a
strreplaced byrepl.Use
String.replace()with a regexp to replace all vowels instr. Omotreplto 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,
-OPERATORSto specify each operator's matching mathematical operation. -UseString.replace()with a regular expression to replace^with**,String.split()to tokenize the string andArray.filter()to remove empty tokens. -UseArray.forEach()to parse eachsymbol, evaluate it as a numeric value or operator and solve the mathematical expression. -Numeric values are converted to floating point numbers and pushed to astack, while operators are evaluated using theOPERATORSdictionary and pop elements from thestackto 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,
OPERATORSto specify each operator's matching mathematical operation. UseString.replace()with a regular expression to replace^with**,String.split()to tokenize the string andArray.filter()to remove empty tokens. UseArray.forEach()to parse eachsymbol, evaluate it as a numeric value or operator and solve the mathematical expression. Numeric values are converted to floating point numbers and pushed to astack, while operators are evaluated using theOPERATORSdictionary and pop elements from thestackto 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 asta };solveRPN('15 7 1 1 + - / 3 * 2 1 1 + + -'); // 5 solveRPN('2 3 ^'); // 8 --speechSynthesis
-Performs speech synthesis (experimental).
-Use
-SpeechSynthesisUtterance.voiceandwindow.speechSynthesis.getVoices()to convert a message to speech. -Usewindow.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.voiceandwindow.speechSynthesis.getVoices()to convert a message to speech. Usewindow.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 --