{ "data": [ { "id": "binarySearch", "type": "snippet", "attributes": { "fileName": "binarySearch.md", "text": "Use recursion. Similar to `Array.indexOf()` that finds the index of a value within an array.\nThe 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()`.\n\nSearch a sorted array by repeatedly dividing the search interval in half.\nBegin with an interval covering the whole array.\nIf 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.\nRepeatedly 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`.", "codeBlocks": [ "const binarySearch = (arr, val, start = 0, end = arr.length - 1) => {\n if (start > end) return -1;\n const mid = Math.floor((start + end) / 2);\n if (arr[mid] > val) return binarySearch(arr, val, start, mid - 1);\n if (arr[mid] < val) return binarySearch(arr, val, mid + 1, end);\n return mid;\n};", "binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 6); // 2\nbinarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 21); // -1" ], "tags": [] }, "meta": { "archived": true, "hash": "2e9aff504a7716c4b49b30702ee3b922c707fac70efc099422ae5ba5a7d0e009" } }, { "id": "cleanObj", "type": "snippet", "attributes": { "fileName": "cleanObj.md", "text": "Removes any properties except the ones specified from a JSON object.\n\nUse `Object.keys()` method to loop over given JSON object and deleting keys that are not included in given array.\nIf you pass a special key,`childIndicator`, it will search deeply apply the function to inner objects, too.", "codeBlocks": [ "const cleanObj = (obj, keysToKeep = [], childIndicator) => {\n Object.keys(obj).forEach(key => {\n if (key === childIndicator) {\n cleanObj(obj[key], keysToKeep, childIndicator);\n } else if (!keysToKeep.includes(key)) {\n delete obj[key];\n }\n });\n return obj;\n};", "const testObj = { a: 1, b: 2, children: { a: 1, b: 2 } };\ncleanObj(testObj, ['a'], 'children'); // { a: 1, children : { a: 1}}" ], "tags": [] }, "meta": { "archived": true, "hash": "ec33abb9423c49520400becb5183d87b37bbf6eb60012673c8df5a0a672a6af0" } }, { "id": "collatz", "type": "snippet", "attributes": { "fileName": "collatz.md", "text": "Applies the Collatz algorithm.\n\nIf `n` is even, return `n/2`. Otherwise, return `3n+1`.", "codeBlocks": [ "const collatz = n => (n % 2 === 0 ? n / 2 : 3 * n + 1);", "collatz(8); // 4" ], "tags": [] }, "meta": { "archived": true, "hash": "650c91d557244ee0e3f64a00d457d63b47271aa0b963728bfc37dc5c3c88c67e" } }, { "id": "countVowels", "type": "snippet", "attributes": { "fileName": "countVowels.md", "text": "Retuns `number` of vowels in provided string.\n\nUse a regular expression to count the number of vowels `(A, E, I, O, U)` in a `string`.", "codeBlocks": [ "const countVowels = str => (str.match(/[aeiou]/gi) || []).length;", "countVowels('foobar'); // 3\ncountVowels('gym'); // 0" ], "tags": [] }, "meta": { "archived": true, "hash": "333c7a72864d3249f1f409dee1f23214ec47701a54d561a69078e0092137fa4c" } }, { "id": "factors", "type": "snippet", "attributes": { "fileName": "factors.md", "text": "Returns the array of factors of the given `num`. \nIf the second argument is set to `true` returns only the prime factors of `num`.\nIf `num` is `1` or `0` returns an empty array.\nIf `num` is less than `0` returns all the factors of `-int` together with their additive inverses.\n\nUse `Array.from()`, `Array.map()` and `Array.filter()` to find all the factors of `num`.\nIf given `num` is negative, use `Array.reduce()` to add the additive inverses to the array.\nReturn all results if `primes` is `false`, else determine and return only the prime factors using `isPrime` and `Array.filter()`.\nOmit the second argument, `primes`, to return prime and non-prime factors by default.\n\n**Note**:- _Negative numbers are not considered prime._", "codeBlocks": [ "const factors = (num, primes = false) => {\n const isPrime = num => {\n const boundary = Math.floor(Math.sqrt(num));\n for (var i = 2; i <= boundary; i++) if (num % i === 0) return false;\n return num >= 2;\n };\n const isNeg = num < 0;\n num = isNeg ? -num : num;\n let array = Array.from({ length: num - 1 })\n .map((val, i) => (num % (i + 2) === 0 ? i + 2 : false))\n .filter(val => val);\n if (isNeg)\n array = array.reduce((acc, val) => {\n acc.push(val);\n acc.push(-val);\n return acc;\n }, []);\n return primes ? array.filter(isPrime) : array;\n};", "factors(12); // [2,3,4,6,12]\nfactors(12, true); // [2,3]\nfactors(-12); // [2, -2, 3, -3, 4, -4, 6, -6, 12, -12]\nfactors(-12, true); // [2,3]" ], "tags": [] }, "meta": { "archived": true, "hash": "dcef8352bcfcbbd210467de2541b2d3b55c9c06b207c1253cf44ae8ea865559b" } }, { "id": "fibonacciCountUntilNum", "type": "snippet", "attributes": { "fileName": "fibonacciCountUntilNum.md", "text": "Returns the number of fibonnacci numbers up to `num`(`0` and `num` inclusive).\n\nUse a mathematical formula to calculate the number of fibonacci numbers until `num`.", "codeBlocks": [ "const fibonacciCountUntilNum = num =>\n Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));", "fibonacciCountUntilNum(10); // 7" ], "tags": [] }, "meta": { "archived": true, "hash": "d93d0af81aeca41981ed58548672652f9c5ca4b2a6bb887c2c7e0595112dd035" } }, { "id": "fibonacciUntilNum", "type": "snippet", "attributes": { "fileName": "fibonacciUntilNum.md", "text": "Generates an array, containing the Fibonacci sequence, up until the nth term.\n\nCreate an empty array of the specific length, initializing the first two values (`0` and `1`).\nUse `Array.reduce()` to add values into the array, using the sum of the last two values, except for the first two.\nUses a mathematical formula to calculate the length of the array required.", "codeBlocks": [ "const fibonacciUntilNum = num => {\n let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));\n return Array.from({ length: n }).reduce(\n (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),\n []\n );\n};", "fibonacciUntilNum(10); // [ 0, 1, 1, 2, 3, 5, 8 ]" ], "tags": [] }, "meta": { "archived": true, "hash": "1c765ad82aedd1cc090d1c33498ce8426825ab5cb8a74882516ce07343f77f8d" } }, { "id": "howManyTimes", "type": "snippet", "attributes": { "fileName": "howManyTimes.md", "text": "Returns the number of times `num` can be divided by `divisor` (integer or fractional) without getting a fractional answer.\nWorks for both negative and positive integers.\n\nIf `divisor` is `-1` or `1` return `Infinity`.\nIf `divisor` is `-0` or `0` return `0`.\nOtherwise, keep dividing `num` with `divisor` and incrementing `i`, while the result is an integer.\nReturn the number of times the loop was executed, `i`.", "codeBlocks": [ "const howManyTimes = (num, divisor) => {\n if (divisor === 1 || divisor === -1) return Infinity;\n if (divisor === 0) return 0;\n let i = 0;\n while (Number.isInteger(num / divisor)) {\n i++;\n num = num / divisor;\n }\n return i;\n};", "howManyTimes(100, 2); // 2\nhowManyTimes(100, 2.5); // 2\nhowManyTimes(100, 0); // 0\nhowManyTimes(100, -1); // Infinity" ], "tags": [] }, "meta": { "archived": true, "hash": "41f76138f7e673020c6eecd592baea18016869d7d0161edd9d7669f3a991c398" } }, { "id": "httpDelete", "type": "snippet", "attributes": { "fileName": "httpDelete.md", "text": "Makes a `DELETE` request to the passed URL.\n\nUse `XMLHttpRequest` web api to make a `delete` request to the given `url`.\nHandle the `onload` event, by running the provided `callback` function.\nHandle the `onerror` event, by running the provided `err` function.\nOmit the third argument, `err` to log the request to the console's error stream by default.", "codeBlocks": [ "const httpDelete = (url, callback, err = console.error) => {\n const request = new XMLHttpRequest();\n request.open('DELETE', url, true);\n request.onload = () => callback(request);\n request.onerror = () => err(request);\n request.send();\n};", "httpDelete('https://website.com/users/123', request => {\n console.log(request.responseText);\n}); // 'Deletes a user from the database'" ], "tags": [] }, "meta": { "archived": true, "hash": "0b543697856c3c91e3e0a58d3928d743dbe8a369e7263fbc9806aedf487ff723" } }, { "id": "httpPut", "type": "snippet", "attributes": { "fileName": "httpPut.md", "text": "Makes a `PUT` request to the passed URL.\n\nUse `XMLHttpRequest` web api to make a `put` request to the given `url`.\nSet the value of an `HTTP` request header with `setRequestHeader` method.\nHandle the `onload` event, by running the provided `callback` function.\nHandle the `onerror` event, by running the provided `err` function.\nOmit the last argument, `err` to log the request to the console's error stream by default.", "codeBlocks": [ "const httpPut = (url, data, callback, err = console.error) => {\n const request = new XMLHttpRequest();\n request.open(\"PUT\", url, true);\n request.setRequestHeader('Content-type','application/json; charset=utf-8');\n request.onload = () => callback(request);\n request.onerror = () => err(request);\n request.send(data);\n};", "const password = \"fooBaz\";\nconst data = JSON.stringify(password);\nhttpPut('https://website.com/users/123', data, request => {\n console.log(request.responseText);\n}); // 'Updates a user's password in database'" ], "tags": [] }, "meta": { "archived": true, "hash": "59572ee267c7f0bc7c4e411ebde24834a2f5e8e928e2e50c16ac787034b1a53a" } }, { "id": "isArmstrongNumber", "type": "snippet", "attributes": { "fileName": "isArmstrongNumber.md", "text": "Checks if the given number is an Armstrong number or not.\n\nConvert 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`.", "codeBlocks": [ "const isArmstrongNumber = digits =>\n (arr => arr.reduce((a, d) => a + parseInt(d) ** arr.length, 0) == digits)(\n (digits + '').split('')\n );", "isArmstrongNumber(1634); // true\nisArmstrongNumber(56); // false" ], "tags": [] }, "meta": { "archived": true, "hash": "28a3c44cfc4ec7d34e00b2866b67bff9b3fb100f6f72c767b893159b869fd8f4" } }, { "id": "isSimilar", "type": "snippet", "attributes": { "fileName": "isSimilar.md", "text": "Determines if the `pattern` matches with `str`.\n\nUse `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.\nAdapted from [here](https://github.com/forrestthewoods/lib_fts/blob/80f3f8c52db53428247e741b9efe2cde9667050c/code/fts_fuzzy_match.js#L18).", "codeBlocks": [ "const isSimilar = (pattern, str) =>\n [...str].reduce(\n (matchIndex, char) =>\n char.toLowerCase() === (pattern[matchIndex] || '').toLowerCase()\n ? matchIndex + 1\n : matchIndex,\n 0\n ) === pattern.length\n ? true\n : false;", "isSimilar('rt','Rohit'); // true\nisSimilar('tr','Rohit'); // false" ], "tags": [] }, "meta": { "archived": true, "hash": "570b1b21e29f3793d7c1f001958ec68a7c27b913d65e37cf5f078b1e6a839437" } }, { "id": "JSONToDate", "type": "snippet", "attributes": { "fileName": "JSONToDate.md", "text": "Converts a JSON object to a date.\n\nUse `Date()`, to convert dates in JSON format to readable format (`dd/mm/yyyy`).", "codeBlocks": [ "const JSONToDate = arr => {\n const dt = new Date(parseInt(arr.toString().substr(6)));\n return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`;\n};", "JSONToDate(/Date(1489525200000)/); // \"14/3/2017\"" ], "tags": [] }, "meta": { "archived": true, "hash": "eb80d886a67c11c9395bcb414beb1e684c875b1318025609b7e12c44a58d99e9" } }, { "id": "levenshteinDistance", "type": "snippet", "attributes": { "fileName": "levenshteinDistance.md", "text": "Calculates the [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) between two strings.\n\nCalculates the number of changes (substitutions, deletions or additions) required to convert `string1` to `string2`. \nCan also be used to compare two strings as shown in the second example.", "codeBlocks": [ "``` js\nconst levenshteinDistance = (string1, string2) => {\n if (string1.length === 0) return string2.length;\n if (string2.length === 0) return string1.length;\n let matrix = Array(string2.length + 1)\n .fill(0)\n .map((x, i) => [i]);\n matrix[0] = Array(string1.length + 1)\n .fill(0)\n .map((x, i) => i);\n for (let i = 1; i <= string2.length; i++) {\n for (let j = 1; j <= string1.length; j++) {\n if (string2[i - 1] === string1[j - 1]) {\n matrix[i][j] = matrix[i - 1][j - 1];\n } else {\n matrix[i][j] = Math.min(\n matrix[i - 1][j - 1] + 1,\n matrix[i][j - 1] + 1,\n matrix[i - 1][j] + 1\n );\n }\n }\n }\n return matrix[string2.length][string1.length];\n};\n```", "levenshteinDistance('30-seconds-of-code','30-seconds-of-python-code'); // 7\nconst compareStrings = (string1,string2) => (100 - levenshteinDistance(string1,string2) / Math.max(string1.length,string2.length));\ncompareStrings('30-seconds-of-code', '30-seconds-of-python-code'); // 99.72 (%)" ], "tags": [] }, "meta": { "archived": true, "hash": "3cc34a842404de0aea2752a6b1398b8a0825cb1a359ff36ab5275f7d15eff107" } }, { "id": "quickSort", "type": "snippet", "attributes": { "fileName": "quickSort.md", "text": "QuickSort an Array (ascending sort by default).\n\nUse recursion. \nUse `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. \nIf the parameter `desc` is truthy, return array sorts in descending order.", "codeBlocks": [ "const quickSort = ([n, ...nums], desc) =>\n isNaN(n)\n ? []\n : [\n ...quickSort(nums.filter(v => (desc ? v > n : v <= n)), desc),\n n,\n ...quickSort(nums.filter(v => (!desc ? v > n : v <= n)), desc)\n ];", "quickSort([4, 1, 3, 2]); // [1,2,3,4]\nquickSort([4, 1, 3, 2], true); // [4,3,2,1]" ], "tags": [] }, "meta": { "archived": true, "hash": "396d8fec22d42453b2556d4428fb35e7ef06b9844f7d6ad163923f292a96a6b5" } }, { "id": "README", "type": "snippet", "attributes": { "fileName": "README.md", "text": "Converts a JSON object to a date.\n\nUse `Date()`, to convert dates in JSON format to readable format (`dd/mm/yyyy`).", "codeBlocks": [ "const JSONToDate = arr => {\n const dt = new Date(parseInt(arr.toString().substr(6)));\n return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`;\n};", "JSONToDate(/Date(1489525200000)/); // \"14/3/2017\"", "const speechSynthesis = message => {\n const msg = new SpeechSynthesisUtterance(message);\n msg.voice = window.speechSynthesis.getVoices()[0];\n window.speechSynthesis.speak(msg);\n};", "speechSynthesis('Hello, World'); // // plays the message", "const binarySearch = (arr, val, start = 0, end = arr.length - 1) => {\n if (start > end) return -1;\n const mid = Math.floor((start + end) / 2);\n if (arr[mid] > val) return binarySearch(arr, val, start, mid - 1);\n if (arr[mid] < val) return binarySearch(arr, val, mid + 1, end);\n return mid;\n};", "binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 6); // 2\nbinarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 21); // -1", "const cleanObj = (obj, keysToKeep = [], childIndicator) => {\n Object.keys(obj).forEach(key => {\n if (key === childIndicator) {\n cleanObj(obj[key], keysToKeep, childIndicator);\n } else if (!keysToKeep.includes(key)) {\n delete obj[key];\n }\n });\n return obj;\n};", "const testObj = { a: 1, b: 2, children: { a: 1, b: 2 } };\ncleanObj(testObj, ['a'], 'children'); // { a: 1, children : { a: 1}}", "const collatz = n => (n % 2 === 0 ? n / 2 : 3 * n + 1);", "collatz(8); // 4", "const countVowels = str => (str.match(/[aeiou]/gi) || []).length;", "countVowels('foobar'); // 3\ncountVowels('gym'); // 0", "const factors = (num, primes = false) => {\n const isPrime = num => {\n const boundary = Math.floor(Math.sqrt(num));\n for (var i = 2; i <= boundary; i++) if (num % i === 0) return false;\n return num >= 2;\n };\n const isNeg = num < 0;\n num = isNeg ? -num : num;\n let array = Array.from({ length: num - 1 })\n .map((val, i) => (num % (i + 2) === 0 ? i + 2 : false))\n .filter(val => val);\n if (isNeg)\n array = array.reduce((acc, val) => {\n acc.push(val);\n acc.push(-val);\n return acc;\n }, []);\n return primes ? array.filter(isPrime) : array;\n};", "factors(12); // [2,3,4,6,12]\nfactors(12, true); // [2,3]\nfactors(-12); // [2, -2, 3, -3, 4, -4, 6, -6, 12, -12]\nfactors(-12, true); // [2,3]", "const fibonacciCountUntilNum = num =>\n Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));", "fibonacciCountUntilNum(10); // 7", "const fibonacciUntilNum = num => {\n let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));\n return Array.from({ length: n }).reduce(\n (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),\n []\n );\n};", "fibonacciUntilNum(10); // [ 0, 1, 1, 2, 3, 5, 8 ]", "const httpDelete = (url, callback, err = console.error) => {\n const request = new XMLHttpRequest();\n request.open('DELETE', url, true);\n request.onload = () => callback(request);\n request.onerror = () => err(request);\n request.send();\n};", "httpDelete('https://website.com/users/123', request => {\n console.log(request.responseText);\n}); // 'Deletes a user from the database'", "const httpPut = (url, data, callback, err = console.error) => {\n const request = new XMLHttpRequest();\n request.open(\"PUT\", url, true);\n request.setRequestHeader('Content-type','application/json; charset=utf-8');\n request.onload = () => callback(request);\n request.onerror = () => err(request);\n request.send(data);\n};", "const password = \"fooBaz\";\nconst data = JSON.stringify(password);\nhttpPut('https://website.com/users/123', data, request => {\n console.log(request.responseText);\n}); // 'Updates a user's password in database'", "const isArmstrongNumber = digits =>\n (arr => arr.reduce((a, d) => a + parseInt(d) ** arr.length, 0) == digits)(\n (digits + '').split('')\n );", "isArmstrongNumber(1634); // true\nisArmstrongNumber(56); // false", "const isSimilar = (pattern, str) =>\n [...str].reduce(\n (matchIndex, char) =>\n char.toLowerCase() === (pattern[matchIndex] || '').toLowerCase()\n ? matchIndex + 1\n : matchIndex,\n 0\n ) === pattern.length\n ? true\n : false;", "isSimilar('rt','Rohit'); // true\nisSimilar('tr','Rohit'); // false", "``` js\nconst levenshteinDistance = (string1, string2) => {\n if (string1.length === 0) return string2.length;\n if (string2.length === 0) return string1.length;\n let matrix = Array(string2.length + 1)\n .fill(0)\n .map((x, i) => [i]);\n matrix[0] = Array(string1.length + 1)\n .fill(0)\n .map((x, i) => i);\n for (let i = 1; i <= string2.length; i++) {\n for (let j = 1; j <= string1.length; j++) {\n if (string2[i - 1] === string1[j - 1]) {\n matrix[i][j] = matrix[i - 1][j - 1];\n } else {\n matrix[i][j] = Math.min(\n matrix[i - 1][j - 1] + 1,\n matrix[i][j - 1] + 1,\n matrix[i - 1][j] + 1\n );\n }\n }\n }\n return matrix[string2.length][string1.length];\n};\n```", "levenshteinDistance('30-seconds-of-code','30-seconds-of-python-code'); // 7\nconst compareStrings = (string1,string2) => (100 - levenshteinDistance(string1,string2) / Math.max(string1.length,string2.length));\ncompareStrings('30-seconds-of-code', '30-seconds-of-python-code'); // 99.72 (%)", "const quickSort = ([n, ...nums], desc) =>\n isNaN(n)\n ? []\n : [\n ...quickSort(nums.filter(v => (desc ? v > n : v <= n)), desc),\n n,\n ...quickSort(nums.filter(v => (!desc ? v > n : v <= n)), desc)\n ];", "quickSort([4, 1, 3, 2]); // [1,2,3,4]\nquickSort([4, 1, 3, 2], true); // [4,3,2,1]", "const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi, repl);", "removeVowels(\"foobAr\"); // \"fbr\"\nremoveVowels(\"foobAr\",\"*\"); // \"f**b*r\"", "const solveRPN = rpn => {\n const OPERATORS = {\n '*': (a, b) => a * b,\n '+': (a, b) => a + b,\n '-': (a, b) => a - b,\n '/': (a, b) => a / b,\n '**': (a, b) => a ** b\n };\n const [stack, solve] = [\n [],\n rpn\n .replace(/\\^/g, '**')\n .split(/\\s+/g)\n .filter(el => !/\\s+/.test(el) && el !== '')\n ];\n solve.forEach(symbol => {\n if (!isNaN(parseFloat(symbol)) && isFinite(symbol)) {\n stack.push(symbol);\n } else if (Object.keys(OPERATORS).includes(symbol)) {\n const [a, b] = [stack.pop(), stack.pop()];\n stack.push(OPERATORS[symbol](parseFloat(b), parseFloat(a)));\n } else {\n throw `${symbol} is not a recognized symbol`;\n }\n });\n if (stack.length === 1) return stack.pop();\n else throw `${rpn} is not a proper RPN. Please check it and try again`;\n};", "solveRPN('15 7 1 1 + - / 3 * 2 1 1 + + -'); // 5\nsolveRPN('2 3 ^'); // 8", "const howManyTimes = (num, divisor) => {\n if (divisor === 1 || divisor === -1) return Infinity;\n if (divisor === 0) return 0;\n let i = 0;\n while (Number.isInteger(num / divisor)) {\n i++;\n num = num / divisor;\n }\n return i;\n};", "howManyTimes(100, 2); // 2\nhowManyTimes(100, 2.5); // 2\nhowManyTimes(100, 0); // 0\nhowManyTimes(100, -1); // Infinity" ], "tags": [] }, "meta": { "archived": true, "hash": "86af9032bb3fd1afc0b6e32aeca6a25c69549594804ff93f9eb0fe6e9e37236b" } }, { "id": "removeVowels", "type": "snippet", "attributes": { "fileName": "removeVowels.md", "text": "Returns all the vowels in a `str` replaced by `repl`.\n\nUse `String.replace()` with a regexp to replace all vowels in `str`.\nOmot `repl` to use a default value of `''`.", "codeBlocks": [ "const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi, repl);", "removeVowels(\"foobAr\"); // \"fbr\"\nremoveVowels(\"foobAr\",\"*\"); // \"f**b*r\"" ], "tags": [] }, "meta": { "archived": true, "hash": "5f3ccc861fd5a18aa561957aadb6494402c1b3bdc1ec38b768e524c600ac756b" } }, { "id": "solveRPN", "type": "snippet", "attributes": { "fileName": "solveRPN.md", "text": "Solves the given mathematical expression in [reverse polish notation](https://en.wikipedia.org/wiki/Reverse_Polish_notation).\nThrows 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.\n\nUse a dictionary, `OPERATORS` to specify each operator's matching mathematical operation.\nUse `String.replace()` with a regular expression to replace `^` with `**`, `String.split()` to tokenize the string and `Array.filter()` to remove empty tokens.\nUse `Array.forEach()` to parse each `symbol`, evaluate it as a numeric value or operator and solve the mathematical expression.\nNumeric 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.", "codeBlocks": [ "const solveRPN = rpn => {\n const OPERATORS = {\n '*': (a, b) => a * b,\n '+': (a, b) => a + b,\n '-': (a, b) => a - b,\n '/': (a, b) => a / b,\n '**': (a, b) => a ** b\n };\n const [stack, solve] = [\n [],\n rpn\n .replace(/\\^/g, '**')\n .split(/\\s+/g)\n .filter(el => !/\\s+/.test(el) && el !== '')\n ];\n solve.forEach(symbol => {\n if (!isNaN(parseFloat(symbol)) && isFinite(symbol)) {\n stack.push(symbol);\n } else if (Object.keys(OPERATORS).includes(symbol)) {\n const [a, b] = [stack.pop(), stack.pop()];\n stack.push(OPERATORS[symbol](parseFloat(b), parseFloat(a)));\n } else {\n throw `${symbol} is not a recognized symbol`;\n }\n });\n if (stack.length === 1) return stack.pop();\n else throw `${rpn} is not a proper RPN. Please check it and try again`;\n};", "solveRPN('15 7 1 1 + - / 3 * 2 1 1 + + -'); // 5\nsolveRPN('2 3 ^'); // 8" ], "tags": [] }, "meta": { "archived": true, "hash": "6b02ad139d3edcc41e767b6768cc53439c5316f5c14e00a4e2a56b2da102d1e9" } }, { "id": "speechSynthesis", "type": "snippet", "attributes": { "fileName": "speechSynthesis.md", "text": "Performs speech synthesis (experimental).\n\nUse `SpeechSynthesisUtterance.voice` and `window.speechSynthesis.getVoices()` to convert a message to speech.\nUse `window.speechSynthesis.speak()` to play the message.\n\nLearn more about the [SpeechSynthesisUtterance interface of the Web Speech API](https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisUtterance).", "codeBlocks": [ "const speechSynthesis = message => {\n const msg = new SpeechSynthesisUtterance(message);\n msg.voice = window.speechSynthesis.getVoices()[0];\n window.speechSynthesis.speak(msg);\n};", "speechSynthesis('Hello, World'); // // plays the message" ], "tags": [] }, "meta": { "archived": true, "hash": "21409f3b5ea7aaa9ad0041508b14c64dcaeff234121aca148e14fe26cf8b5f93" } } ], "meta": { "specification": "http://jsonapi.org/format/" } }