Cleanup old files
This commit is contained in:
20
.github/ISSUE_TEMPLATE/bug-report.md
vendored
20
.github/ISSUE_TEMPLATE/bug-report.md
vendored
@ -1,20 +0,0 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
|
||||
---
|
||||
|
||||
## Bug description
|
||||
<!-- A clear and concise description of what the bug is. -->
|
||||
|
||||
## Steps to reproduce
|
||||
<!-- Where did you encounter the bug/What code caused the bug to appear? -->
|
||||
|
||||
## Expected behavior
|
||||
<!-- A clear and concise description of what you expected to happen. -->
|
||||
|
||||
## Screenshots
|
||||
<!-- If applicable, add screenshots to help explain your problem. -->
|
||||
|
||||
## Environment
|
||||
<!-- Provide some information about your OS, Browser or mobile device (if applicable). -->
|
||||
8
.github/ISSUE_TEMPLATE/discussion.md
vendored
8
.github/ISSUE_TEMPLATE/discussion.md
vendored
@ -1,8 +0,0 @@
|
||||
---
|
||||
name: Discussion
|
||||
about: Discuss something with us
|
||||
|
||||
---
|
||||
|
||||
## Description
|
||||
<!-- A clear and concise description of what you want to discuss. -->
|
||||
9
.github/ISSUE_TEMPLATE/feature_request.md
vendored
9
.github/ISSUE_TEMPLATE/feature_request.md
vendored
@ -1,9 +0,0 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
|
||||
---
|
||||
|
||||
## Description
|
||||
<!-- A clear and concise description of what you want to happen. -->
|
||||
<!-- Provide sample code, useful information, possible solutions and examples whenever possible. -->
|
||||
15
.github/PULL_REQUEST_TEMPLATE.md
vendored
15
.github/PULL_REQUEST_TEMPLATE.md
vendored
@ -1,15 +0,0 @@
|
||||
<!-- Use a descriptive title, prefix it with [FIX], [FEATURE] or [ENHANCEMENT] if applicable (use only one) -->
|
||||
|
||||
## Description
|
||||
<!-- Write a detailed description of your changes/additions here -->
|
||||
<!-- If your PR resolves an issue, please state "Resolves #(issue number)" to help maintainers process it faster -->
|
||||
<!-- If you think your PR will cause breaking changes, require changes in the documentation etc, please be so kind as to explain what, where and how -->
|
||||
|
||||
## PR Type
|
||||
- [ ] Snippets, Tests & Tags (new snippets, updated snippets, re-tagging of snippets, added/updated tests)
|
||||
- [ ] Tools, Scripts & Automation (anything related to files in the scripts folder, Gatsby, website, Travis CI or Netlify)
|
||||
- [ ] General, Typos, Misc. & Meta (everything related to content, typos, general stuff and meta files in the repository - e.g. the issue template)
|
||||
- [ ] Other (please specify in the description above)
|
||||
|
||||
## Guidelines
|
||||
- [ ] I have read the guidelines in the [CONTRIBUTING](https://github.com/30-seconds/30-seconds-of-code/blob/master/CONTRIBUTING.md) document.
|
||||
12
.mdlrc
12
.mdlrc
@ -1,12 +0,0 @@
|
||||
rules "MD003", // header style - atx
|
||||
"MD004", // ul list style - asterisk
|
||||
"MD009", // no trailing whitespaces
|
||||
"MD010", // no hard tabs
|
||||
"MD011", // no reversed links
|
||||
"MD018", // no space after hash on atx style header
|
||||
"MD023", // headers should start on the start of the line
|
||||
"MD025", // no multiple h1 headers
|
||||
"MD031", // blanks around fences
|
||||
"MD038", // no spaces inside code elements
|
||||
"MD040" // fenced code blocks need to have a language specified
|
||||
style ".mdlrc.style.rb"
|
||||
@ -1,7 +0,0 @@
|
||||
all
|
||||
rule 'header-style', :style => "atx"
|
||||
rule 'ul-style', :style => "asterisk"
|
||||
|
||||
exclude_rule 'first-header-h1'
|
||||
exclude_rule 'first-line-h1'
|
||||
exclude_rule 'no-inline-html'
|
||||
29
.npmignore
29
.npmignore
@ -1,29 +0,0 @@
|
||||
snippet-template.md
|
||||
tag_database
|
||||
travis.log
|
||||
CONTRIBUTING.md
|
||||
COLLABORATING.md
|
||||
CODE_OF_CONDUCT.md
|
||||
.travis.yml
|
||||
.mdlrc.style.rb
|
||||
.mdlrc
|
||||
.codeclimate.yml
|
||||
test/*
|
||||
glossary/*
|
||||
snippets/*
|
||||
src/*
|
||||
static/*
|
||||
static-parts/*
|
||||
snippet_data/*
|
||||
snippets_archive/*
|
||||
scripts/*
|
||||
locale/*
|
||||
coverage/*
|
||||
docs/*
|
||||
.travis/*
|
||||
.github/*
|
||||
advanced.svg
|
||||
package-lock.json
|
||||
yarn.lock
|
||||
advanced.svg
|
||||
sponsored_by_DigitalOcean.png
|
||||
3421
dist/_30s.es5.js
vendored
3421
dist/_30s.es5.js
vendored
File diff suppressed because it is too large
Load Diff
1
dist/_30s.es5.min.js
vendored
1
dist/_30s.es5.min.js
vendored
File diff suppressed because one or more lines are too long
1596
dist/_30s.esm.js
vendored
1596
dist/_30s.esm.js
vendored
File diff suppressed because it is too large
Load Diff
1991
dist/_30s.js
vendored
1991
dist/_30s.js
vendored
File diff suppressed because it is too large
Load Diff
18
package.json
18
package.json
@ -7,10 +7,7 @@
|
||||
"sideEffects": false,
|
||||
"scripts": {
|
||||
"linter": "node ./scripts/lint.js",
|
||||
"extractor": "extract-snippet-data config.js",
|
||||
"vscoder": "node ./scripts/vscodegen.js",
|
||||
"packager": "node ./scripts/module.js",
|
||||
"test": "jest --verbose --coverage --testPathIgnorePatterns=\".cache\""
|
||||
"extractor": "extract-snippet-data config.js"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@ -30,20 +27,9 @@
|
||||
"dependencies": {},
|
||||
"devDependencies": {
|
||||
"@30-seconds/integration-tools": "^1.3.4",
|
||||
"@babel/core": "^7.5.4",
|
||||
"@babel/plugin-proposal-class-properties": "^7.5.0",
|
||||
"@babel/plugin-syntax-dynamic-import": "^7.2.0",
|
||||
"@babel/preset-env": "^7.5.4",
|
||||
"babel-plugin-transform-es2015-modules-commonjs": "^6.26.2",
|
||||
"babel-plugin-transform-object-rest-spread": "^6.26.0",
|
||||
"eslint": "^5.16.0",
|
||||
"front-matter": "^3.0.2",
|
||||
"fs-extra": "^8.1.0",
|
||||
"jest": "^24.9.0",
|
||||
"kleur": "^3.0.3",
|
||||
"prettier": "^1.18.2",
|
||||
"rollup": "^0.58.2",
|
||||
"rollup-plugin-babel": "^4.0.3",
|
||||
"rollup-plugin-babel-minify": "^4.0.0"
|
||||
"prettier": "^1.18.2"
|
||||
}
|
||||
}
|
||||
|
||||
@ -9,8 +9,8 @@ const fs = require('fs-extra');
|
||||
const cp = require('child_process');
|
||||
const path = require('path');
|
||||
const { green, red } = require('kleur');
|
||||
const util = require('./util');
|
||||
if (util.isTravisCI() && /^Travis build: \d+/g.test(process.env['TRAVIS_COMMIT_MESSAGE'])) {
|
||||
const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env;
|
||||
if (isTravisCI() && /^Travis build: \d+/g.test(process.env['TRAVIS_COMMIT_MESSAGE'])) {
|
||||
console.log(`${green('NOBUILD')} Linting terminated, parent commit is a Travis build!`);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
@ -1,144 +0,0 @@
|
||||
/**
|
||||
* Builds the `_30s` module in UMD and ESM formats.
|
||||
* Also builds the test module file for testing snippets.
|
||||
*/
|
||||
const fs = require('fs-extra');
|
||||
const path = require('path');
|
||||
const { green, red } = require('kleur');
|
||||
const util = require('./util');
|
||||
const { rollup } = require('rollup');
|
||||
const babel = require('rollup-plugin-babel');
|
||||
const minify = require('rollup-plugin-babel-minify');
|
||||
const config = require('../config');
|
||||
|
||||
const MODULE_NAME = `./${config.moduleName}`;
|
||||
const SNIPPETS_PATH = `./${config.snippetPath}`;
|
||||
const SNIPPETS_ARCHIVE_PATH = `./${config.snippetArchivePath}`;
|
||||
const DIST_PATH = `./${config.distPath}`;
|
||||
const ROLLUP_INPUT_FILE = `./${config.rollupInputFile}`;
|
||||
const TEST_MODULE_FILE = `./${config.testModuleFile}`;
|
||||
const CODE_RE = /```\s*js([\s\S]*?)```/;
|
||||
|
||||
/**
|
||||
* Builds the UMD + ESM files to the ./dist directory.
|
||||
*/
|
||||
async function doRollup() {
|
||||
// Plugins
|
||||
const es5 = babel({ presets: ['@babel/preset-env'], plugins: ['transform-object-rest-spread'] });
|
||||
const min = minify({ comments: false });
|
||||
|
||||
const output = format => file => ({
|
||||
format,
|
||||
file,
|
||||
name: MODULE_NAME
|
||||
});
|
||||
|
||||
const umd = output('umd');
|
||||
const esm = output('es');
|
||||
|
||||
const bundle = await rollup({ input: ROLLUP_INPUT_FILE });
|
||||
const bundleES5 = await rollup({ input: ROLLUP_INPUT_FILE, plugins: [es5] });
|
||||
const bundleES5Min = await rollup({
|
||||
input: ROLLUP_INPUT_FILE,
|
||||
plugins: [es5, min]
|
||||
});
|
||||
|
||||
const baseName = `${DIST_PATH}/${MODULE_NAME}`;
|
||||
|
||||
// UMD ES2018
|
||||
await bundle.write(umd(`${baseName}.js`));
|
||||
// ESM ES2018
|
||||
await bundle.write(esm(`${baseName}.esm.js`));
|
||||
// UMD ES5
|
||||
await bundleES5.write(umd(`${baseName}.es5.js`));
|
||||
// UMD ES5 min
|
||||
await bundleES5Min.write(umd(`${baseName}.es5.min.js`));
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the build process.
|
||||
*/
|
||||
async function build() {
|
||||
console.time('Packager');
|
||||
|
||||
let requires = [];
|
||||
let esmExportString = '';
|
||||
let cjsExportString = '';
|
||||
|
||||
try {
|
||||
if (!fs.existsSync(DIST_PATH)) fs.mkdirSync(DIST_PATH);
|
||||
fs.writeFileSync(ROLLUP_INPUT_FILE, '');
|
||||
fs.writeFileSync(TEST_MODULE_FILE, '');
|
||||
|
||||
// Synchronously read all snippets from snippets folder and sort them as necessary (case-insensitive)
|
||||
snippets = util.readSnippets(SNIPPETS_PATH);
|
||||
snippetsArray = Object.keys(snippets).reduce((acc, key) => {
|
||||
acc.push(snippets[key]);
|
||||
return acc;
|
||||
}, []);
|
||||
archivedSnippets = util.readSnippets(SNIPPETS_ARCHIVE_PATH);
|
||||
archivedSnippetsArray = Object.keys(archivedSnippets).reduce((acc, key) => {
|
||||
acc.push(archivedSnippets[key]);
|
||||
return acc;
|
||||
}, []);
|
||||
|
||||
[...snippetsArray, ...archivedSnippetsArray].forEach(snippet => {
|
||||
let code = `${snippet.attributes.codeBlocks.es6}\n`;
|
||||
if(snippet.attributes.tags.includes('node')) {
|
||||
requires.push(code.match(/const.*=.*require\(([^\)]*)\);/g));
|
||||
code = code.replace(/const.*=.*require\(([^\)]*)\);/g, '');
|
||||
}
|
||||
esmExportString += `export ${code}`;
|
||||
cjsExportString += code;
|
||||
});
|
||||
|
||||
requires = [
|
||||
...new Set(
|
||||
requires
|
||||
.filter(Boolean)
|
||||
.map(v =>
|
||||
v[0].replace(
|
||||
'require(',
|
||||
'typeof require !== "undefined" && require('
|
||||
)
|
||||
)
|
||||
)
|
||||
].join('\n');
|
||||
|
||||
fs.writeFileSync(ROLLUP_INPUT_FILE, `${requires}\n\n${esmExportString}`);
|
||||
|
||||
const testExports = `module.exports = {${[...snippetsArray, ...archivedSnippetsArray]
|
||||
.map(v => v.id)
|
||||
.join(',')}}`;
|
||||
|
||||
fs.writeFileSync(
|
||||
TEST_MODULE_FILE,
|
||||
`${requires}\n\n${cjsExportString}\n\n${testExports}`
|
||||
);
|
||||
|
||||
// Check Travis builds - Will skip builds on Travis if not CRON/API
|
||||
if (util.isTravisCI() && util.isNotTravisCronOrAPI()) {
|
||||
fs.unlink(ROLLUP_INPUT_FILE);
|
||||
console.log(
|
||||
`${green(
|
||||
'NOBUILD'
|
||||
)} Module build terminated, not a cron job or a custom build!`
|
||||
);
|
||||
console.timeEnd('Packager');
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
await doRollup();
|
||||
|
||||
// Clean up the temporary input file Rollup used for building the module
|
||||
fs.unlink(ROLLUP_INPUT_FILE);
|
||||
|
||||
console.log(`${green('SUCCESS!')} Snippet module built!`);
|
||||
console.timeEnd('Packager');
|
||||
} catch (err) {
|
||||
console.log(`${red('ERROR!')} During module creation: ${err}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
build();
|
||||
@ -1,12 +0,0 @@
|
||||
// Checks if current environment is Travis CI, Cron builds, API builds
|
||||
const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env;
|
||||
const isTravisCronOrAPI = () =>
|
||||
process.env['TRAVIS_EVENT_TYPE'] === 'cron' ||
|
||||
process.env['TRAVIS_EVENT_TYPE'] === 'api';
|
||||
const isNotTravisCronOrAPI = () => !isTravisCronOrAPI();
|
||||
|
||||
module.exports = {
|
||||
isTravisCI,
|
||||
isTravisCronOrAPI,
|
||||
isNotTravisCronOrAPI,
|
||||
};
|
||||
@ -1,60 +0,0 @@
|
||||
const config = require('../../config');
|
||||
|
||||
const getMarkDownAnchor = paragraphTitle =>
|
||||
paragraphTitle
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[^\w\- ]+/g, '')
|
||||
.replace(/\s/g, '-')
|
||||
.replace(/\-+$/, '');
|
||||
// Creates an object from pairs
|
||||
const objectFromPairs = arr => arr.reduce((a, v) => ((a[v[0]] = v[1]), a), {});
|
||||
// Optimizes nodes in an HTML document
|
||||
const optimizeNodes = (data, regexp, replacer) => {
|
||||
let count = 0;
|
||||
let output = data;
|
||||
do {
|
||||
output = output.replace(regexp, replacer);
|
||||
count = 0;
|
||||
while (regexp.exec(output) !== null) ++count;
|
||||
} while (count > 0);
|
||||
return output;
|
||||
};
|
||||
// Capitalizes the first letter of a string
|
||||
const capitalize = (str, lowerRest = false) =>
|
||||
str.slice(0, 1).toUpperCase() +
|
||||
(lowerRest ? str.slice(1).toLowerCase() : str.slice(1));
|
||||
const prepTaggedData = tagDbData =>
|
||||
[...new Set(Object.entries(tagDbData).map(t => t[1][0]))]
|
||||
.filter(v => v)
|
||||
.sort((a, b) =>
|
||||
capitalize(a, true) === 'Uncategorized'
|
||||
? 1
|
||||
: capitalize(b, true) === 'Uncategorized'
|
||||
? -1
|
||||
: a.localeCompare(b),
|
||||
);
|
||||
const makeExamples = data => {
|
||||
data =
|
||||
data.slice(0, data.lastIndexOf(`\`\`\`${config.language.short}`)).trim() +
|
||||
misc.collapsible(
|
||||
'Examples',
|
||||
data.slice(
|
||||
data.lastIndexOf(`\`\`\`${config.language.short}`),
|
||||
data.lastIndexOf('```'),
|
||||
) + data.slice(data.lastIndexOf('```')),
|
||||
);
|
||||
return `${data}\n<br>${misc.link(
|
||||
'⬆ Back to top',
|
||||
misc.anchor('Contents'),
|
||||
)}\n\n`;
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
getMarkDownAnchor,
|
||||
objectFromPairs,
|
||||
optimizeNodes,
|
||||
capitalize,
|
||||
prepTaggedData,
|
||||
makeExamples,
|
||||
};
|
||||
@ -1,37 +0,0 @@
|
||||
const {
|
||||
isTravisCI,
|
||||
isTravisCronOrAPI,
|
||||
isNotTravisCronOrAPI,
|
||||
} = require('./environmentCheck');
|
||||
const {
|
||||
getMarkDownAnchor,
|
||||
objectFromPairs,
|
||||
optimizeNodes,
|
||||
capitalize,
|
||||
prepTaggedData,
|
||||
makeExamples,
|
||||
} = require('./helpers');
|
||||
const {
|
||||
getFilesInDir,
|
||||
hashData,
|
||||
getCodeBlocks,
|
||||
getTextualContent,
|
||||
readSnippets,
|
||||
} = require('./snippetParser');
|
||||
|
||||
module.exports = {
|
||||
isTravisCI,
|
||||
isTravisCronOrAPI,
|
||||
isNotTravisCronOrAPI,
|
||||
getMarkDownAnchor,
|
||||
objectFromPairs,
|
||||
optimizeNodes,
|
||||
capitalize,
|
||||
prepTaggedData,
|
||||
makeExamples,
|
||||
getFilesInDir,
|
||||
hashData,
|
||||
getCodeBlocks,
|
||||
getTextualContent,
|
||||
readSnippets,
|
||||
};
|
||||
@ -1,125 +0,0 @@
|
||||
const fs = require('fs-extra'),
|
||||
path = require('path'),
|
||||
{ red } = require('kleur'),
|
||||
crypto = require('crypto'),
|
||||
frontmatter = require('front-matter'),
|
||||
babel = require('@babel/core');
|
||||
const config = require('../../config');
|
||||
const execSync = require('child_process').execSync;
|
||||
|
||||
// Reade all files in a directory
|
||||
const getFilesInDir = (directoryPath, withPath, exclude = null) => {
|
||||
try {
|
||||
let directoryFilenames = fs.readdirSync(directoryPath);
|
||||
directoryFilenames.sort((a, b) => {
|
||||
a = a.toLowerCase();
|
||||
b = b.toLowerCase();
|
||||
if (a < b) return -1;
|
||||
if (a > b) return 1;
|
||||
return 0;
|
||||
});
|
||||
|
||||
if (withPath) {
|
||||
// a hacky way to do conditional array.map
|
||||
return directoryFilenames.reduce((fileNames, fileName) => {
|
||||
if (
|
||||
exclude == null ||
|
||||
!exclude.some(toExclude => fileName === toExclude)
|
||||
)
|
||||
fileNames.push(`${directoryPath}/${fileName}`);
|
||||
return fileNames;
|
||||
}, []);
|
||||
}
|
||||
return directoryFilenames.filter(v => v !== 'README.md');
|
||||
} catch (err) {
|
||||
console.log(`${red('ERROR!')} During snippet loading: ${err}`);
|
||||
process.exit(1);
|
||||
}
|
||||
};
|
||||
// Creates a hash for a value using the SHA-256 algorithm.
|
||||
const hashData = val =>
|
||||
crypto
|
||||
.createHash('sha256')
|
||||
.update(val)
|
||||
.digest('hex');
|
||||
// Gets the code blocks for a snippet file.
|
||||
const getCodeBlocks = str => {
|
||||
const regex = /```[.\S\s]*?```/g;
|
||||
let results = [];
|
||||
let m = null;
|
||||
while ((m = regex.exec(str)) !== null) {
|
||||
if (m.index === regex.lastIndex) regex.lastIndex += 1;
|
||||
|
||||
m.forEach((match, groupIndex) => {
|
||||
results.push(match);
|
||||
});
|
||||
}
|
||||
const replacer = new RegExp(
|
||||
`\`\`\`${config.language.short}([\\s\\S]*?)\`\`\``,
|
||||
'g',
|
||||
);
|
||||
results = results.map(v => v.replace(replacer, '$1').trim());
|
||||
return {
|
||||
es6: results[0],
|
||||
es5: babel.transformSync(results[0], { presets: ['@babel/preset-env'] }).code.replace('"use strict";\n\n', ''),
|
||||
example: results[1],
|
||||
};
|
||||
};
|
||||
// Gets the textual content for a snippet file.
|
||||
const getTextualContent = str => {
|
||||
const regex = /([\s\S]*?)```/g;
|
||||
const results = [];
|
||||
let m = null;
|
||||
while ((m = regex.exec(str)) !== null) {
|
||||
if (m.index === regex.lastIndex) regex.lastIndex += 1;
|
||||
|
||||
m.forEach((match, groupIndex) => {
|
||||
results.push(match);
|
||||
});
|
||||
}
|
||||
if (!results.length) return str.replace(/\r\n/g, '\n');
|
||||
return results[1].replace(/\r\n/g, '\n');
|
||||
};
|
||||
|
||||
// Synchronously read all snippets and sort them as necessary (case-insensitive)
|
||||
const readSnippets = snippetsPath => {
|
||||
const snippetFilenames = getFilesInDir(snippetsPath, false);
|
||||
|
||||
let snippets = {};
|
||||
try {
|
||||
for (let snippet of snippetFilenames) {
|
||||
let data = frontmatter(
|
||||
fs.readFileSync(path.join(snippetsPath, snippet), 'utf8'),
|
||||
);
|
||||
snippets[snippet] = {
|
||||
id: snippet.slice(0, -3),
|
||||
title: data.attributes.title,
|
||||
type: 'snippet',
|
||||
attributes: {
|
||||
fileName: snippet,
|
||||
text: getTextualContent(data.body),
|
||||
codeBlocks: getCodeBlocks(data.body),
|
||||
tags: data.attributes.tags.split(',').map(t => t.trim()),
|
||||
},
|
||||
meta: {
|
||||
hash: hashData(data.body),
|
||||
firstSeen: execSync(`git log --diff-filter=A --pretty=format:%at -- snippets/${snippet}`).toString(),
|
||||
lastUpdated: execSync(`git log -n 1 --pretty=format:%at -- snippets/${snippet}`).toString(),
|
||||
updateCount: execSync(`git log --pretty=%H -- snippets/${snippet}`).toString().split('\n').length
|
||||
},
|
||||
};
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(`${red('ERROR!')} During snippet loading: ${err}`);
|
||||
process.exit(1);
|
||||
}
|
||||
return snippets;
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
getFilesInDir,
|
||||
hashData,
|
||||
getCodeBlocks,
|
||||
getTextualContent,
|
||||
readSnippets
|
||||
};
|
||||
@ -1,33 +0,0 @@
|
||||
/*
|
||||
This is the VSCode generator script that generates the vscode_snippets/snippets.json file.
|
||||
Run using `npm run vscoder`.
|
||||
*/
|
||||
// Load modules
|
||||
const fs = require('fs-extra');
|
||||
const path = require('path');
|
||||
const { green } = require('kleur');
|
||||
let snippetsData = require('../snippet_data/snippets.json');
|
||||
// Paths
|
||||
const OUTPUT_PATH = './vscode_snippets';
|
||||
console.time('VSCoder');
|
||||
// Read and format data
|
||||
let vscodeData = snippetsData.data.filter(v => !v.meta.archived ).reduce((acc, v) => {
|
||||
acc[v.id] = {
|
||||
prefix: `30s_${v.id}`,
|
||||
body: v.attributes.codeBlocks.es6.replace(/\r/g, '').split('\n'),
|
||||
description: v.attributes.text.slice(0, v.attributes.text.indexOf('\r\n\r\n'))
|
||||
};
|
||||
return acc;
|
||||
}, {});
|
||||
// Write data
|
||||
fs.writeFileSync(
|
||||
path.join(OUTPUT_PATH, 'snippets.json'),
|
||||
JSON.stringify(vscodeData, null, 2)
|
||||
);
|
||||
// Display messages and time
|
||||
console.log(
|
||||
`${green(
|
||||
'SUCCESS!'
|
||||
)} vscode_snippets/snippets.json file generated!`
|
||||
);
|
||||
console.timeEnd('VSCoder');
|
||||
@ -1,406 +0,0 @@
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": "binarySearch",
|
||||
"type": "snippetListing",
|
||||
"title": "binarySearch",
|
||||
"attributes": {
|
||||
"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`.\n\n",
|
||||
"tags": [
|
||||
"algorithm",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "48d538bccbc7be7e78b8f6a69004055c4b21324d2c8d7cbc4cba0cd42e4f67fb"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "celsiusToFahrenheit",
|
||||
"type": "snippetListing",
|
||||
"title": "celsiusToFahrenheit",
|
||||
"attributes": {
|
||||
"text": "Celsius to Fahrenheit temperature conversion.\n\nFollows the conversion formula `F = 1.8C + 32`.\n\n",
|
||||
"tags": [
|
||||
"math",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "d59410c4fa0ea5173af553068c1e1d4ef931695e084c50cdd8166b0cd0278722"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "cleanObj",
|
||||
"type": "snippetListing",
|
||||
"title": "cleanObj",
|
||||
"attributes": {
|
||||
"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.\n\n",
|
||||
"tags": [
|
||||
"object",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "aaefc9bd6e9170001fe4754b1bc7bb9808ab97a5bec7fc6ceb1193be2f8009b1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "collatz",
|
||||
"type": "snippetListing",
|
||||
"title": "collatz",
|
||||
"attributes": {
|
||||
"text": "Applies the Collatz algorithm.\n\nIf `n` is even, return `n/2`. Otherwise, return `3n+1`.\n\n",
|
||||
"tags": [
|
||||
"math",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "0280a47e49f505d5f10e0e0bd2c3ab28a6ea2b931fc83f63155f8395f64a1840"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "countVowels",
|
||||
"type": "snippetListing",
|
||||
"title": "countVowels",
|
||||
"attributes": {
|
||||
"text": "Returns `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`.\n\n",
|
||||
"tags": [
|
||||
"string",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "dbc7e4369d07c299fb69df1142c0c209fead5e159574de6144bff614848ec1c5"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "factors",
|
||||
"type": "snippetListing",
|
||||
"title": "factors",
|
||||
"attributes": {
|
||||
"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._\n\n",
|
||||
"tags": [
|
||||
"math",
|
||||
"intermediate"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "8eed39b1040d6472e2fd619abf744848d30f12eebffda2711966c616d474524f"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "fahrenheitToCelsius",
|
||||
"type": "snippetListing",
|
||||
"title": "fahrenheitToCelsius",
|
||||
"attributes": {
|
||||
"text": "Fahrenheit to Celsius temperature conversion.\n\nFollows the conversion formula `C = (F - 32) * 5/9`.\n\n",
|
||||
"tags": [
|
||||
"math",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "a39ade2ae05ad86443446b335dbc019e3ac734fe0c1a542d50b929c554040fc0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "fibonacciCountUntilNum",
|
||||
"type": "snippetListing",
|
||||
"title": "fibonacciCountUntilNum",
|
||||
"attributes": {
|
||||
"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`.\n\n",
|
||||
"tags": [
|
||||
"math",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "35488eb0f56b59035b56cc67fa0a5e1a970162ede4aafd97ebb2b4009c321c01"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "fibonacciUntilNum",
|
||||
"type": "snippetListing",
|
||||
"title": "fibonacciUntilNum",
|
||||
"attributes": {
|
||||
"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.\n\n",
|
||||
"tags": [
|
||||
"math",
|
||||
"intermediate"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "6ff845c13444a06569be548ce9e69900b7001516c44c315795f34b31e9baa833"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "heronArea",
|
||||
"type": "snippetListing",
|
||||
"title": "heronArea",
|
||||
"attributes": {
|
||||
"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.\n\n",
|
||||
"tags": [
|
||||
"math",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "d0be594ab377cbeb2910308610af5890b3468c06e7567cd0995a84d11aaccf47"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "howManyTimes",
|
||||
"type": "snippetListing",
|
||||
"title": "howManyTimes",
|
||||
"attributes": {
|
||||
"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`.\n\n",
|
||||
"tags": [
|
||||
"math",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "52ffa251dfc4e2bec7160a9066ef24a8c3047706e1ad2837f9d987cdf4d5f73e"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "httpDelete",
|
||||
"type": "snippetListing",
|
||||
"title": "httpDelete",
|
||||
"attributes": {
|
||||
"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.\n\n",
|
||||
"tags": [
|
||||
"browser",
|
||||
"intermediate"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "4fccb2abe966313a742d13965ee46cfd1094763a2697591eddb19c1c5af1db7e"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "httpPut",
|
||||
"type": "snippetListing",
|
||||
"title": "httpPut",
|
||||
"attributes": {
|
||||
"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.\n\n",
|
||||
"tags": [
|
||||
"browser",
|
||||
"intermediate"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "7eb4b1ffc1cbe28c10190bb82b7731ade2d79e78a5569bdee62af33a1020f2f5"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "isArmstrongNumber",
|
||||
"type": "snippetListing",
|
||||
"title": "isArmstrongNumber",
|
||||
"attributes": {
|
||||
"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`.\n\n",
|
||||
"tags": [
|
||||
"math",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "71ebcdb61794d8222fcf447509d206ffb10dc8068072a88c6b587e21e76fc7f2"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "isSimilar",
|
||||
"type": "snippetListing",
|
||||
"title": "isSimilar",
|
||||
"attributes": {
|
||||
"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).\n\n",
|
||||
"tags": [
|
||||
"string",
|
||||
"intermediate"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "250615cfc281e99014b97d054c722d3ba6aa4190ccf66dd719e530ec80aec3bd"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "JSONToDate",
|
||||
"type": "snippetListing",
|
||||
"title": "JSONToDate",
|
||||
"attributes": {
|
||||
"text": "Converts a JSON object to a date.\n\nUse `Date()`, to convert dates in JSON format to readable format (`dd/mm/yyyy`).\n\n",
|
||||
"tags": [
|
||||
"object",
|
||||
"date",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "33e1e304fead4088971a60d4da974d0e9380370560f383ddb1ddc14e628df18b"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "kmphToMph",
|
||||
"type": "snippetListing",
|
||||
"title": "kmphToMph",
|
||||
"attributes": {
|
||||
"text": "Convert kilometers/hour to miles/hour.\n\nMultiply the constant of proportionality with the argument.\n\n",
|
||||
"tags": [
|
||||
"math",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "f885a599e1185f8480445e1eb0c4a5cb8bf33948d7893f013dd4e8085478fe7a"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "levenshteinDistance",
|
||||
"type": "snippetListing",
|
||||
"title": "levenshteinDistance",
|
||||
"attributes": {
|
||||
"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.\n\n",
|
||||
"tags": [
|
||||
"algorithm",
|
||||
"advanced"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "9f71509c5937cb68b65ef31893b1ad723ce6690e8ecd161707cb222ab67a475b"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "mphToKmph",
|
||||
"type": "snippetListing",
|
||||
"title": "mphToKmph",
|
||||
"attributes": {
|
||||
"text": "Convert miles/hour to kilometers/hour.\n\nMultiply the constant of proportionality with the argument.\n\n",
|
||||
"tags": [
|
||||
"math",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "d1ec7968c8f8c48642a3f91878db84330231bdf84bf74633dc0754456e951338"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "objectToEntries",
|
||||
"type": "snippetListing",
|
||||
"title": "objectToEntries",
|
||||
"attributes": {
|
||||
"text": "Creates an array of key-value pair arrays from an object.\n\nUse `Object.keys()` and `Array.prototype.map()` to iterate over the object's keys and produce an array with key-value pairs.\n\n",
|
||||
"tags": [
|
||||
"object",
|
||||
"array",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "da5ab6a4f794f33d985d8a82794414b80913e63214a80d78c87bbda9638faa4f"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "pipeLog",
|
||||
"type": "snippetListing",
|
||||
"title": "pipeLog",
|
||||
"attributes": {
|
||||
"text": "Logs a value and returns it.\n\nUse `console.log` to log the supplied value, combined with the `||` operator to return it.\n\n",
|
||||
"tags": [
|
||||
"utility",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "dba6fa36424c23d601c4e463463a5f23d32b51d8b058a6c5020d3b4098a65e51"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "quickSort",
|
||||
"type": "snippetListing",
|
||||
"title": "quickSort",
|
||||
"attributes": {
|
||||
"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.\n\n",
|
||||
"tags": [
|
||||
"algorithm",
|
||||
"recursion",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "5c26069a02342eadd2c5ba2656a1b211da8f1a94da03c2cc31a5090be556d7b7"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "removeVowels",
|
||||
"type": "snippetListing",
|
||||
"title": "removeVowels",
|
||||
"attributes": {
|
||||
"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 `''`.\n\n",
|
||||
"tags": [
|
||||
"string",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "5c6f8e292db8506568de362aa63890047f9d5a65d35143cfca1e27562642c414"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "solveRPN",
|
||||
"type": "snippetListing",
|
||||
"title": "solveRPN",
|
||||
"attributes": {
|
||||
"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.\n\n",
|
||||
"tags": [
|
||||
"algorithm",
|
||||
"advanced"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "0c37cf46586652fd20dfa9ca682d3635f01fe61c46864f9773f6b258e8f3b6f6"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "speechSynthesis",
|
||||
"type": "snippetListing",
|
||||
"title": "speechSynthesis",
|
||||
"attributes": {
|
||||
"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).\n\n",
|
||||
"tags": [
|
||||
"browser",
|
||||
"intermediate"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "9859dbef05dc0398e825150b50fccfea370583cf6b807c00c9e83b769d2b51c0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "squareSum",
|
||||
"type": "snippetListing",
|
||||
"title": "squareSum",
|
||||
"attributes": {
|
||||
"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.\n\n",
|
||||
"tags": [
|
||||
"math",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "19837ac6714833e9c5fe698811e171cc2598f7b9405a4847b33b8d3b35debf8a"
|
||||
}
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"specification": "http://jsonapi.org/format/",
|
||||
"type": "snippetListingArray",
|
||||
"scope": "./snippets_archive",
|
||||
"language": {
|
||||
"short": "js",
|
||||
"long": "JavaScript"
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,666 +0,0 @@
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": "binarySearch",
|
||||
"title": "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`.\n\n",
|
||||
"codeBlocks": {
|
||||
"es6": "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};",
|
||||
"es5": "var binarySearch = function binarySearch(arr, val) {\n var start = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;\n var end = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : arr.length - 1;\n if (start > end) return -1;\n var 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};",
|
||||
"example": "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": [
|
||||
"algorithm",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "48d538bccbc7be7e78b8f6a69004055c4b21324d2c8d7cbc4cba0cd42e4f67fb",
|
||||
"firstSeen": "1515453617",
|
||||
"lastUpdated": "1565681352",
|
||||
"updateCount": 6,
|
||||
"authorCount": 3
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "celsiusToFahrenheit",
|
||||
"title": "celsiusToFahrenheit",
|
||||
"type": "snippet",
|
||||
"attributes": {
|
||||
"fileName": "celsiusToFahrenheit.md",
|
||||
"text": "Celsius to Fahrenheit temperature conversion.\n\nFollows the conversion formula `F = 1.8C + 32`.\n\n",
|
||||
"codeBlocks": {
|
||||
"es6": "const celsiusToFahrenheit = degrees => 1.8 * degrees + 32;",
|
||||
"es5": "var celsiusToFahrenheit = function celsiusToFahrenheit(degrees) {\n return 1.8 * degrees + 32;\n};",
|
||||
"example": "celsiusToFahrenheit(33) // 91.4"
|
||||
},
|
||||
"tags": [
|
||||
"math",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "d59410c4fa0ea5173af553068c1e1d4ef931695e084c50cdd8166b0cd0278722",
|
||||
"firstSeen": "1539711071",
|
||||
"lastUpdated": "1565681352",
|
||||
"updateCount": 3,
|
||||
"authorCount": 2
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "cleanObj",
|
||||
"title": "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.\n\n",
|
||||
"codeBlocks": {
|
||||
"es6": "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};",
|
||||
"es5": "var cleanObj = function cleanObj(obj) {\n var keysToKeep = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];\n var childIndicator = arguments.length > 2 ? arguments[2] : undefined;\n Object.keys(obj).forEach(function (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};",
|
||||
"example": "const testObj = { a: 1, b: 2, children: { a: 1, b: 2 } };\ncleanObj(testObj, ['a'], 'children'); // { a: 1, children : { a: 1}}"
|
||||
},
|
||||
"tags": [
|
||||
"object",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "aaefc9bd6e9170001fe4754b1bc7bb9808ab97a5bec7fc6ceb1193be2f8009b1",
|
||||
"firstSeen": "1516359948",
|
||||
"lastUpdated": "1565681352",
|
||||
"updateCount": 3,
|
||||
"authorCount": 2
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "collatz",
|
||||
"title": "collatz",
|
||||
"type": "snippet",
|
||||
"attributes": {
|
||||
"fileName": "collatz.md",
|
||||
"text": "Applies the Collatz algorithm.\n\nIf `n` is even, return `n/2`. Otherwise, return `3n+1`.\n\n",
|
||||
"codeBlocks": {
|
||||
"es6": "const collatz = n => (n % 2 === 0 ? n / 2 : 3 * n + 1);",
|
||||
"es5": "var collatz = function collatz(n) {\n return n % 2 === 0 ? n / 2 : 3 * n + 1;\n};",
|
||||
"example": "collatz(8); // 4"
|
||||
},
|
||||
"tags": [
|
||||
"math",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "0280a47e49f505d5f10e0e0bd2c3ab28a6ea2b931fc83f63155f8395f64a1840",
|
||||
"firstSeen": "1515162834",
|
||||
"lastUpdated": "1565681352",
|
||||
"updateCount": 4,
|
||||
"authorCount": 2
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "countVowels",
|
||||
"title": "countVowels",
|
||||
"type": "snippet",
|
||||
"attributes": {
|
||||
"fileName": "countVowels.md",
|
||||
"text": "Returns `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`.\n\n",
|
||||
"codeBlocks": {
|
||||
"es6": "const countVowels = str => (str.match(/[aeiou]/gi) || []).length;",
|
||||
"es5": "var countVowels = function countVowels(str) {\n return (str.match(/[aeiou]/gi) || []).length;\n};",
|
||||
"example": "countVowels('foobar'); // 3\ncountVowels('gym'); // 0"
|
||||
},
|
||||
"tags": [
|
||||
"string",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "dbc7e4369d07c299fb69df1142c0c209fead5e159574de6144bff614848ec1c5",
|
||||
"firstSeen": "1515500549",
|
||||
"lastUpdated": "1584841330",
|
||||
"updateCount": 4,
|
||||
"authorCount": 3
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "factors",
|
||||
"title": "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._\n\n",
|
||||
"codeBlocks": {
|
||||
"es6": "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};",
|
||||
"es5": "var factors = function factors(num) {\n var primes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n\n var isPrime = function isPrime(num) {\n var boundary = Math.floor(Math.sqrt(num));\n\n for (var i = 2; i <= boundary; i++) {\n if (num % i === 0) return false;\n }\n\n return num >= 2;\n };\n\n var isNeg = num < 0;\n num = isNeg ? -num : num;\n var array = Array.from({\n length: num - 1\n }).map(function (val, i) {\n return num % (i + 2) === 0 ? i + 2 : false;\n }).filter(function (val) {\n return val;\n });\n if (isNeg) array = array.reduce(function (acc, val) {\n acc.push(val);\n acc.push(-val);\n return acc;\n }, []);\n return primes ? array.filter(isPrime) : array;\n};",
|
||||
"example": "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": [
|
||||
"math",
|
||||
"intermediate"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "8eed39b1040d6472e2fd619abf744848d30f12eebffda2711966c616d474524f",
|
||||
"firstSeen": "1515162834",
|
||||
"lastUpdated": "1565681352",
|
||||
"updateCount": 4,
|
||||
"authorCount": 3
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "fahrenheitToCelsius",
|
||||
"title": "fahrenheitToCelsius",
|
||||
"type": "snippet",
|
||||
"attributes": {
|
||||
"fileName": "fahrenheitToCelsius.md",
|
||||
"text": "Fahrenheit to Celsius temperature conversion.\n\nFollows the conversion formula `C = (F - 32) * 5/9`.\n\n",
|
||||
"codeBlocks": {
|
||||
"es6": "const fahrenheitToCelsius = degrees => (degrees - 32) * 5/9;",
|
||||
"es5": "var fahrenheitToCelsius = function fahrenheitToCelsius(degrees) {\n return (degrees - 32) * 5 / 9;\n};",
|
||||
"example": "fahrenheitToCelsius(32); // 0"
|
||||
},
|
||||
"tags": [
|
||||
"math",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "a39ade2ae05ad86443446b335dbc019e3ac734fe0c1a542d50b929c554040fc0",
|
||||
"firstSeen": "1539711071",
|
||||
"lastUpdated": "1565681352",
|
||||
"updateCount": 3,
|
||||
"authorCount": 2
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "fibonacciCountUntilNum",
|
||||
"title": "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`.\n\n",
|
||||
"codeBlocks": {
|
||||
"es6": "const fibonacciCountUntilNum = num =>\n Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));",
|
||||
"es5": "var fibonacciCountUntilNum = function fibonacciCountUntilNum(num) {\n return Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));\n};",
|
||||
"example": "fibonacciCountUntilNum(10); // 7"
|
||||
},
|
||||
"tags": [
|
||||
"math",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "35488eb0f56b59035b56cc67fa0a5e1a970162ede4aafd97ebb2b4009c321c01",
|
||||
"firstSeen": "1515162834",
|
||||
"lastUpdated": "1565681352",
|
||||
"updateCount": 3,
|
||||
"authorCount": 2
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "fibonacciUntilNum",
|
||||
"title": "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.\n\n",
|
||||
"codeBlocks": {
|
||||
"es6": "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};",
|
||||
"es5": "var fibonacciUntilNum = function fibonacciUntilNum(num) {\n var n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));\n return Array.from({\n length: n\n }).reduce(function (acc, val, i) {\n return acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i);\n }, []);\n};",
|
||||
"example": "fibonacciUntilNum(10); // [ 0, 1, 1, 2, 3, 5, 8 ]"
|
||||
},
|
||||
"tags": [
|
||||
"math",
|
||||
"intermediate"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "6ff845c13444a06569be548ce9e69900b7001516c44c315795f34b31e9baa833",
|
||||
"firstSeen": "1515162834",
|
||||
"lastUpdated": "1565681352",
|
||||
"updateCount": 4,
|
||||
"authorCount": 3
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "heronArea",
|
||||
"title": "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.\n\n",
|
||||
"codeBlocks": {
|
||||
"es6": "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 };",
|
||||
"es5": "var heronArea = function heronArea(side_a, side_b, side_c) {\n var p = (side_a + side_b + side_c) / 2;\n return Math.sqrt(p * (p - side_a) * (p - side_b) * (p - side_c));\n};",
|
||||
"example": "heronArea(3, 4, 5); // 6"
|
||||
},
|
||||
"tags": [
|
||||
"math",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "d0be594ab377cbeb2910308610af5890b3468c06e7567cd0995a84d11aaccf47",
|
||||
"firstSeen": "1538938431",
|
||||
"lastUpdated": "1565681352",
|
||||
"updateCount": 3,
|
||||
"authorCount": 3
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "howManyTimes",
|
||||
"title": "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`.\n\n",
|
||||
"codeBlocks": {
|
||||
"es6": "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};",
|
||||
"es5": "var howManyTimes = function howManyTimes(num, divisor) {\n if (divisor === 1 || divisor === -1) return Infinity;\n if (divisor === 0) return 0;\n var i = 0;\n\n while (Number.isInteger(num / divisor)) {\n i++;\n num = num / divisor;\n }\n\n return i;\n};",
|
||||
"example": "howManyTimes(100, 2); // 2\nhowManyTimes(100, 2.5); // 2\nhowManyTimes(100, 0); // 0\nhowManyTimes(100, -1); // Infinity"
|
||||
},
|
||||
"tags": [
|
||||
"math",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "52ffa251dfc4e2bec7160a9066ef24a8c3047706e1ad2837f9d987cdf4d5f73e",
|
||||
"firstSeen": "1515162834",
|
||||
"lastUpdated": "1565681352",
|
||||
"updateCount": 3,
|
||||
"authorCount": 2
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "httpDelete",
|
||||
"title": "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.\n\n",
|
||||
"codeBlocks": {
|
||||
"es6": "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};",
|
||||
"es5": "var httpDelete = function httpDelete(url, callback) {\n var err = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : console.error;\n var request = new XMLHttpRequest();\n request.open('DELETE', url, true);\n\n request.onload = function () {\n return callback(request);\n };\n\n request.onerror = function () {\n return err(request);\n };\n\n request.send();\n};",
|
||||
"example": "httpDelete('https://website.com/users/123', request => {\n console.log(request.responseText);\n}); // 'Deletes a user from the database'"
|
||||
},
|
||||
"tags": [
|
||||
"browser",
|
||||
"intermediate"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "4fccb2abe966313a742d13965ee46cfd1094763a2697591eddb19c1c5af1db7e",
|
||||
"firstSeen": "1515608606",
|
||||
"lastUpdated": "1565681352",
|
||||
"updateCount": 4,
|
||||
"authorCount": 3
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "httpPut",
|
||||
"title": "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.\n\n",
|
||||
"codeBlocks": {
|
||||
"es6": "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};",
|
||||
"es5": "var httpPut = function httpPut(url, data, callback) {\n var err = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : console.error;\n var request = new XMLHttpRequest();\n request.open(\"PUT\", url, true);\n request.setRequestHeader('Content-type', 'application/json; charset=utf-8');\n\n request.onload = function () {\n return callback(request);\n };\n\n request.onerror = function () {\n return err(request);\n };\n\n request.send(data);\n};",
|
||||
"example": "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": [
|
||||
"browser",
|
||||
"intermediate"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "7eb4b1ffc1cbe28c10190bb82b7731ade2d79e78a5569bdee62af33a1020f2f5",
|
||||
"firstSeen": "1515608606",
|
||||
"lastUpdated": "1565681352",
|
||||
"updateCount": 4,
|
||||
"authorCount": 3
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "isArmstrongNumber",
|
||||
"title": "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`.\n\n",
|
||||
"codeBlocks": {
|
||||
"es6": "const isArmstrongNumber = digits =>\n (arr => arr.reduce((a, d) => a + parseInt(d) ** arr.length, 0) == digits)(\n (digits + '').split('')\n );",
|
||||
"es5": "var isArmstrongNumber = function isArmstrongNumber(digits) {\n return function (arr) {\n return arr.reduce(function (a, d) {\n return a + Math.pow(parseInt(d), arr.length);\n }, 0) == digits;\n }((digits + '').split(''));\n};",
|
||||
"example": "isArmstrongNumber(1634); // true\nisArmstrongNumber(56); // false"
|
||||
},
|
||||
"tags": [
|
||||
"math",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "71ebcdb61794d8222fcf447509d206ffb10dc8068072a88c6b587e21e76fc7f2",
|
||||
"firstSeen": "1515162834",
|
||||
"lastUpdated": "1565681352",
|
||||
"updateCount": 3,
|
||||
"authorCount": 2
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "isSimilar",
|
||||
"title": "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).\n\n",
|
||||
"codeBlocks": {
|
||||
"es6": "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;",
|
||||
"es5": "function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }\n\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance\"); }\n\nfunction _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === \"[object Arguments]\") return Array.from(iter); }\n\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }\n\nvar isSimilar = function isSimilar(pattern, str) {\n return _toConsumableArray(str).reduce(function (matchIndex, _char) {\n return _char.toLowerCase() === (pattern[matchIndex] || '').toLowerCase() ? matchIndex + 1 : matchIndex;\n }, 0) === pattern.length;\n};",
|
||||
"example": "isSimilar('rt','Rohit'); // true\nisSimilar('tr','Rohit'); // false"
|
||||
},
|
||||
"tags": [
|
||||
"string",
|
||||
"intermediate"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "250615cfc281e99014b97d054c722d3ba6aa4190ccf66dd719e530ec80aec3bd",
|
||||
"firstSeen": "1519637807",
|
||||
"lastUpdated": "1565681352",
|
||||
"updateCount": 7,
|
||||
"authorCount": 5
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "JSONToDate",
|
||||
"title": "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`).\n\n",
|
||||
"codeBlocks": {
|
||||
"es6": "const JSONToDate = arr => {\n const dt = new Date(parseInt(arr.toString().substr(6)));\n return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`;\n};",
|
||||
"es5": "var JSONToDate = function JSONToDate(arr) {\n var dt = new Date(parseInt(arr.toString().substr(6)));\n return \"\".concat(dt.getDate(), \"/\").concat(dt.getMonth() + 1, \"/\").concat(dt.getFullYear());\n};",
|
||||
"example": "JSONToDate(/Date(1489525200000)/); // \"14/3/2017\""
|
||||
},
|
||||
"tags": [
|
||||
"object",
|
||||
"date",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "33e1e304fead4088971a60d4da974d0e9380370560f383ddb1ddc14e628df18b",
|
||||
"firstSeen": "1515162834",
|
||||
"lastUpdated": "1565681352",
|
||||
"updateCount": 3,
|
||||
"authorCount": 2
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "kmphToMph",
|
||||
"title": "kmphToMph",
|
||||
"type": "snippet",
|
||||
"attributes": {
|
||||
"fileName": "kmphToMph.md",
|
||||
"text": "Convert kilometers/hour to miles/hour.\n\nMultiply the constant of proportionality with the argument.\n\n",
|
||||
"codeBlocks": {
|
||||
"es6": "const kmphToMph = (kmph) => 0.621371192 * kmph;",
|
||||
"es5": "var kmphToMph = function kmphToMph(kmph) {\n return 0.621371192 * kmph;\n};",
|
||||
"example": "kmphToMph(10); // 16.09344000614692\nkmphToMph(345.4); // 138.24264965280207"
|
||||
},
|
||||
"tags": [
|
||||
"math",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "f885a599e1185f8480445e1eb0c4a5cb8bf33948d7893f013dd4e8085478fe7a",
|
||||
"firstSeen": "1539710543",
|
||||
"lastUpdated": "1565681352",
|
||||
"updateCount": 3,
|
||||
"authorCount": 2
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "levenshteinDistance",
|
||||
"title": "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.\n\n",
|
||||
"codeBlocks": {
|
||||
"es6": "const 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};",
|
||||
"es5": "var levenshteinDistance = function levenshteinDistance(string1, string2) {\n if (string1.length === 0) return string2.length;\n if (string2.length === 0) return string1.length;\n var matrix = Array(string2.length + 1).fill(0).map(function (x, i) {\n return [i];\n });\n matrix[0] = Array(string1.length + 1).fill(0).map(function (x, i) {\n return i;\n });\n\n for (var i = 1; i <= string2.length; i++) {\n for (var 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(matrix[i - 1][j - 1] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j] + 1);\n }\n }\n }\n\n return matrix[string2.length][string1.length];\n};",
|
||||
"example": "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": [
|
||||
"algorithm",
|
||||
"advanced"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "9f71509c5937cb68b65ef31893b1ad723ce6690e8ecd161707cb222ab67a475b",
|
||||
"firstSeen": "1519637486",
|
||||
"lastUpdated": "1565681352",
|
||||
"updateCount": 7,
|
||||
"authorCount": 4
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "mphToKmph",
|
||||
"title": "mphToKmph",
|
||||
"type": "snippet",
|
||||
"attributes": {
|
||||
"fileName": "mphToKmph.md",
|
||||
"text": "Convert miles/hour to kilometers/hour.\n\nMultiply the constant of proportionality with the argument.\n\n",
|
||||
"codeBlocks": {
|
||||
"es6": "const mphToKmph = (mph) => 1.6093440006146922 * mph;",
|
||||
"es5": "var mphToKmph = function mphToKmph(mph) {\n return 1.6093440006146922 * mph;\n};",
|
||||
"example": "mphToKmph(10); // 16.09344000614692\nmphToKmph(85.9); // 138.24264965280207"
|
||||
},
|
||||
"tags": [
|
||||
"math",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "d1ec7968c8f8c48642a3f91878db84330231bdf84bf74633dc0754456e951338",
|
||||
"firstSeen": "1539710543",
|
||||
"lastUpdated": "1565681352",
|
||||
"updateCount": 3,
|
||||
"authorCount": 2
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "objectToEntries",
|
||||
"title": "objectToEntries",
|
||||
"type": "snippet",
|
||||
"attributes": {
|
||||
"fileName": "objectToEntries.md",
|
||||
"text": "Creates an array of key-value pair arrays from an object.\n\nUse `Object.keys()` and `Array.prototype.map()` to iterate over the object's keys and produce an array with key-value pairs.\n\n",
|
||||
"codeBlocks": {
|
||||
"es6": "const objectToEntries = obj => Object.keys(obj).map(k => [k, obj[k]]);",
|
||||
"es5": "var objectToEntries = function objectToEntries(obj) {\n return Object.keys(obj).map(function (k) {\n return [k, obj[k]];\n });\n};",
|
||||
"example": "objectToEntries({ a: 1, b: 2 }); // [ ['a', 1], ['b', 2] ]"
|
||||
},
|
||||
"tags": [
|
||||
"object",
|
||||
"array",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "da5ab6a4f794f33d985d8a82794414b80913e63214a80d78c87bbda9638faa4f",
|
||||
"firstSeen": "1584968830",
|
||||
"lastUpdated": "1584968830",
|
||||
"updateCount": 2,
|
||||
"authorCount": 2
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "pipeLog",
|
||||
"title": "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.\n\n",
|
||||
"codeBlocks": {
|
||||
"es6": "const pipeLog = data => console.log(data) || data;",
|
||||
"es5": "var pipeLog = function pipeLog(data) {\n return console.log(data) || data;\n};",
|
||||
"example": "pipeLog(1); // logs `1` and returns `1`"
|
||||
},
|
||||
"tags": [
|
||||
"utility",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "dba6fa36424c23d601c4e463463a5f23d32b51d8b058a6c5020d3b4098a65e51",
|
||||
"firstSeen": "1537616292",
|
||||
"lastUpdated": "1565681352",
|
||||
"updateCount": 3,
|
||||
"authorCount": 2
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "quickSort",
|
||||
"title": "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.\n\n",
|
||||
"codeBlocks": {
|
||||
"es6": "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 ];",
|
||||
"es5": "function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }\n\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance\"); }\n\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }\n\nfunction _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest(); }\n\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance\"); }\n\nfunction _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === \"[object Arguments]\") return Array.from(iter); }\n\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n\nvar quickSort = function quickSort(_ref, desc) {\n var _ref2 = _toArray(_ref),\n n = _ref2[0],\n nums = _ref2.slice(1);\n\n return isNaN(n) ? [] : [].concat(_toConsumableArray(quickSort(nums.filter(function (v) {\n return desc ? v > n : v <= n;\n }), desc)), [n], _toConsumableArray(quickSort(nums.filter(function (v) {\n return !desc ? v > n : v <= n;\n }), desc)));\n};",
|
||||
"example": "quickSort([4, 1, 3, 2]); // [1,2,3,4]\nquickSort([4, 1, 3, 2], true); // [4,3,2,1]"
|
||||
},
|
||||
"tags": [
|
||||
"algorithm",
|
||||
"recursion",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "5c26069a02342eadd2c5ba2656a1b211da8f1a94da03c2cc31a5090be556d7b7",
|
||||
"firstSeen": "1515162834",
|
||||
"lastUpdated": "1565681352",
|
||||
"updateCount": 4,
|
||||
"authorCount": 3
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "removeVowels",
|
||||
"title": "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 `''`.\n\n",
|
||||
"codeBlocks": {
|
||||
"es6": "const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi, repl);",
|
||||
"es5": "var removeVowels = function removeVowels(str) {\n var repl = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';\n return str.replace(/[aeiou]/gi, repl);\n};",
|
||||
"example": "removeVowels(\"foobAr\"); // \"fbr\"\nremoveVowels(\"foobAr\",\"*\"); // \"f**b*r\""
|
||||
},
|
||||
"tags": [
|
||||
"string",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "5c6f8e292db8506568de362aa63890047f9d5a65d35143cfca1e27562642c414",
|
||||
"firstSeen": "1515500549",
|
||||
"lastUpdated": "1565681352",
|
||||
"updateCount": 5,
|
||||
"authorCount": 3
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "solveRPN",
|
||||
"title": "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.\n\n",
|
||||
"codeBlocks": {
|
||||
"es6": "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};",
|
||||
"es5": "var solveRPN = function solveRPN(rpn) {\n var OPERATORS = {\n '*': function _(a, b) {\n return a * b;\n },\n '+': function _(a, b) {\n return a + b;\n },\n '-': function _(a, b) {\n return a - b;\n },\n '/': function _(a, b) {\n return a / b;\n },\n '**': function _(a, b) {\n return Math.pow(a, b);\n }\n };\n var _ref = [[], rpn.replace(/\\^/g, '**').split(/\\s+/g).filter(function (el) {\n return !/\\s+/.test(el) && el !== '';\n })],\n stack = _ref[0],\n solve = _ref[1];\n solve.forEach(function (symbol) {\n if (!isNaN(parseFloat(symbol)) && isFinite(symbol)) {\n stack.push(symbol);\n } else if (Object.keys(OPERATORS).includes(symbol)) {\n var _ref2 = [stack.pop(), stack.pop()],\n a = _ref2[0],\n b = _ref2[1];\n stack.push(OPERATORS[symbol](parseFloat(b), parseFloat(a)));\n } else {\n throw \"\".concat(symbol, \" is not a recognized symbol\");\n }\n });\n if (stack.length === 1) return stack.pop();else throw \"\".concat(rpn, \" is not a proper RPN. Please check it and try again\");\n};",
|
||||
"example": "solveRPN('15 7 1 1 + - / 3 * 2 1 1 + + -'); // 5\nsolveRPN('2 3 ^'); // 8"
|
||||
},
|
||||
"tags": [
|
||||
"algorithm",
|
||||
"advanced"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "0c37cf46586652fd20dfa9ca682d3635f01fe61c46864f9773f6b258e8f3b6f6",
|
||||
"firstSeen": "1515162834",
|
||||
"lastUpdated": "1565681352",
|
||||
"updateCount": 4,
|
||||
"authorCount": 3
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "speechSynthesis",
|
||||
"title": "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).\n\n",
|
||||
"codeBlocks": {
|
||||
"es6": "const speechSynthesis = message => {\n const msg = new SpeechSynthesisUtterance(message);\n msg.voice = window.speechSynthesis.getVoices()[0];\n window.speechSynthesis.speak(msg);\n};",
|
||||
"es5": "var speechSynthesis = function speechSynthesis(message) {\n var msg = new SpeechSynthesisUtterance(message);\n msg.voice = window.speechSynthesis.getVoices()[0];\n window.speechSynthesis.speak(msg);\n};",
|
||||
"example": "speechSynthesis('Hello, World'); // // plays the message"
|
||||
},
|
||||
"tags": [
|
||||
"browser",
|
||||
"intermediate"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "9859dbef05dc0398e825150b50fccfea370583cf6b807c00c9e83b769d2b51c0",
|
||||
"firstSeen": "1515162834",
|
||||
"lastUpdated": "1565681352",
|
||||
"updateCount": 3,
|
||||
"authorCount": 2
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "squareSum",
|
||||
"title": "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.\n\n",
|
||||
"codeBlocks": {
|
||||
"es6": "const squareSum = (...args) => args.reduce((squareSum, number) => squareSum + Math.pow(number, 2), 0);",
|
||||
"es5": "var squareSum = function squareSum() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return args.reduce(function (squareSum, number) {\n return squareSum + Math.pow(number, 2);\n }, 0);\n};",
|
||||
"example": "squareSum(1, 2, 2); // 9"
|
||||
},
|
||||
"tags": [
|
||||
"math",
|
||||
"beginner"
|
||||
]
|
||||
},
|
||||
"meta": {
|
||||
"hash": "19837ac6714833e9c5fe698811e171cc2598f7b9405a4847b33b8d3b35debf8a",
|
||||
"firstSeen": "1539593592",
|
||||
"lastUpdated": "1565681352",
|
||||
"updateCount": 7,
|
||||
"authorCount": 3
|
||||
}
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"specification": "http://jsonapi.org/format/",
|
||||
"type": "snippetArray",
|
||||
"scope": "./snippets_archive",
|
||||
"language": {
|
||||
"short": "js",
|
||||
"long": "JavaScript"
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,4 +0,0 @@
|
||||
[[headers]]
|
||||
for = "/static/*"
|
||||
[headers.values]
|
||||
Cache-Control = "public, max-age=360000"
|
||||
@ -1 +0,0 @@
|
||||
/ https://30secondsofcode.org 301!
|
||||
@ -1,2 +0,0 @@
|
||||
User-agent: *
|
||||
Disallow:
|
||||
@ -1,17 +0,0 @@
|
||||
const {CSVToArray} = require('./_30s.js');
|
||||
|
||||
test('CSVToArray is a Function', () => {
|
||||
expect(CSVToArray).toBeInstanceOf(Function);
|
||||
});
|
||||
test('CSVToArray works with default delimiter', () => {
|
||||
expect(CSVToArray('a,b\nc,d')).toEqual([['a', 'b'], ['c', 'd']]);
|
||||
});
|
||||
test('CSVToArray works with custom delimiter', () => {
|
||||
expect(CSVToArray('a;b\nc;d', ';')).toEqual([['a', 'b'], ['c', 'd']]);
|
||||
});
|
||||
test('CSVToArray omits the first row', () => {
|
||||
expect(CSVToArray('col1,col2\na,b\nc,d', ',', true)).toEqual([['a', 'b'], ['c', 'd']]);
|
||||
});
|
||||
test('CSVToArray omits the first row and works with a custom delimiter', () => {
|
||||
expect(CSVToArray('col1;col2\na;b\nc;d', ';', true)).toEqual([['a', 'b'], ['c', 'd']]);
|
||||
});
|
||||
@ -1,17 +0,0 @@
|
||||
const {CSVToJSON} = require('./_30s.js');
|
||||
|
||||
test('CSVToJSON is a Function', () => {
|
||||
expect(CSVToJSON).toBeInstanceOf(Function);
|
||||
});
|
||||
test('CSVToJSON works with default delimiter', () => {
|
||||
expect(CSVToJSON('col1,col2\na,b\nc,d')).toEqual([
|
||||
{ col1: 'a', col2: 'b' },
|
||||
{ col1: 'c', col2: 'd' }
|
||||
]);
|
||||
});
|
||||
test('CSVToJSON works with custom delimiter', () => {
|
||||
expect(CSVToJSON('col1;col2\na;b\nc;d', ';')).toEqual([
|
||||
{ col1: 'a', col2: 'b' },
|
||||
{ col1: 'c', col2: 'd' }
|
||||
]);
|
||||
});
|
||||
@ -1,5 +0,0 @@
|
||||
const {JSONToFile} = require('./_30s.js');
|
||||
|
||||
test('JSONToFile is a Function', () => {
|
||||
expect(JSONToFile).toBeInstanceOf(Function);
|
||||
});
|
||||
@ -1,15 +0,0 @@
|
||||
const {JSONtoCSV} = require('./_30s.js');
|
||||
|
||||
test('JSONtoCSV is a Function', () => {
|
||||
expect(JSONtoCSV).toBeInstanceOf(Function);
|
||||
});
|
||||
test('JSONtoCSV works with default delimiter', () => {
|
||||
expect(JSONtoCSV([{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }], ['a', 'b'])).toBe(
|
||||
'a,b\n"1","2"\n"3","4"\n"6",""\n"","7"'
|
||||
);
|
||||
});
|
||||
test('JSONtoCSV works with custom delimiter', () => {
|
||||
expect(
|
||||
JSONtoCSV([{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }], ['a', 'b'], ';')
|
||||
).toBe('a;b\n"1";"2"\n"3";"4"\n"6";""\n"";"7"');
|
||||
});
|
||||
@ -1,8 +0,0 @@
|
||||
const {RGBToHex} = require('./_30s.js');
|
||||
|
||||
test('RGBToHex is a Function', () => {
|
||||
expect(RGBToHex).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Converts the values of RGB components to a color code.', () => {
|
||||
expect(RGBToHex(255, 165, 1)).toBe('ffa501');
|
||||
});
|
||||
@ -1,15 +0,0 @@
|
||||
const {URLJoin} = require('./_30s.js');
|
||||
|
||||
test('URLJoin is a Function', () => {
|
||||
expect(URLJoin).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Returns proper URL', () => {
|
||||
expect(URLJoin('http://www.google.com', 'a', '/b/cd', '?foo=123', '?bar=foo')).toBe(
|
||||
'http://www.google.com/a/b/cd?foo=123&bar=foo'
|
||||
);
|
||||
});
|
||||
test('Returns proper URL', () => {
|
||||
expect(URLJoin('file://www.google.com', 'a', '/b/cd', '?foo=123', '?bar=foo')).toBe(
|
||||
'file:///www.google.com/a/b/cd?foo=123&bar=foo'
|
||||
);
|
||||
});
|
||||
@ -1,5 +0,0 @@
|
||||
const {UUIDGeneratorBrowser} = require('./_30s.js');
|
||||
|
||||
test('UUIDGeneratorBrowser is a Function', () => {
|
||||
expect(UUIDGeneratorBrowser).toBeInstanceOf(Function);
|
||||
});
|
||||
@ -1,12 +0,0 @@
|
||||
const {UUIDGeneratorNode} = require('./_30s.js');
|
||||
|
||||
test('UUIDGeneratorNode is a Function', () => {
|
||||
expect(UUIDGeneratorNode).toBeInstanceOf(Function);
|
||||
});
|
||||
const uuid = UUIDGeneratorNode();
|
||||
test('Contains dashes in the proper places', () => {
|
||||
expect([uuid[8], uuid[13], uuid[18], uuid[23]]).toEqual(['-', '-', '-', '-']);
|
||||
});
|
||||
test('Only contains hexadecimal digits', () => {
|
||||
expect(/^[0-9A-Fa-f-]+$/.test(uuid)).toBeTruthy();
|
||||
});
|
||||
1602
test/_30s.js
1602
test/_30s.js
File diff suppressed because it is too large
Load Diff
@ -1,29 +0,0 @@
|
||||
const {all} = require('./_30s.js');
|
||||
|
||||
test('all is a Function', () => {
|
||||
expect(all).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Returns true for arrays with no falsy values', () => {
|
||||
expect(all([4, 1, 2, 3])).toBeTruthy();
|
||||
});
|
||||
test('Returns false for arrays with 0', () => {
|
||||
expect(all([0, 1])).toBeFalsy();
|
||||
});
|
||||
test('Returns false for arrays with NaN', () => {
|
||||
expect(all([NaN, 1])).toBeFalsy();
|
||||
});
|
||||
test('Returns false for arrays with undefined', () => {
|
||||
expect(all([undefined, 1])).toBeFalsy();
|
||||
});
|
||||
test('Returns false for arrays with null', () => {
|
||||
expect(all([null, 1])).toBeFalsy();
|
||||
});
|
||||
test('Returns false for arrays with empty strings', () => {
|
||||
expect(all(['', 1])).toBeFalsy();
|
||||
});
|
||||
test('Returns true with predicate function', () => {
|
||||
expect(all([4, 1, 2, 3], x => x >= 1)).toBeTruthy();
|
||||
});
|
||||
test('Returns false with a predicate function', () => {
|
||||
expect(all([0, 1], x => x >= 1)).toBeFalsy();
|
||||
});
|
||||
@ -1,41 +0,0 @@
|
||||
const {allEqual} = require('./_30s.js');
|
||||
|
||||
test('allEqual is a Function', () => {
|
||||
expect(allEqual).toBeInstanceOf(Function);
|
||||
});
|
||||
|
||||
test('Truthy numbers', () => {
|
||||
expect(allEqual([4, 4, 4])).toBeTruthy();
|
||||
});
|
||||
|
||||
test('Falsy numbers', () => {
|
||||
expect(allEqual([4, 3.999, 4])).toBeFalsy();
|
||||
});
|
||||
|
||||
test('Truthy strings', () => {
|
||||
expect(allEqual(['lorem', 'lorem', 'lorem'])).toBeTruthy();
|
||||
});
|
||||
|
||||
test('Falsy numbers', () => {
|
||||
expect(allEqual(['lorem', 'ipsum', 'dolore'])).toBeFalsy();
|
||||
});
|
||||
|
||||
test('Truthy trues', () => {
|
||||
expect(allEqual([true, true, true])).toBeTruthy();
|
||||
});
|
||||
|
||||
test('Truthy falses', () => {
|
||||
expect(allEqual([false, false, false])).toBeTruthy();
|
||||
});
|
||||
|
||||
test('Falsy trues', () => {
|
||||
expect(allEqual([true, true, false])).toBeFalsy();
|
||||
});
|
||||
|
||||
test('Falsy falses', () => {
|
||||
expect(allEqual([false, false, true])).toBeFalsy();
|
||||
});
|
||||
|
||||
test('False when there are different types', () => {
|
||||
expect(allEqual([1, '1', true])).toBeFalsy();
|
||||
});
|
||||
@ -1,20 +0,0 @@
|
||||
const {any} = require('./_30s.js');
|
||||
|
||||
test('any is a Function', () => {
|
||||
expect(any).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Returns true for arrays with at least one truthy value', () => {
|
||||
expect(any([0, 1, 2, 3])).toBeTruthy();
|
||||
});
|
||||
test('Returns false for arrays with no truthy values', () => {
|
||||
expect(any([0, 0])).toBeFalsy();
|
||||
});
|
||||
test('Returns false for arrays with no truthy values', () => {
|
||||
expect(any([NaN, 0, undefined, null, ''])).toBeFalsy();
|
||||
});
|
||||
test('Returns true with predicate function', () => {
|
||||
expect(any([4, 1, 0, 3], x => x >= 1)).toBeTruthy();
|
||||
});
|
||||
test('Returns false with a predicate function', () => {
|
||||
expect(any([0, 1], x => x < 0)).toBeFalsy();
|
||||
});
|
||||
@ -1,17 +0,0 @@
|
||||
const {approximatelyEqual} = require('./_30s.js');
|
||||
|
||||
test('approximatelyEqual is a Function', () => {
|
||||
expect(approximatelyEqual).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Works for PI / 2', () => {
|
||||
expect(approximatelyEqual(Math.PI / 2.0, 1.5708)).toBeTruthy();
|
||||
});
|
||||
test('Works for 0.1 + 0.2 === 0.3', () => {
|
||||
expect(approximatelyEqual(0.1 + 0.2, 0.3)).toBeTruthy();
|
||||
});
|
||||
test('Works for exactly equal values', () => {
|
||||
expect(approximatelyEqual(0.5, 0.5)).toBeTruthy();
|
||||
});
|
||||
test('Works for a custom epsilon', () => {
|
||||
expect(approximatelyEqual(0.501, 0.5, 0.1)).toBeTruthy();
|
||||
});
|
||||
@ -1,14 +0,0 @@
|
||||
const {arrayToCSV} = require('./_30s.js');
|
||||
|
||||
test('arrayToCSV is a Function', () => {
|
||||
expect(arrayToCSV).toBeInstanceOf(Function);
|
||||
});
|
||||
test('arrayToCSV works with default delimiter', () => {
|
||||
expect(arrayToCSV([['a', 'b'], ['c', 'd']])).toBe('"a","b"\n"c","d"');
|
||||
});
|
||||
test('arrayToCSV works with custom delimiter', () => {
|
||||
expect(arrayToCSV([['a', 'b'], ['c', 'd']], ';')).toBe('"a";"b"\n"c";"d"');
|
||||
});
|
||||
test('arrayToCSV escapes quotes and doesn\'t quote numbers', () => {
|
||||
expect(arrayToCSV([['a', '"b" great'], ['c', 3.1415]])).toBe('"a","""b"" great"\n"c",3.1415');
|
||||
});
|
||||
@ -1,5 +0,0 @@
|
||||
const {arrayToHtmlList} = require('./_30s.js');
|
||||
|
||||
test('arrayToHtmlList is a Function', () => {
|
||||
expect(arrayToHtmlList).toBeInstanceOf(Function);
|
||||
});
|
||||
@ -1,9 +0,0 @@
|
||||
const {ary} = require('./_30s.js');
|
||||
|
||||
test('ary is a Function', () => {
|
||||
expect(ary).toBeInstanceOf(Function);
|
||||
});
|
||||
const firstTwoMax = ary(Math.max, 2);
|
||||
test('Discards arguments with index >=n', () => {
|
||||
expect([[2, 6, 'a'], [6, 4, 8], [10]].map(x => firstTwoMax(...x))).toEqual([6, 6, 10]);
|
||||
});
|
||||
@ -1,11 +0,0 @@
|
||||
const {atob} = require('./_30s.js');
|
||||
|
||||
test('atob is a Function', () => {
|
||||
expect(atob).toBeInstanceOf(Function);
|
||||
});
|
||||
test('atob("Zm9vYmFy") equals "foobar"', () => {
|
||||
expect(atob('Zm9vYmFy')).toBe('foobar');
|
||||
});
|
||||
test('atob("Z") returns ""', () => {
|
||||
expect(atob('Z')).toBe('');
|
||||
});
|
||||
@ -1,15 +0,0 @@
|
||||
const {attempt} = require('./_30s.js');
|
||||
|
||||
test('attempt is a Function', () => {
|
||||
expect(attempt).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Returns a value', () => {
|
||||
expect(attempt(() => 0)).toBe(0);
|
||||
});
|
||||
test('Returns an error', () => {
|
||||
expect(
|
||||
attempt(() => {
|
||||
throw new Error();
|
||||
})
|
||||
).toBeInstanceOf(Error);
|
||||
});
|
||||
@ -1,45 +0,0 @@
|
||||
const {average} = require('./_30s.js');
|
||||
|
||||
test('average is a Function', () => {
|
||||
expect(average).toBeInstanceOf(Function);
|
||||
});
|
||||
test('average(true) returns 1', () => {
|
||||
expect(average(true) === 1).toBeTruthy();
|
||||
});
|
||||
test('average(false) returns 0', () => {
|
||||
expect(average(false) === 0).toBeTruthy();
|
||||
});
|
||||
test('average(9, 1) returns 5', () => {
|
||||
expect(average(9, 1)).toBe(5);
|
||||
});
|
||||
test('average(153, 44, 55, 64, 71, 1122, 322774, 2232, 23423, 234, 3631) returns 32163.909090909092 ', () => {
|
||||
expect(average(153, 44, 55, 64, 71, 1122, 322774, 2232, 23423, 234, 3631)).toBeCloseTo(
|
||||
32163.909090909092,
|
||||
3
|
||||
);
|
||||
});
|
||||
test('average(1, 2, 3) returns 2', () => {
|
||||
expect(average(1, 2, 3)).toBe(2);
|
||||
});
|
||||
test('average(null) returns 0', () => {
|
||||
expect(average(null)).toBe(0);
|
||||
});
|
||||
test('average(undefined) returns NaN', () => {
|
||||
expect(isNaN(average(undefined))).toBeTruthy();
|
||||
});
|
||||
test('average("String") returns NaN', () => {
|
||||
expect(isNaN(average('String'))).toBeTruthy();
|
||||
});
|
||||
test('average({ a: 123}) returns NaN', () => {
|
||||
expect(isNaN(average({ a: 123 }))).toBeTruthy();
|
||||
});
|
||||
test('average([undefined, 0, string]) returns NaN', () => {
|
||||
expect(isNaN(average([undefined, 0, 'string']))).toBeTruthy();
|
||||
});
|
||||
|
||||
let start = new Date().getTime();
|
||||
average(153, 44, 55, 64, 71, 1122, 322774, 2232, 23423, 234, 3631);
|
||||
let end = new Date().getTime();
|
||||
test('average([1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 1122, 32124, 23232]) takes less than 2s to run', () => {
|
||||
expect(end - start < 2000).toBeTruthy();
|
||||
});
|
||||
@ -1,11 +0,0 @@
|
||||
const {averageBy} = require('./_30s.js');
|
||||
|
||||
test('averageBy is a Function', () => {
|
||||
expect(averageBy).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Produces the right result with a function', () => {
|
||||
expect(averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n)).toBe(5);
|
||||
});
|
||||
test('Produces the right result with a property name', () => {
|
||||
expect(averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n')).toBe(5);
|
||||
});
|
||||
@ -1,11 +0,0 @@
|
||||
const {bifurcate} = require('./_30s.js');
|
||||
|
||||
test('bifurcate is a Function', () => {
|
||||
expect(bifurcate).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Splits the collection into two groups', () => {
|
||||
expect(bifurcate(['beep', 'boop', 'foo', 'bar'], [true, true, false, true])).toEqual([
|
||||
['beep', 'boop', 'bar'],
|
||||
['foo']
|
||||
]);
|
||||
});
|
||||
@ -1,11 +0,0 @@
|
||||
const {bifurcateBy} = require('./_30s.js');
|
||||
|
||||
test('bifurcateBy is a Function', () => {
|
||||
expect(bifurcateBy).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Splits the collection into two groups', () => {
|
||||
expect(bifurcateBy(['beep', 'boop', 'foo', 'bar'], x => x[0] === 'b')).toEqual([
|
||||
['beep', 'boop', 'bar'],
|
||||
['foo']
|
||||
]);
|
||||
});
|
||||
@ -1,13 +0,0 @@
|
||||
const {bind} = require('./_30s.js');
|
||||
|
||||
test('bind is a Function', () => {
|
||||
expect(bind).toBeInstanceOf(Function);
|
||||
});
|
||||
function greet(greeting, punctuation) {
|
||||
return greeting + ' ' + this.user + punctuation;
|
||||
}
|
||||
const freddy = { user: 'fred' };
|
||||
const freddyBound = bind(greet, freddy);
|
||||
test('Binds to an object context', () => {
|
||||
expect(freddyBound('hi', '!')).toBe('hi fred!');
|
||||
});
|
||||
@ -1,15 +0,0 @@
|
||||
const {bindAll} = require('./_30s.js');
|
||||
|
||||
test('bindAll is a Function', () => {
|
||||
expect(bindAll).toBeInstanceOf(Function);
|
||||
});
|
||||
var view = {
|
||||
label: 'docs',
|
||||
click() {
|
||||
return 'clicked ' + this.label;
|
||||
}
|
||||
};
|
||||
bindAll(view, 'click');
|
||||
test('Binds to an object context', () => {
|
||||
expect(view.click()).toBe('clicked docs');
|
||||
});
|
||||
@ -1,15 +0,0 @@
|
||||
const {bindKey} = require('./_30s.js');
|
||||
|
||||
test('bindKey is a Function', () => {
|
||||
expect(bindKey).toBeInstanceOf(Function);
|
||||
});
|
||||
const freddy = {
|
||||
user: 'fred',
|
||||
greet(greeting, punctuation) {
|
||||
return greeting + ' ' + this.user + punctuation;
|
||||
}
|
||||
};
|
||||
const freddyBound = bindKey(freddy, 'greet');
|
||||
test('Binds function to an object context', () => {
|
||||
expect(freddyBound('hi', '!')).toBe('hi fred!');
|
||||
});
|
||||
@ -1,26 +0,0 @@
|
||||
const {binomialCoefficient} = require('./_30s.js');
|
||||
|
||||
test('binomialCoefficient is a Function', () => {
|
||||
expect(binomialCoefficient).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Returns the appropriate value', () => {
|
||||
expect(binomialCoefficient(8, 2)).toBe(28);
|
||||
});
|
||||
test('Returns the appropriate value', () => {
|
||||
expect(binomialCoefficient(0, 0)).toBe(1);
|
||||
});
|
||||
test('Returns the appropriate value', () => {
|
||||
expect(binomialCoefficient(5, 3)).toBe(10);
|
||||
});
|
||||
test('Returns the appropriate value', () => {
|
||||
expect(binomialCoefficient(8, -1)).toBe(0);
|
||||
});
|
||||
test('Returns the appropriate value', () => {
|
||||
expect(binomialCoefficient(8, 1)).toBe(8);
|
||||
});
|
||||
test('Returns NaN', () => {
|
||||
expect(Number.isNaN(binomialCoefficient(NaN, 3))).toBeTruthy();
|
||||
});
|
||||
test('Returns NaN', () => {
|
||||
expect(Number.isNaN(binomialCoefficient(5, NaN))).toBeTruthy();
|
||||
});
|
||||
@ -1,8 +0,0 @@
|
||||
const {bottomVisible} = require('./_30s.js');
|
||||
|
||||
test('bottomVisible is a Function', () => {
|
||||
expect(bottomVisible).toBeInstanceOf(Function);
|
||||
});
|
||||
test('bottomVisible returns a boolean', () => {
|
||||
expect(typeof bottomVisible()).toBe('boolean');
|
||||
});
|
||||
@ -1,8 +0,0 @@
|
||||
const {btoa} = require('./_30s.js');
|
||||
|
||||
test('btoa is a Function', () => {
|
||||
expect(btoa).toBeInstanceOf(Function);
|
||||
});
|
||||
test('btoa("foobar") equals "Zm9vYmFy"', () => {
|
||||
expect(btoa('foobar')).toBe('Zm9vYmFy');
|
||||
});
|
||||
@ -1,21 +0,0 @@
|
||||
const { byteSize } = require('./_30s.js');
|
||||
const Blob = class {
|
||||
constructor(s) {
|
||||
return {
|
||||
size: Buffer.byteLength(s.toString())
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
test('byteSize is a Function', () => {
|
||||
expect(byteSize).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Works for a single letter', () => {
|
||||
expect(byteSize('a')).toBe(1);
|
||||
});
|
||||
test('Works for a common string', () => {
|
||||
expect(byteSize('Hello World')).toBe(11);
|
||||
});
|
||||
test('Works for emoji', () => {
|
||||
expect(byteSize('😀')).toBe(4);
|
||||
});
|
||||
@ -1,8 +0,0 @@
|
||||
const {call} = require('./_30s.js');
|
||||
|
||||
test('call is a Function', () => {
|
||||
expect(call).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Calls function on given object', () => {
|
||||
expect(call('map', x => x * 2)([1, 2, 3])).toEqual([2, 4, 6]);
|
||||
});
|
||||
@ -1,17 +0,0 @@
|
||||
const {capitalize} = require('./_30s.js');
|
||||
|
||||
test('capitalize is a Function', () => {
|
||||
expect(capitalize).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Capitalizes the first letter of a string', () => {
|
||||
expect(capitalize('fooBar')).toBe('FooBar');
|
||||
});
|
||||
test('Capitalizes the first letter of a string', () => {
|
||||
expect(capitalize('fooBar', true)).toBe('Foobar');
|
||||
});
|
||||
test('Works with characters', () => {
|
||||
expect(capitalize('#!#', true)).toBe('#!#');
|
||||
});
|
||||
test('"Works with single character words', () => {
|
||||
expect(capitalize('a', true)).toBe('A');
|
||||
});
|
||||
@ -1,14 +0,0 @@
|
||||
const {capitalizeEveryWord} = require('./_30s.js');
|
||||
|
||||
test('capitalizeEveryWord is a Function', () => {
|
||||
expect(capitalizeEveryWord).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Capitalizes the first letter of every word in a string', () => {
|
||||
expect(capitalizeEveryWord('hello world!')).toBe('Hello World!');
|
||||
});
|
||||
test('Works with characters', () => {
|
||||
expect(capitalizeEveryWord('$# @!')).toBe('$# @!');
|
||||
});
|
||||
test('Works with one word string', () => {
|
||||
expect(capitalizeEveryWord('a')).toBe('A');
|
||||
});
|
||||
@ -1,20 +0,0 @@
|
||||
const {castArray} = require('./_30s.js');
|
||||
|
||||
test('castArray is a Function', () => {
|
||||
expect(castArray).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Works for single values', () => {
|
||||
expect(castArray(1)).toEqual([1]);
|
||||
});
|
||||
test('Works for arrays with one value', () => {
|
||||
expect(castArray([1])).toEqual([1]);
|
||||
});
|
||||
test('Works for arrays with multiple value', () => {
|
||||
expect(castArray([1, 2, 3])).toEqual([1, 2, 3]);
|
||||
});
|
||||
test('Works for strings', () => {
|
||||
expect(castArray('test')).toEqual(['test']);
|
||||
});
|
||||
test('Works for objects', () => {
|
||||
expect(castArray({})).toEqual([{}]);
|
||||
});
|
||||
@ -1,25 +0,0 @@
|
||||
const {celsiusToFahrenheit} = require('./_30s.js');
|
||||
|
||||
test('celsiusToFahrenheit is a Function', () => {
|
||||
expect(celsiusToFahrenheit).toBeInstanceOf(Function);
|
||||
});
|
||||
|
||||
test('0 Celsius is 32 Fahrenheit', () => {
|
||||
expect(celsiusToFahrenheit(0)).toBe(32);
|
||||
});
|
||||
|
||||
test('100 Celsius is 212 Fahrenheit', () => {
|
||||
expect(celsiusToFahrenheit(100)).toBe(212);
|
||||
});
|
||||
|
||||
test('-50 Celsius is -58 Fahrenheit', () => {
|
||||
expect(celsiusToFahrenheit(-50)).toBe(-58);
|
||||
});
|
||||
|
||||
test('1000 Celsius is 1832 Fahrenheit', () => {
|
||||
expect(celsiusToFahrenheit(1000)).toBe(1832);
|
||||
});
|
||||
|
||||
test('Not a number value is NaN', () => {
|
||||
expect(celsiusToFahrenheit('Durr')).toBe(NaN);
|
||||
});
|
||||
@ -1,35 +0,0 @@
|
||||
const {chainAsync} = require('./_30s.js');
|
||||
|
||||
test('chainAsync is a Function', () => {
|
||||
expect(chainAsync).toBeInstanceOf(Function);
|
||||
});
|
||||
|
||||
let incrementer = 0;
|
||||
test('Calls all functions in an array', done => {
|
||||
chainAsync([
|
||||
next => {
|
||||
incrementer += 1;
|
||||
next();
|
||||
},
|
||||
next => {
|
||||
incrementer += 1;
|
||||
next();
|
||||
},
|
||||
next => {
|
||||
expect(incrementer).toEqual(2);
|
||||
done();
|
||||
}
|
||||
]);
|
||||
});
|
||||
|
||||
test('Last function does not receive "next" argument', done => {
|
||||
chainAsync([
|
||||
next => {
|
||||
next();
|
||||
},
|
||||
next => {
|
||||
expect(next).toBe(undefined);
|
||||
done();
|
||||
}
|
||||
]);
|
||||
});
|
||||
@ -1,5 +0,0 @@
|
||||
const {checkProp} = require('./_30s.js');
|
||||
|
||||
test('checkProp is a Function', () => {
|
||||
expect(checkProp).toBeInstanceOf(Function);
|
||||
});
|
||||
@ -1,41 +0,0 @@
|
||||
const {chunk} = require('./_30s.js');
|
||||
|
||||
test('chunk is a Function', () => {
|
||||
expect(chunk).toBeInstanceOf(Function);
|
||||
});
|
||||
test('chunk([1, 2, 3, 4, 5], 2) returns [[1,2],[3,4],[5]] ', () => {
|
||||
expect(chunk([1, 2, 3, 4, 5], 2)).toEqual([[1, 2], [3, 4], [5]]);
|
||||
});
|
||||
test('chunk([]) returns []', () => {
|
||||
expect(chunk([])).toEqual([]);
|
||||
});
|
||||
test('chunk(123) returns []', () => {
|
||||
expect(chunk(123)).toEqual([]);
|
||||
});
|
||||
test('chunk({ a: 123}) returns []', () => {
|
||||
expect(chunk({ a: 123 })).toEqual([]);
|
||||
});
|
||||
test('chunk(string, 2) returns [ st, ri, ng ]', () => {
|
||||
expect(chunk('string', 2)).toEqual(['st', 'ri', 'ng']);
|
||||
});
|
||||
test('chunk() throws an error', () => {
|
||||
expect(() => {
|
||||
chunk();
|
||||
}).toThrow();
|
||||
});
|
||||
test('chunk(undefined) throws an error', () => {
|
||||
expect(() => {
|
||||
chunk(undefined);
|
||||
}).toThrow();
|
||||
});
|
||||
test('chunk(null) throws an error', () => {
|
||||
expect(() => {
|
||||
chunk(null);
|
||||
}).toThrow();
|
||||
});
|
||||
let start = new Date().getTime();
|
||||
chunk('This is a string', 2);
|
||||
let end = new Date().getTime();
|
||||
test('chunk(This is a string, 2) takes less than 2s to run', () => {
|
||||
expect(end - start < 2000).toBeTruthy();
|
||||
});
|
||||
@ -1,8 +0,0 @@
|
||||
const {clampNumber} = require('./_30s.js');
|
||||
|
||||
test('clampNumber is a Function', () => {
|
||||
expect(clampNumber).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Clamps num within the inclusive range specified by the boundary values a and b', () => {
|
||||
expect(clampNumber(2, 3, 5)).toBe(3);
|
||||
});
|
||||
@ -1,9 +0,0 @@
|
||||
const {cloneRegExp} = require('./_30s.js');
|
||||
|
||||
test('cloneRegExp is a Function', () => {
|
||||
expect(cloneRegExp).toBeInstanceOf(Function);
|
||||
});
|
||||
const rgTest = /./g;
|
||||
test('Clones regular expressions properly', () => {
|
||||
expect(cloneRegExp(rgTest)).not.toBe(rgTest);
|
||||
});
|
||||
@ -1,8 +0,0 @@
|
||||
const {coalesce} = require('./_30s.js');
|
||||
|
||||
test('coalesce is a Function', () => {
|
||||
expect(coalesce).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Returns the first non-null/undefined argument', () => {
|
||||
expect(coalesce(null, undefined, '', NaN, 'Waldo')).toEqual('');
|
||||
});
|
||||
@ -1,9 +0,0 @@
|
||||
const {coalesceFactory} = require('./_30s.js');
|
||||
|
||||
test('coalesceFactory is a Function', () => {
|
||||
expect(coalesceFactory).toBeInstanceOf(Function);
|
||||
});
|
||||
const customCoalesce = coalesceFactory(_ => ![null, undefined, '', NaN].includes(_));
|
||||
test('Returns a customized coalesce function', () => {
|
||||
expect(customCoalesce(undefined, null, NaN, '', 'Waldo')).toEqual('Waldo');
|
||||
});
|
||||
@ -1,12 +0,0 @@
|
||||
const {collectInto} = require('./_30s.js');
|
||||
|
||||
test('collectInto is a Function', () => {
|
||||
expect(collectInto).toBeInstanceOf(Function);
|
||||
});
|
||||
const Pall = collectInto(Promise.all.bind(Promise));
|
||||
let p1 = Promise.resolve(1);
|
||||
let p2 = Promise.resolve(2);
|
||||
let p3 = new Promise(resolve => setTimeout(resolve, 2000, 3));
|
||||
test('Works with multiple promises', () => {
|
||||
return expect(Pall(p1, p2, p3)).resolves.toEqual([1, 2, 3]);
|
||||
});
|
||||
@ -1,8 +0,0 @@
|
||||
const {colorize} = require('./_30s.js');
|
||||
|
||||
test('colorize is a Function', () => {
|
||||
expect(colorize).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Returns the appropriate value', () => {
|
||||
expect(colorize('x').black).toBe('\x1b[30mx');
|
||||
});
|
||||
@ -1,15 +0,0 @@
|
||||
const {compact} = require('./_30s.js');
|
||||
|
||||
test('compact is a Function', () => {
|
||||
expect(compact).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Removes falsy values from an array', () => {
|
||||
expect(compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34, null, undefined])).toEqual([
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
'a',
|
||||
's',
|
||||
34
|
||||
]);
|
||||
});
|
||||
@ -1,17 +0,0 @@
|
||||
const {compactWhitespace} = require('./_30s.js');
|
||||
|
||||
test('compactWhitespace is a Function', () => {
|
||||
expect(compactWhitespace).toBeInstanceOf(Function);
|
||||
});
|
||||
test('compactWhitespace returns a string with compacted whitespaces', () => {
|
||||
expect(compactWhitespace('Lorem Ipsum')).toBe('Lorem Ipsum');
|
||||
});
|
||||
test('compactWhitespace returns a string with compacted whitespaces', () => {
|
||||
expect(compactWhitespace('Lorem Ipsum')).toBe('Lorem Ipsum');
|
||||
});
|
||||
test('compactWhitespace returns a string with compacted whitespaces', () => {
|
||||
expect(compactWhitespace('Lorem \t Ipsum')).toBe('Lorem Ipsum');
|
||||
});
|
||||
test('compactWhitespace returns a string with compacted whitespaces', () => {
|
||||
expect(compactWhitespace('\t Lorem \n\n \n Ipsum ')).toBe(' Lorem Ipsum ');
|
||||
});
|
||||
@ -1,14 +0,0 @@
|
||||
const {compose} = require('./_30s.js');
|
||||
|
||||
test('compose is a Function', () => {
|
||||
expect(compose).toBeInstanceOf(Function);
|
||||
});
|
||||
const add5 = x => x + 5;
|
||||
const multiply = (x, y) => x * y;
|
||||
const multiplyAndAdd5 = compose(
|
||||
add5,
|
||||
multiply
|
||||
);
|
||||
test('Performs right-to-left function composition', () => {
|
||||
expect(multiplyAndAdd5(5, 2)).toBe(15);
|
||||
});
|
||||
@ -1,11 +0,0 @@
|
||||
const {composeRight} = require('./_30s.js');
|
||||
|
||||
test('composeRight is a Function', () => {
|
||||
expect(composeRight).toBeInstanceOf(Function);
|
||||
});
|
||||
const add = (x, y) => x + y;
|
||||
const square = x => x * x;
|
||||
const addAndSquare = composeRight(add, square);
|
||||
test('Performs left-to-right function composition', () => {
|
||||
expect(addAndSquare(1, 2)).toBe(9);
|
||||
});
|
||||
@ -1,11 +0,0 @@
|
||||
const {containsWhitespace} = require('./_30s.js');
|
||||
|
||||
test('containsWhitespace is a Function', () => {
|
||||
expect(containsWhitespace).toBeInstanceOf(Function);
|
||||
});
|
||||
test('containsWhitespace returns true when there are whitespaces', () => {
|
||||
expect(containsWhitespace('Lorem Ipsum')).toBe(true);
|
||||
});
|
||||
test('containsWhitespace returns false when there are no whitespaces', () => {
|
||||
expect(containsWhitespace('LoremIpsum')).toBe(false);
|
||||
});
|
||||
@ -1,16 +0,0 @@
|
||||
const {converge} = require('./_30s.js');
|
||||
|
||||
test('converge is a Function', () => {
|
||||
expect(converge).toBeInstanceOf(Function);
|
||||
});
|
||||
const average = converge((a, b) => a / b, [
|
||||
arr => arr.reduce((a, v) => a + v, 0),
|
||||
arr => arr.length
|
||||
]);
|
||||
test('Produces the average of the array', () => {
|
||||
expect(average([1, 2, 3, 4, 5, 6, 7])).toBe(4);
|
||||
});
|
||||
const strangeConcat = converge((a, b) => a + b, [x => x.toUpperCase(), x => x.toLowerCase()]);
|
||||
test('Produces the strange concatenation', () => {
|
||||
expect(strangeConcat('Yodel')).toBe('YODELyodel');
|
||||
});
|
||||
@ -1,30 +0,0 @@
|
||||
const {copyToClipboard} = require('./_30s.js');
|
||||
|
||||
test('copyToClipboard is a Function', () => {
|
||||
expect(copyToClipboard).toBeInstanceOf(Function);
|
||||
});
|
||||
test('copyToClipboard does not throw errors', () => {
|
||||
document.getSelection = function() {
|
||||
return {
|
||||
rangeCount: 0,
|
||||
removeAllRanges() { return; },
|
||||
addRange(x) { return x; }
|
||||
};
|
||||
};
|
||||
document.execCommand = function(x) { return x; };
|
||||
|
||||
expect(copyToClipboard('hi')).toBe(undefined);
|
||||
});
|
||||
test('copyToClipboard does not throw errors', () => {
|
||||
document.getSelection = function() {
|
||||
return {
|
||||
rangeCount: 1,
|
||||
getRangeAt(x) { return x + 1; },
|
||||
removeAllRanges() { return; },
|
||||
addRange(x) { return x; }
|
||||
};
|
||||
};
|
||||
document.execCommand = function(x) { return x; };
|
||||
|
||||
expect(copyToClipboard('hi')).toBe(undefined);
|
||||
});
|
||||
@ -1,11 +0,0 @@
|
||||
const {countBy} = require('./_30s.js');
|
||||
|
||||
test('countBy is a Function', () => {
|
||||
expect(countBy).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Works for functions', () => {
|
||||
expect(countBy([6.1, 4.2, 6.3], Math.floor)).toEqual({ 4: 1, 6: 2 });
|
||||
});
|
||||
test('Works for property names', () => {
|
||||
expect(countBy(['one', 'two', 'three'], 'length')).toEqual({ 3: 2, 5: 1 });
|
||||
});
|
||||
@ -1,11 +0,0 @@
|
||||
const {countOccurrences} = require('./_30s.js');
|
||||
|
||||
test('countOccurrences is a Function', () => {
|
||||
expect(countOccurrences).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Counts the occurrences of a value in an array', () => {
|
||||
expect(countOccurrences([1, 1, 2, 1, 2, 3], 1)).toEqual(3);
|
||||
});
|
||||
test('Works with different types in the same array', () => {
|
||||
expect(countOccurrences([1, 1, 2, 1, 2, 3, '1', true], 1)).toEqual(3);
|
||||
});
|
||||
@ -1,13 +0,0 @@
|
||||
const {counter} = require('./_30s.js');
|
||||
|
||||
test('counter is a Function', () => {
|
||||
expect(counter).toBeInstanceOf(Function);
|
||||
});
|
||||
test('counter does not throw errors', () => {
|
||||
expect(() => {
|
||||
document.body.appendChild(document.createElement('div'));
|
||||
counter('div', 1, 1000, 5, 2000);
|
||||
counter('div', 1000, 1, 5, 2000);
|
||||
counter('div', 1, 1000);
|
||||
}).not.toThrow(TypeError);
|
||||
});
|
||||
@ -1,5 +0,0 @@
|
||||
const {createDirIfNotExists} = require('./_30s.js');
|
||||
|
||||
test('createDirIfNotExists is a Function', () => {
|
||||
expect(createDirIfNotExists).toBeInstanceOf(Function);
|
||||
});
|
||||
@ -1,12 +0,0 @@
|
||||
const {createElement} = require('./_30s.js');
|
||||
|
||||
test('createElement is a Function', () => {
|
||||
expect(createElement).toBeInstanceOf(Function);
|
||||
});
|
||||
test('createElement creates an element', () => {
|
||||
expect(createElement(
|
||||
`<div class="container">
|
||||
<p>Hello!</p>
|
||||
</div>`
|
||||
).className).toEqual('container');
|
||||
});
|
||||
@ -1,16 +0,0 @@
|
||||
const {createEventHub} = require('./_30s.js');
|
||||
|
||||
test('createEventHub is a Function', () => {
|
||||
expect(createEventHub).toBeInstanceOf(Function);
|
||||
});
|
||||
test('createEventHub returns an object', () => {
|
||||
let hub = createEventHub();
|
||||
expect(typeof hub).toBe('object');
|
||||
expect(typeof hub.hub).toBe('object');
|
||||
expect(hub.emit).toBeInstanceOf(Function);
|
||||
expect(hub.on).toBeInstanceOf(Function);
|
||||
expect(hub.off).toBeInstanceOf(Function);
|
||||
expect(hub.emit()).toBe(undefined);
|
||||
expect(hub.on()).toBe(undefined);
|
||||
expect(hub.off()).toBe(undefined);
|
||||
});
|
||||
@ -1,8 +0,0 @@
|
||||
const {currentURL} = require('./_30s.js');
|
||||
|
||||
test('currentURL is a Function', () => {
|
||||
expect(currentURL).toBeInstanceOf(Function);
|
||||
});
|
||||
test('currentURL returns the appropriate value', () => {
|
||||
expect(currentURL()).toEqual(global.location.href);
|
||||
});
|
||||
@ -1,11 +0,0 @@
|
||||
const {curry} = require('./_30s.js');
|
||||
|
||||
test('curry is a Function', () => {
|
||||
expect(curry).toBeInstanceOf(Function);
|
||||
});
|
||||
test('curries a Math.pow', () => {
|
||||
expect(curry(Math.pow)(2)(10)).toBe(1024);
|
||||
});
|
||||
test('curries a Math.min', () => {
|
||||
expect(curry(Math.min, 3)(10)(50)(2)).toBe(2);
|
||||
});
|
||||
@ -1,5 +0,0 @@
|
||||
const {dayOfYear} = require('./_30s.js');
|
||||
|
||||
test('dayOfYear is a Function', () => {
|
||||
expect(dayOfYear).toBeInstanceOf(Function);
|
||||
});
|
||||
@ -1,12 +0,0 @@
|
||||
const {debounce} = require('./_30s.js');
|
||||
|
||||
test('debounce is a Function', () => {
|
||||
expect(debounce).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Works as expected', done => {
|
||||
const debouncedFn = debounce(() => {
|
||||
expect(true).toBeTruthy();
|
||||
done();
|
||||
});
|
||||
debouncedFn();
|
||||
});
|
||||
@ -1,11 +0,0 @@
|
||||
const {decapitalize} = require('./_30s.js');
|
||||
|
||||
test('decapitalize is a Function', () => {
|
||||
expect(decapitalize).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Works with default parameter', () => {
|
||||
expect(decapitalize('FooBar')).toBe('fooBar');
|
||||
});
|
||||
test('Works with second parameter set to true', () => {
|
||||
expect(decapitalize('FooBar', true)).toBe('fOOBAR');
|
||||
});
|
||||
@ -1,39 +0,0 @@
|
||||
const {deepClone} = require('./_30s.js');
|
||||
|
||||
test('deepClone is a Function', () => {
|
||||
expect(deepClone).toBeInstanceOf(Function);
|
||||
});
|
||||
const data = {
|
||||
a: [],
|
||||
b: [1, 2, 3],
|
||||
c: [{ foo: 'bar' }],
|
||||
d: {},
|
||||
e: { a: 'a', b: 'b', c: 'c', d: ['a', 'b', 'c'] },
|
||||
f: 1,
|
||||
g: true,
|
||||
h: null
|
||||
};
|
||||
const dupe = deepClone(data);
|
||||
test('Shallow cloning works', () => {
|
||||
expect(data).not.toBe(dupe);
|
||||
});
|
||||
test('Array shallow cloning edge case works', () => {
|
||||
expect(dupe.a).toEqual([]);
|
||||
});
|
||||
test('Array shallow cloning works', () => {
|
||||
expect(data.b).not.toBe(dupe.b);
|
||||
});
|
||||
test('Array deep cloning works', () => {
|
||||
expect(data.c[0]).not.toBe(dupe.c[0]);
|
||||
});
|
||||
test('Deep cloning works', () => {
|
||||
expect(data.d).not.toBe(dupe.d);
|
||||
expect(data.e).not.toBe(dupe.e);
|
||||
});
|
||||
test('Cloning primitives works', () => {
|
||||
expect(data.f).toBe(dupe.f);
|
||||
expect(data.g).toBe(dupe.g);
|
||||
});
|
||||
test('Cloning null works', () => {
|
||||
expect(data.h).toBe(dupe.h);
|
||||
});
|
||||
@ -1,8 +0,0 @@
|
||||
const {deepFlatten} = require('./_30s.js');
|
||||
|
||||
test('deepFlatten is a Function', () => {
|
||||
expect(deepFlatten).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Deep flattens an array', () => {
|
||||
expect(deepFlatten([1, [2], [[3], 4], 5])).toEqual([1, 2, 3, 4, 5]);
|
||||
});
|
||||
@ -1,34 +0,0 @@
|
||||
const {deepFreeze} = require('./_30s.js');
|
||||
|
||||
test('deepFreeze is a Function', () => {
|
||||
expect(deepFreeze).toBeInstanceOf(Function);
|
||||
});
|
||||
|
||||
test('modifying deeply freezed object prop throws an error in strict mode', () => {
|
||||
let freezedObj = deepFreeze({ a: 42 });
|
||||
|
||||
expect(() => {
|
||||
'use strict';
|
||||
freezedObj.a = 24;
|
||||
}).toThrow();
|
||||
});
|
||||
|
||||
test('should not modify deeply freezed object inside another object', () => {
|
||||
let freezedObj = deepFreeze({
|
||||
a: {
|
||||
b: 42
|
||||
}
|
||||
});
|
||||
|
||||
freezedObj.a.b = 16;
|
||||
|
||||
expect(freezedObj.a.b).toBe(42);
|
||||
});
|
||||
|
||||
test('should not add prop to deeply freezed empty object', () => {
|
||||
let freezedObj = deepFreeze({});
|
||||
|
||||
freezedObj.a = 42;
|
||||
|
||||
expect(freezedObj).toEqual({});
|
||||
});
|
||||
@ -1,39 +0,0 @@
|
||||
const {deepGet} = require('./_30s.js');
|
||||
|
||||
let idx = 2
|
||||
const data = {
|
||||
level1: {
|
||||
level2: {
|
||||
level3: 'level3',
|
||||
level3a: true,
|
||||
level3b: [1, 2, 3, { level3c: 'level3c' }, 4, 5],
|
||||
level3d: {
|
||||
level4: [{ foo: 'foo' }, { bar: 'bar' }, { baz: 'baz' }]
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
test('deepGet is a Function', () => {
|
||||
expect(deepGet).toBeInstanceOf(Function);
|
||||
});
|
||||
|
||||
test('deepGet target success', () => {
|
||||
expect(deepGet(data, ['level1', 'level2', 'level3'])).toEqual('level3');
|
||||
});
|
||||
|
||||
test('deepGet target and return null', () => {
|
||||
expect(deepGet(data, ['level1', 'level2', 'foo', 'baz'])).toEqual(null);
|
||||
});
|
||||
|
||||
test('deepGet target in an array', () => {
|
||||
expect(deepGet(data, ['level1', 'level2', 'level3d', 'level4', 2, 'baz'])).toEqual('baz');
|
||||
});
|
||||
|
||||
test('deepGet target with variable key', () => {
|
||||
expect(deepGet(data, ['level1', 'level2', 'level3b', idx])).toEqual(3);
|
||||
});
|
||||
|
||||
test('deepGet target with empty Object', () => {
|
||||
expect(deepGet({}, ['foo', 'bar', idx, 'foo'])).toEqual(null);
|
||||
});
|
||||
@ -1,31 +0,0 @@
|
||||
const { deepMapKeys, toCamelCase } = require('./_30s.js');
|
||||
|
||||
test('deepMapKeys is a Function', () => {
|
||||
expect(deepMapKeys).toBeInstanceOf(Function);
|
||||
});
|
||||
|
||||
test('Deep maps object keys', () => {
|
||||
const obj = {
|
||||
'foo_bar': 'hello',
|
||||
'deep_child': {
|
||||
'child_array': ['hello'],
|
||||
'child_object_array': [
|
||||
{ 'hola_hello': 'Gamarjoba' }
|
||||
]
|
||||
}
|
||||
};
|
||||
const expected = {
|
||||
fooBar: 'hello',
|
||||
deepChild: {
|
||||
childArray: ['hello'],
|
||||
childObjectArray: [
|
||||
{
|
||||
holaHello: 'Gamarjoba'
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
const camleCaseKeys = k => toCamelCase(k);
|
||||
expect(deepMapKeys(obj, camleCaseKeys)).toEqual(expected);
|
||||
});
|
||||
|
||||
@ -1,8 +0,0 @@
|
||||
const {defaults} = require('./_30s.js');
|
||||
|
||||
test('defaults is a Function', () => {
|
||||
expect(defaults).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Assigns default values for undefined properties', () => {
|
||||
expect(defaults({ a: 1 }, { b: 2 }, { b: 6 }, { a: 3 })).toEqual({ a: 1, b: 2 });
|
||||
});
|
||||
@ -1,5 +0,0 @@
|
||||
const {defer} = require('./_30s.js');
|
||||
|
||||
test('defer is a Function', () => {
|
||||
expect(defer).toBeInstanceOf(Function);
|
||||
});
|
||||
@ -1,9 +0,0 @@
|
||||
const {degreesToRads} = require('./_30s.js');
|
||||
|
||||
// const approxeq = (v1,v2, diff = 0.001) => Math.abs(v1 - v2) < diff;
|
||||
test('degreesToRads is a Function', () => {
|
||||
expect(degreesToRads).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Returns the appropriate value', () => {
|
||||
expect(degreesToRads(90.0)).toBeCloseTo(Math.PI / 2, 3);
|
||||
});
|
||||
@ -1,15 +0,0 @@
|
||||
const {delay} = require('./_30s.js');
|
||||
|
||||
test('delay is a Function', () => {
|
||||
expect(delay).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Works as expecting, passing arguments properly', done => {
|
||||
delay(
|
||||
function(text) {
|
||||
expect(text).toBe('test');
|
||||
done();
|
||||
},
|
||||
1000,
|
||||
'test'
|
||||
);
|
||||
});
|
||||
@ -1,5 +0,0 @@
|
||||
const {detectDeviceType} = require('./_30s.js');
|
||||
|
||||
test('detectDeviceType is a Function', () => {
|
||||
expect(detectDeviceType).toBeInstanceOf(Function);
|
||||
});
|
||||
@ -1,8 +0,0 @@
|
||||
const {difference} = require('./_30s.js');
|
||||
|
||||
test('difference is a Function', () => {
|
||||
expect(difference).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Returns the difference between two arrays', () => {
|
||||
expect(difference([1, 2, 3], [1, 2, 4])).toEqual([3]);
|
||||
});
|
||||
@ -1,11 +0,0 @@
|
||||
const {differenceBy} = require('./_30s.js');
|
||||
|
||||
test('differenceBy is a Function', () => {
|
||||
expect(differenceBy).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Works using a native function and numbers', () => {
|
||||
expect(differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor)).toEqual([1]);
|
||||
});
|
||||
test('Works with arrow function and objects', () => {
|
||||
expect(differenceBy([{ x: 2 }, { x: 1 }], [{ x: 1 }], v => v.x)).toEqual([2]);
|
||||
});
|
||||
@ -1,10 +0,0 @@
|
||||
const {differenceWith} = require('./_30s.js');
|
||||
|
||||
test('differenceWith is a Function', () => {
|
||||
expect(differenceWith).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Filters out all values from an array', () => {
|
||||
expect(
|
||||
differenceWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0], (a, b) => Math.round(a) === Math.round(b))
|
||||
).toEqual([1, 1.2]);
|
||||
});
|
||||
@ -1,31 +0,0 @@
|
||||
const {dig} = require('./_30s.js');
|
||||
|
||||
const data = {
|
||||
level1: {
|
||||
level2: {
|
||||
level3: 'some data',
|
||||
level3f: false,
|
||||
level3a: [1, 2, 3, 4]
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
test('dig is a Function', () => {
|
||||
expect(dig).toBeInstanceOf(Function);
|
||||
});
|
||||
|
||||
test('Dig target success', () => {
|
||||
expect(dig(data, 'level3')).toEqual('some data');
|
||||
});
|
||||
|
||||
test('Dig target with falsy value', () => {
|
||||
expect(dig(data, 'level3f')).toEqual(false);
|
||||
});
|
||||
|
||||
test('Dig target with array', () => {
|
||||
expect(dig(data, 'level3a')).toEqual([1, 2, 3, 4]);
|
||||
});
|
||||
|
||||
test('Unknown target return undefined', () => {
|
||||
expect(dig(data, 'level4')).toEqual(undefined);
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user