Updated extractor, removed analyzer
This commit is contained in:
@ -34,7 +34,6 @@
|
||||
"extractor": "node ./scripts/extract.js",
|
||||
"packager": "node ./scripts/module.js",
|
||||
"localizer": "node ./scripts/localize.js",
|
||||
"analyzer": "node ./scripts/analyze.js",
|
||||
"test": "jest --verbose"
|
||||
},
|
||||
"repository": {
|
||||
|
||||
@ -1,58 +0,0 @@
|
||||
/*
|
||||
This is the analyzer script that generates the snippetAnalytics.json and snippetArchiveAnalytics.json files.
|
||||
Run using `npm run analyzer`.
|
||||
*/
|
||||
// Load modules
|
||||
const fs = require('fs-extra');
|
||||
const path = require('path');
|
||||
const chalk = require('chalk');
|
||||
const prism = require('prismjs');
|
||||
let snippetsData = require('../snippet_data/snippets.json');
|
||||
let snippetsArchiveData = require('../snippet_data/snippetsArchive.json');
|
||||
// Paths
|
||||
const OUTPUT_PATH = './snippet_data';
|
||||
console.time('Analyzer');
|
||||
// Read data
|
||||
let [snippetTokens, snippetArchiveTokens] = [snippetsData, snippetsArchiveData].map(v => ({
|
||||
data: v.data.map(snippet => {
|
||||
let tokens = prism.tokenize(
|
||||
snippet.attributes.codeBlocks[0],
|
||||
prism.languages.javascript,
|
||||
'javascript'
|
||||
);
|
||||
return {
|
||||
id: snippet.id,
|
||||
type: 'snippetAnalysis',
|
||||
attributes: {
|
||||
codeLength: snippet.attributes.codeBlocks[0].trim().length,
|
||||
tokenCount: tokens.length,
|
||||
functionCount: tokens.filter(t => t.type === 'function').length,
|
||||
operatorCount: tokens.filter(t => t.type === 'operator').length,
|
||||
keywordCount: tokens.filter(t => t.type === 'keyword').length,
|
||||
distinctFunctionCount: [
|
||||
...new Set(tokens.filter(t => t.type === 'function').map(t => t.content))
|
||||
].length
|
||||
},
|
||||
meta: {
|
||||
hash: snippet.meta.hash
|
||||
}
|
||||
};
|
||||
}),
|
||||
meta: { specification: 'http://jsonapi.org/format/' }
|
||||
}));
|
||||
// Write data
|
||||
fs.writeFileSync(
|
||||
path.join(OUTPUT_PATH, 'snippetAnalytics.json'),
|
||||
JSON.stringify(snippetTokens, null, 2)
|
||||
);
|
||||
fs.writeFileSync(
|
||||
path.join(OUTPUT_PATH, 'snippetArchiveAnalytics.json'),
|
||||
JSON.stringify(snippetArchiveTokens, null, 2)
|
||||
);
|
||||
// Display messages and time
|
||||
console.log(
|
||||
`${chalk.green(
|
||||
'SUCCESS!'
|
||||
)} snippetAnalyticss.json and snippetArchiveAnalytics.json files generated!`
|
||||
);
|
||||
console.timeEnd('Analyzer');
|
||||
@ -29,59 +29,66 @@ snippets = util.readSnippets(SNIPPETS_PATH);
|
||||
archivedSnippets = util.readSnippets(SNIPPETS_ARCHIVE_PATH);
|
||||
tagDbData = util.readTags();
|
||||
// Extract snippet data
|
||||
let snippetData = {
|
||||
data: Object.keys(snippets).map(key => {
|
||||
return {
|
||||
id: key.slice(0, -3),
|
||||
type: 'snippet',
|
||||
attributes: {
|
||||
fileName: key,
|
||||
text: util.getTextualContent(snippets[key]).trim(),
|
||||
codeBlocks: util
|
||||
.getCodeBlocks(snippets[key])
|
||||
.map(v => v.replace(/```js([\s\S]*?)```/g, '$1').trim()),
|
||||
tags: tagDbData[key.slice(0, -3)]
|
||||
},
|
||||
meta: {
|
||||
archived: false,
|
||||
hash: util.hashData(snippets[key])
|
||||
}
|
||||
};
|
||||
}),
|
||||
let snippetData = Object.keys(snippets).map(key => {
|
||||
return {
|
||||
id: key.slice(0, -3),
|
||||
type: 'snippet',
|
||||
attributes: {
|
||||
fileName: key,
|
||||
text: util.getTextualContent(snippets[key]).trim(),
|
||||
codeBlocks: util.getCodeBlocks(snippets[key]),
|
||||
tags: tagDbData[key.slice(0, -3)]
|
||||
},
|
||||
meta: {
|
||||
archived: false,
|
||||
hash: util.hashData(snippets[key])
|
||||
}
|
||||
};
|
||||
});
|
||||
// Extract archived snippet data
|
||||
let snippetArchiveData = Object.keys(archivedSnippets).map(key => {
|
||||
return {
|
||||
id: key.slice(0, -3),
|
||||
type: 'snippet',
|
||||
attributes: {
|
||||
fileName: key,
|
||||
text: util.getTextualContent(archivedSnippets[key]).trim(),
|
||||
codeBlocks: util.getCodeBlocks(archivedSnippets[key]),
|
||||
tags: []
|
||||
},
|
||||
meta: {
|
||||
archived: true,
|
||||
hash: util.hashData(archivedSnippets[key])
|
||||
}
|
||||
};
|
||||
});
|
||||
const completeData = {
|
||||
data: [...snippetData, ...snippetArchiveData],
|
||||
meta: {
|
||||
specification: 'http://jsonapi.org/format/'
|
||||
}
|
||||
};
|
||||
// Extract archived snippet data
|
||||
let snippetArchiveData = {
|
||||
data: Object.keys(archivedSnippets).map(key => {
|
||||
return {
|
||||
id: key.slice(0, -3),
|
||||
type: 'snippet',
|
||||
let listingData = {
|
||||
data:
|
||||
completeData.data.map(v => ({
|
||||
id: v.id,
|
||||
type: 'snippetListing',
|
||||
attributes: {
|
||||
fileName: key,
|
||||
text: util.getTextualContent(archivedSnippets[key]).trim(),
|
||||
codeBlocks: util
|
||||
.getCodeBlocks(archivedSnippets[key])
|
||||
.map(v => v.replace(/```js([\s\S]*?)```/g, '$1').trim()),
|
||||
tags: []
|
||||
tags: v.attributes.tags,
|
||||
archived: v.meta.archived
|
||||
},
|
||||
meta: {
|
||||
archived: true,
|
||||
hash: util.hashData(archivedSnippets[key])
|
||||
hash: v.meta.hash
|
||||
}
|
||||
};
|
||||
}),
|
||||
}))
|
||||
,
|
||||
meta: {
|
||||
specification: 'http://jsonapi.org/format/'
|
||||
}
|
||||
};
|
||||
// Write files
|
||||
fs.writeFileSync(path.join(OUTPUT_PATH, 'snippets.json'), JSON.stringify(snippetData, null, 2));
|
||||
fs.writeFileSync(
|
||||
path.join(OUTPUT_PATH, 'snippetsArchive.json'),
|
||||
JSON.stringify(snippetArchiveData, null, 2)
|
||||
);
|
||||
fs.writeFileSync(path.join(OUTPUT_PATH, 'snippets.json'), JSON.stringify(completeData, null, 2));
|
||||
fs.writeFileSync(path.join(OUTPUT_PATH, 'snippetList.json'), JSON.stringify(listingData, null, 2));
|
||||
// Display messages and time
|
||||
console.log(`${chalk.green('SUCCESS!')} snippets.json and snippetsArchive.json files generated!`);
|
||||
console.timeEnd('Extractor');
|
||||
|
||||
@ -2,6 +2,7 @@ const fs = require('fs-extra'),
|
||||
path = require('path'),
|
||||
chalk = require('chalk'),
|
||||
crypto = require('crypto');
|
||||
const babel = require('@babel/core');
|
||||
|
||||
const getMarkDownAnchor = paragraphTitle =>
|
||||
paragraphTitle
|
||||
@ -117,7 +118,7 @@ const hashData = val =>
|
||||
// Gets the code blocks for a snippet file.
|
||||
const getCodeBlocks = str => {
|
||||
const regex = /```[.\S\s]*?```/g;
|
||||
const results = [];
|
||||
let results = [];
|
||||
let m = null;
|
||||
while ((m = regex.exec(str)) !== null) {
|
||||
if (m.index === regex.lastIndex)
|
||||
@ -127,7 +128,12 @@ const getCodeBlocks = str => {
|
||||
results.push(match);
|
||||
});
|
||||
}
|
||||
return results;
|
||||
results = results.map(v => v.replace(/```js([\s\S]*?)```/g, '$1').trim());
|
||||
return {
|
||||
es6: results[0],
|
||||
es5: babel.transformSync(results[0], { presets: ['@babel/preset-env'] }).code,
|
||||
example: results[1]
|
||||
}
|
||||
};
|
||||
// Gets the textual content for a snippet file.
|
||||
const getTextualContent = str => {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,292 +0,0 @@
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": "binarySearch",
|
||||
"type": "snippetAnalysis",
|
||||
"attributes": {
|
||||
"codeLength": 297,
|
||||
"tokenCount": 127,
|
||||
"functionCount": 3,
|
||||
"operatorCount": 14,
|
||||
"keywordCount": 9,
|
||||
"distinctFunctionCount": 2
|
||||
},
|
||||
"meta": {
|
||||
"hash": "2e9aff504a7716c4b49b30702ee3b922c707fac70efc099422ae5ba5a7d0e009"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "cleanObj",
|
||||
"type": "snippetAnalysis",
|
||||
"attributes": {
|
||||
"codeLength": 280,
|
||||
"tokenCount": 95,
|
||||
"functionCount": 4,
|
||||
"operatorCount": 6,
|
||||
"keywordCount": 6,
|
||||
"distinctFunctionCount": 4
|
||||
},
|
||||
"meta": {
|
||||
"hash": "ec33abb9423c49520400becb5183d87b37bbf6eb60012673c8df5a0a672a6af0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "collatz",
|
||||
"type": "snippetAnalysis",
|
||||
"attributes": {
|
||||
"codeLength": 55,
|
||||
"tokenCount": 35,
|
||||
"functionCount": 0,
|
||||
"operatorCount": 8,
|
||||
"keywordCount": 1,
|
||||
"distinctFunctionCount": 0
|
||||
},
|
||||
"meta": {
|
||||
"hash": "650c91d557244ee0e3f64a00d457d63b47271aa0b963728bfc37dc5c3c88c67e"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "countVowels",
|
||||
"type": "snippetAnalysis",
|
||||
"attributes": {
|
||||
"codeLength": 65,
|
||||
"tokenCount": 24,
|
||||
"functionCount": 1,
|
||||
"operatorCount": 3,
|
||||
"keywordCount": 1,
|
||||
"distinctFunctionCount": 1
|
||||
},
|
||||
"meta": {
|
||||
"hash": "333c7a72864d3249f1f409dee1f23214ec47701a54d561a69078e0092137fa4c"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "factors",
|
||||
"type": "snippetAnalysis",
|
||||
"attributes": {
|
||||
"codeLength": 580,
|
||||
"tokenCount": 236,
|
||||
"functionCount": 8,
|
||||
"operatorCount": 30,
|
||||
"keywordCount": 14,
|
||||
"distinctFunctionCount": 6
|
||||
},
|
||||
"meta": {
|
||||
"hash": "dcef8352bcfcbbd210467de2541b2d3b55c9c06b207c1253cf44ae8ea865559b"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "fibonacciCountUntilNum",
|
||||
"type": "snippetAnalysis",
|
||||
"attributes": {
|
||||
"codeLength": 123,
|
||||
"tokenCount": 57,
|
||||
"functionCount": 5,
|
||||
"operatorCount": 8,
|
||||
"keywordCount": 1,
|
||||
"distinctFunctionCount": 3
|
||||
},
|
||||
"meta": {
|
||||
"hash": "d93d0af81aeca41981ed58548672652f9c5ca4b2a6bb887c2c7e0595112dd035"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "fibonacciUntilNum",
|
||||
"type": "snippetAnalysis",
|
||||
"attributes": {
|
||||
"codeLength": 256,
|
||||
"tokenCount": 128,
|
||||
"functionCount": 7,
|
||||
"operatorCount": 15,
|
||||
"keywordCount": 4,
|
||||
"distinctFunctionCount": 5
|
||||
},
|
||||
"meta": {
|
||||
"hash": "1c765ad82aedd1cc090d1c33498ce8426825ab5cb8a74882516ce07343f77f8d"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "howManyTimes",
|
||||
"type": "snippetAnalysis",
|
||||
"attributes": {
|
||||
"codeLength": 237,
|
||||
"tokenCount": 90,
|
||||
"functionCount": 1,
|
||||
"operatorCount": 12,
|
||||
"keywordCount": 8,
|
||||
"distinctFunctionCount": 1
|
||||
},
|
||||
"meta": {
|
||||
"hash": "41f76138f7e673020c6eecd592baea18016869d7d0161edd9d7669f3a991c398"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "httpDelete",
|
||||
"type": "snippetAnalysis",
|
||||
"attributes": {
|
||||
"codeLength": 242,
|
||||
"tokenCount": 85,
|
||||
"functionCount": 4,
|
||||
"operatorCount": 8,
|
||||
"keywordCount": 3,
|
||||
"distinctFunctionCount": 4
|
||||
},
|
||||
"meta": {
|
||||
"hash": "0b543697856c3c91e3e0a58d3928d743dbe8a369e7263fbc9806aedf487ff723"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "httpPut",
|
||||
"type": "snippetAnalysis",
|
||||
"attributes": {
|
||||
"codeLength": 324,
|
||||
"tokenCount": 97,
|
||||
"functionCount": 5,
|
||||
"operatorCount": 8,
|
||||
"keywordCount": 3,
|
||||
"distinctFunctionCount": 5
|
||||
},
|
||||
"meta": {
|
||||
"hash": "59572ee267c7f0bc7c4e411ebde24834a2f5e8e928e2e50c16ac787034b1a53a"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "isArmstrongNumber",
|
||||
"type": "snippetAnalysis",
|
||||
"attributes": {
|
||||
"codeLength": 145,
|
||||
"tokenCount": 58,
|
||||
"functionCount": 3,
|
||||
"operatorCount": 8,
|
||||
"keywordCount": 1,
|
||||
"distinctFunctionCount": 3
|
||||
},
|
||||
"meta": {
|
||||
"hash": "28a3c44cfc4ec7d34e00b2866b67bff9b3fb100f6f72c767b893159b869fd8f4"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "isSimilar",
|
||||
"type": "snippetAnalysis",
|
||||
"attributes": {
|
||||
"codeLength": 251,
|
||||
"tokenCount": 78,
|
||||
"functionCount": 3,
|
||||
"operatorCount": 10,
|
||||
"keywordCount": 1,
|
||||
"distinctFunctionCount": 2
|
||||
},
|
||||
"meta": {
|
||||
"hash": "570b1b21e29f3793d7c1f001958ec68a7c27b913d65e37cf5f078b1e6a839437"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "JSONToDate",
|
||||
"type": "snippetAnalysis",
|
||||
"attributes": {
|
||||
"codeLength": 158,
|
||||
"tokenCount": 41,
|
||||
"functionCount": 3,
|
||||
"operatorCount": 3,
|
||||
"keywordCount": 4,
|
||||
"distinctFunctionCount": 3
|
||||
},
|
||||
"meta": {
|
||||
"hash": "eb80d886a67c11c9395bcb414beb1e684c875b1318025609b7e12c44a58d99e9"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "levenshteinDistance",
|
||||
"type": "snippetAnalysis",
|
||||
"attributes": {
|
||||
"codeLength": 733,
|
||||
"tokenCount": 3,
|
||||
"functionCount": 0,
|
||||
"operatorCount": 0,
|
||||
"keywordCount": 0,
|
||||
"distinctFunctionCount": 0
|
||||
},
|
||||
"meta": {
|
||||
"hash": "3cc34a842404de0aea2752a6b1398b8a0825cb1a359ff36ab5275f7d15eff107"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "quickSort",
|
||||
"type": "snippetAnalysis",
|
||||
"attributes": {
|
||||
"codeLength": 231,
|
||||
"tokenCount": 92,
|
||||
"functionCount": 5,
|
||||
"operatorCount": 15,
|
||||
"keywordCount": 1,
|
||||
"distinctFunctionCount": 3
|
||||
},
|
||||
"meta": {
|
||||
"hash": "396d8fec22d42453b2556d4428fb35e7ef06b9844f7d6ad163923f292a96a6b5"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "README",
|
||||
"type": "snippetAnalysis",
|
||||
"attributes": {
|
||||
"codeLength": 158,
|
||||
"tokenCount": 41,
|
||||
"functionCount": 3,
|
||||
"operatorCount": 3,
|
||||
"keywordCount": 4,
|
||||
"distinctFunctionCount": 3
|
||||
},
|
||||
"meta": {
|
||||
"hash": "86af9032bb3fd1afc0b6e32aeca6a25c69549594804ff93f9eb0fe6e9e37236b"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "removeVowels",
|
||||
"type": "snippetAnalysis",
|
||||
"attributes": {
|
||||
"codeLength": 72,
|
||||
"tokenCount": 23,
|
||||
"functionCount": 1,
|
||||
"operatorCount": 3,
|
||||
"keywordCount": 1,
|
||||
"distinctFunctionCount": 1
|
||||
},
|
||||
"meta": {
|
||||
"hash": "5f3ccc861fd5a18aa561957aadb6494402c1b3bdc1ec38b768e524c600ac756b"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "solveRPN",
|
||||
"type": "snippetAnalysis",
|
||||
"attributes": {
|
||||
"codeLength": 816,
|
||||
"tokenCount": 300,
|
||||
"functionCount": 17,
|
||||
"operatorCount": 23,
|
||||
"keywordCount": 13,
|
||||
"distinctFunctionCount": 12
|
||||
},
|
||||
"meta": {
|
||||
"hash": "6b02ad139d3edcc41e767b6768cc53439c5316f5c14e00a4e2a56b2da102d1e9"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "speechSynthesis",
|
||||
"type": "snippetAnalysis",
|
||||
"attributes": {
|
||||
"codeLength": 182,
|
||||
"tokenCount": 48,
|
||||
"functionCount": 2,
|
||||
"operatorCount": 4,
|
||||
"keywordCount": 3,
|
||||
"distinctFunctionCount": 2
|
||||
},
|
||||
"meta": {
|
||||
"hash": "21409f3b5ea7aaa9ad0041508b14c64dcaeff234121aca148e14fe26cf8b5f93"
|
||||
}
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"specification": "http://jsonapi.org/format/"
|
||||
}
|
||||
}
|
||||
5259
snippet_data/snippetList.json
Normal file
5259
snippet_data/snippetList.json
Normal file
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -1,497 +0,0 @@
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": "binarySearch",
|
||||
"type": "snippet",
|
||||
"attributes": {
|
||||
"fileName": "binarySearch.md",
|
||||
"text": "Use recursion. Similar to `Array.prototype.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.prototype.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": "1ec820569490b17af8315133226e1545efb1d842e4dada922c88126c342a2132"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "celsiusToFahrenheit",
|
||||
"type": "snippet",
|
||||
"attributes": {
|
||||
"fileName": "celsiusToFahrenheit.md",
|
||||
"text": "Celsius to Fahrenheit temperature conversion.\n\nFollows the conversion formula `F = 1.8C + 32`.",
|
||||
"codeBlocks": [
|
||||
"const celsiusToFahrenheit = degrees => 1.8 * degrees + 32;",
|
||||
"celsiusToFahrenheit(33) // 91.4"
|
||||
],
|
||||
"tags": []
|
||||
},
|
||||
"meta": {
|
||||
"archived": true,
|
||||
"hash": "8289007c7b10777d68d346e0ef02a58a44472cee41d5fb2f3bafaec4f1dd148b"
|
||||
}
|
||||
},
|
||||
{
|
||||
"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.prototype.map()` and `Array.prototype.filter()` to find all the factors of `num`.\nIf given `num` is negative, use `Array.prototype.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.prototype.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": "e0056bb031e8df0565daddb6200df1fa9675e2c538e71f354ceeeee164c2b8a9"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "fahrenheitToCelsius",
|
||||
"type": "snippet",
|
||||
"attributes": {
|
||||
"fileName": "fahrenheitToCelsius.md",
|
||||
"text": "Fahrenheit to Celsius temperature conversion.\n\nFollows the conversion formula `C = (F - 32) * 5/9`.",
|
||||
"codeBlocks": [
|
||||
"const fahrenheitToCelsius = degrees => (degrees - 32) * 5/9;",
|
||||
"fahrenheitToCelsius(32); // 0"
|
||||
],
|
||||
"tags": []
|
||||
},
|
||||
"meta": {
|
||||
"archived": true,
|
||||
"hash": "89d58eda3d03f8fc8d2fe61fb36376f92a0443435552d063d4fbf5b623fc4314"
|
||||
}
|
||||
},
|
||||
{
|
||||
"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.prototype.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": "9de50bed5b8c247176570f743c8154a5ec4093432f8a09ba91c423d78af47169"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "heronArea",
|
||||
"type": "snippet",
|
||||
"attributes": {
|
||||
"fileName": "heronArea.md",
|
||||
"text": "Returns the area of a triangle using only the 3 side lengths, Heron's formula. Assumes that the sides define a valid triangle. Does NOT assume it is a right triangle.\n\nMore information on what Heron's formula is and why it works available here: https://en.wikipedia.org/wiki/Heron%27s_formula.\n\nUses `Math.sqrt()` to find the square root of a value.",
|
||||
"codeBlocks": [
|
||||
"const heronArea = (side_a, side_b, side_c) => {\n const p = (side_a + side_b + side_c) / 2\n return Math.sqrt(p * (p-side_a) * (p-side_b) * (p-side_c))\n };",
|
||||
"heronArea(3, 4, 5); // 6"
|
||||
],
|
||||
"tags": []
|
||||
},
|
||||
"meta": {
|
||||
"archived": true,
|
||||
"hash": "594721a84a8fe31c32482e9f475f5126b7cf499462d9408b3cfaee2021a96a30"
|
||||
}
|
||||
},
|
||||
{
|
||||
"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;",
|
||||
"isSimilar('rt','Rohit'); // true\nisSimilar('tr','Rohit'); // false"
|
||||
],
|
||||
"tags": []
|
||||
},
|
||||
"meta": {
|
||||
"archived": true,
|
||||
"hash": "7a3643ea48d34cc34e33f256cb41ca6a8ad1b8a8830ba2ed3e2354aea3a7bb52"
|
||||
}
|
||||
},
|
||||
{
|
||||
"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": "kmphToMph",
|
||||
"type": "snippet",
|
||||
"attributes": {
|
||||
"fileName": "kmphToMph.md",
|
||||
"text": "Convert kilometers/hour to miles/hour.\n\nMultiply the constant of proportionality with the argument.",
|
||||
"codeBlocks": [
|
||||
"const kmphToMph = (kmph) => 0.621371192 * kmph;",
|
||||
"kmphToMph(10); // 16.09344000614692\nkmphToMph(345.4); // 138.24264965280207"
|
||||
],
|
||||
"tags": []
|
||||
},
|
||||
"meta": {
|
||||
"archived": true,
|
||||
"hash": "eb96ed6f8063723296da25db7282ad732b35c21cfef2bb1424068ff6a789311c"
|
||||
}
|
||||
},
|
||||
{
|
||||
"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": "mphToKmph",
|
||||
"type": "snippet",
|
||||
"attributes": {
|
||||
"fileName": "mphToKmph.md",
|
||||
"text": "Convert miles/hour to kilometers/hour.\n\nMultiply the constant of proportionality with the argument.",
|
||||
"codeBlocks": [
|
||||
"const mphToKmph = (mph) => 1.6093440006146922 * mph;",
|
||||
"mphToKmph(10); // 16.09344000614692\nmphToKmph(85.9); // 138.24264965280207"
|
||||
],
|
||||
"tags": []
|
||||
},
|
||||
"meta": {
|
||||
"archived": true,
|
||||
"hash": "174fc1687b3d809f2984e6e7e3e73af321c2bc0030ab1c05c1b1e2a817664e95"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "pipeLog",
|
||||
"type": "snippet",
|
||||
"attributes": {
|
||||
"fileName": "pipeLog.md",
|
||||
"text": "Logs a value and returns it.\n\nUse `console.log` to log the supplied value, combined with the `||` operator to return it.",
|
||||
"codeBlocks": [
|
||||
"const pipeLog = data => console.log(data) || data;",
|
||||
"pipeLog(1); // logs `1` and returns `1`"
|
||||
],
|
||||
"tags": []
|
||||
},
|
||||
"meta": {
|
||||
"archived": true,
|
||||
"hash": "da9808c8ba24ab48b5407ccf48053281bf12627cbe6e24c1b820bfb1216384cb"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "quickSort",
|
||||
"type": "snippet",
|
||||
"attributes": {
|
||||
"fileName": "quickSort.md",
|
||||
"text": "QuickSort an Array (ascending sort by default).\n\nUse recursion.\nUse `Array.prototype.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": "5495d306c24323a8b16d5706180208f3828b043eb07d19014774cfe7f8c5b00e"
|
||||
}
|
||||
},
|
||||
{
|
||||
"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 squareSum = (...args) => args.reduce((squareSum, number) => squareSum + Math.pow(number, 2), 0);",
|
||||
"squareSum(1, 2, 2); // 9",
|
||||
"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 celsiusToFahrenheit = degrees => 1.8 * degrees + 32;",
|
||||
"celsiusToFahrenheit(33) // 91.4",
|
||||
"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 fahrenheitToCelsius = degrees => (degrees - 32) * 5/9;",
|
||||
"fahrenheitToCelsius(32); // 0",
|
||||
"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 heronArea = (side_a, side_b, side_c) => {\n const p = (side_a + side_b + side_c) / 2\n return Math.sqrt(p * (p-side_a) * (p-side_b) * (p-side_c))\n };",
|
||||
"heronArea(3, 4, 5); // 6",
|
||||
"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",
|
||||
"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;",
|
||||
"isSimilar('rt','Rohit'); // true\nisSimilar('tr','Rohit'); // false",
|
||||
"const kmphToMph = (kmph) => 0.621371192 * kmph;",
|
||||
"kmphToMph(10); // 16.09344000614692\nkmphToMph(345.4); // 138.24264965280207",
|
||||
"``` 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 mphToKmph = (mph) => 1.6093440006146922 * mph;",
|
||||
"mphToKmph(10); // 16.09344000614692\nmphToKmph(85.9); // 138.24264965280207",
|
||||
"const pipeLog = data => console.log(data) || data;",
|
||||
"pipeLog(1); // logs `1` and returns `1`",
|
||||
"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 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 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": "cd05a83026c948903673c6d9482c7c1a1c4da1d53e875c60cae3719d7959f79e"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "removeVowels",
|
||||
"type": "snippet",
|
||||
"attributes": {
|
||||
"fileName": "removeVowels.md",
|
||||
"text": "Returns all the vowels in a `str` replaced by `repl`.\n\nUse `String.prototype.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": "62de33e07d133fc89d71a5091f3f350c007fc60a681e1211ee192b2fb58a2b82"
|
||||
}
|
||||
},
|
||||
{
|
||||
"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.prototype.replace()` with a regular expression to replace `^` with `**`, `String.prototype.split()` to tokenize the string and `Array.prototype.filter()` to remove empty tokens.\nUse `Array.prototype.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": "89dc909e8dc0dfbfcafc60e99a3b895370fc20d1930b21717a8125db3777d6f1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"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"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "squareSum",
|
||||
"type": "snippet",
|
||||
"attributes": {
|
||||
"fileName": "squareSum.md",
|
||||
"text": "Squares each number in an array and then sums the results together.\n\nUse `Array.prototype.reduce()` in combination with `Math.pow()` to iterate over numbers and sum their squares into an accumulator.",
|
||||
"codeBlocks": [
|
||||
"const squareSum = (...args) => args.reduce((squareSum, number) => squareSum + Math.pow(number, 2), 0);",
|
||||
"squareSum(1, 2, 2); // 9"
|
||||
],
|
||||
"tags": []
|
||||
},
|
||||
"meta": {
|
||||
"archived": true,
|
||||
"hash": "5d7d8623e504377f07ac9827eaec17c309a37aefc2346f0dd0a889f4f716f499"
|
||||
}
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"specification": "http://jsonapi.org/format/"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user