Merge pull request #5 from Chalarangelo/master
This commit is contained in:
@ -13,15 +13,14 @@ Here's what you can do to help:
|
||||
### Snippet submission and Pull request guidelines
|
||||
|
||||
- **DO NOT MODIFY THE README.md FILE!** Make changes to individual snippet files. You can optionally run `npm run build-list` to update the README.md file automatically, based on the changes you have made.
|
||||
- **Snippet filenames** must correspond to the title of the snippet. For example, if your snippet is titled `### Awesome snippet` the filename should be `awesome-snippet.md`.
|
||||
- Use `kebab-case`, not `snake_case`.
|
||||
- **Snippet filenames** must correspond to the title of the snippet. For example, if your snippet is titled `### awesomeSnippet` the filename should be `awesomeSnippet.md`.
|
||||
- Use `camelCase`, not `kebab-case` or `snake_case`.
|
||||
- Avoid capitalization of words, except if the whole word is capitalized (e.g. `URL` should be capitalized in the filename and the snippet title).
|
||||
- If there are parentheses in the title, add them to the filename (e.g. `awesome-snippet-(extra-awesome).md` if your snippet's title is `Awesome snippet (extra awesome)`).
|
||||
- **Snippet titles** should have only the first letter of the first word capitalized. Certain words can be in capitals (e.g. `URL`, `RGB`), but this is on a per-snippet basis.
|
||||
- **Snippet titles** should have be the same as the name of the function that is present in the snippet.
|
||||
- All snippet titles must be prefixed with `###` and be at the very first line of your snippet.
|
||||
- Snippet titles must be unique (although if you cannot find a better title, just add some placeholder at the end of the filename and title and we will figure it out).
|
||||
- Follow snippet titles with an empty line.
|
||||
- **Snippet descriptions** must be short and to the point. Try to explain *how* the snippet works and what Javascript features are used. Remember to include what functions you are using and why.
|
||||
- **Snippet descriptions** must be short and to the point. Try to explain *what* the snippet does and *how* the snippet works and what Javascript features are used. Remember to include what functions you are using and why.
|
||||
- Follow snippet descriptions with an empty line.
|
||||
- **Snippet code** must be enclosed inside ` ```js ` and ` ``` `.
|
||||
- Remember to start your snippet's code on a new line below the opening backticks.
|
||||
|
||||
BIN
docs/favicon.png
Normal file
BIN
docs/favicon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 8.2 KiB |
1048
docs/index.html
Normal file
1048
docs/index.html
Normal file
File diff suppressed because it is too large
Load Diff
140
docs/prism.css
Normal file
140
docs/prism.css
Normal file
@ -0,0 +1,140 @@
|
||||
/* PrismJS 1.9.0
|
||||
http://prismjs.com/download.html?themes=prism&languages=clike+javascript */
|
||||
/**
|
||||
* prism.js default theme for JavaScript, CSS and HTML
|
||||
* Based on dabblet (http://dabblet.com)
|
||||
* @author Lea Verou
|
||||
*/
|
||||
|
||||
code[class*="language-"],
|
||||
pre[class*="language-"] {
|
||||
color: black;
|
||||
background: none;
|
||||
text-shadow: 0 1px white;
|
||||
font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
|
||||
text-align: left;
|
||||
white-space: pre;
|
||||
word-spacing: normal;
|
||||
word-break: normal;
|
||||
word-wrap: normal;
|
||||
line-height: 1.5;
|
||||
|
||||
-moz-tab-size: 4;
|
||||
-o-tab-size: 4;
|
||||
tab-size: 4;
|
||||
|
||||
-webkit-hyphens: none;
|
||||
-moz-hyphens: none;
|
||||
-ms-hyphens: none;
|
||||
hyphens: none;
|
||||
}
|
||||
|
||||
pre[class*="language-"]::-moz-selection, pre[class*="language-"] ::-moz-selection,
|
||||
code[class*="language-"]::-moz-selection, code[class*="language-"] ::-moz-selection {
|
||||
text-shadow: none;
|
||||
background: #b3d4fc;
|
||||
}
|
||||
|
||||
pre[class*="language-"]::selection, pre[class*="language-"] ::selection,
|
||||
code[class*="language-"]::selection, code[class*="language-"] ::selection {
|
||||
text-shadow: none;
|
||||
background: #b3d4fc;
|
||||
}
|
||||
|
||||
@media print {
|
||||
code[class*="language-"],
|
||||
pre[class*="language-"] {
|
||||
text-shadow: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* Code blocks */
|
||||
pre[class*="language-"] {
|
||||
padding: 1em;
|
||||
margin: .5em 0;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
:not(pre) > code[class*="language-"],
|
||||
pre[class*="language-"] {
|
||||
background: #f5f2f0;
|
||||
}
|
||||
|
||||
/* Inline code */
|
||||
:not(pre) > code[class*="language-"] {
|
||||
padding: .1em;
|
||||
border-radius: .3em;
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
.token.comment,
|
||||
.token.prolog,
|
||||
.token.doctype,
|
||||
.token.cdata {
|
||||
color: slategray;
|
||||
}
|
||||
|
||||
.token.punctuation {
|
||||
color: #999;
|
||||
}
|
||||
|
||||
.namespace {
|
||||
opacity: .7;
|
||||
}
|
||||
|
||||
.token.property,
|
||||
.token.tag,
|
||||
.token.boolean,
|
||||
.token.number,
|
||||
.token.constant,
|
||||
.token.symbol,
|
||||
.token.deleted {
|
||||
color: #905;
|
||||
}
|
||||
|
||||
.token.selector,
|
||||
.token.attr-name,
|
||||
.token.string,
|
||||
.token.char,
|
||||
.token.builtin,
|
||||
.token.inserted {
|
||||
color: #690;
|
||||
}
|
||||
|
||||
.token.operator,
|
||||
.token.entity,
|
||||
.token.url,
|
||||
.language-css .token.string,
|
||||
.style .token.string {
|
||||
color: #a67f59;
|
||||
background: hsla(0, 0%, 100%, .5);
|
||||
}
|
||||
|
||||
.token.atrule,
|
||||
.token.attr-value,
|
||||
.token.keyword {
|
||||
color: #07a;
|
||||
}
|
||||
|
||||
.token.function {
|
||||
color: #DD4A68;
|
||||
}
|
||||
|
||||
.token.regex,
|
||||
.token.important,
|
||||
.token.variable {
|
||||
color: #e90;
|
||||
}
|
||||
|
||||
.token.important,
|
||||
.token.bold {
|
||||
font-weight: bold;
|
||||
}
|
||||
.token.italic {
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.token.entity {
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
5
docs/prism.js
Normal file
5
docs/prism.js
Normal file
File diff suppressed because one or more lines are too long
48
package-lock.json
generated
48
package-lock.json
generated
@ -65,6 +65,16 @@
|
||||
"resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-1.4.0.tgz",
|
||||
"integrity": "sha1-06ioOzGapneTZisT52HHkRQiMG4="
|
||||
},
|
||||
"ansi-regex": {
|
||||
"version": "0.2.1",
|
||||
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-0.2.1.tgz",
|
||||
"integrity": "sha1-DY6UaWej2BQ/k+JOKYUl/BsiNfk="
|
||||
},
|
||||
"ansi-styles": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-1.1.0.tgz",
|
||||
"integrity": "sha1-6uy/Zs1waIJ2Cy9GkVgrj1XXp94="
|
||||
},
|
||||
"anymatch": {
|
||||
"version": "1.3.2",
|
||||
"resolved": "https://registry.npmjs.org/anymatch/-/anymatch-1.3.2.tgz",
|
||||
@ -450,6 +460,7 @@
|
||||
"resolved": "https://registry.npmjs.org/concurrently/-/concurrently-3.5.1.tgz",
|
||||
"integrity": "sha512-689HrwGw8Rbk1xtV9C4dY6TPJAvIYZbRbnKSAtfJ7tHqICFGoZ0PCWYjxfmerRyxBG0o3sbG3pe7N8vqPwIHuQ==",
|
||||
"requires": {
|
||||
"chalk": "0.5.1",
|
||||
"commander": "2.6.0",
|
||||
"date-fns": "1.29.0",
|
||||
"lodash": "4.17.4",
|
||||
@ -457,6 +468,27 @@
|
||||
"spawn-command": "0.0.2-1",
|
||||
"supports-color": "3.2.3",
|
||||
"tree-kill": "1.2.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"chalk": {
|
||||
"version": "0.5.1",
|
||||
"resolved": "https://registry.npmjs.org/chalk/-/chalk-0.5.1.tgz",
|
||||
"integrity": "sha1-Zjs6ZItotV0EaQ1JFnqoN4WPIXQ=",
|
||||
"requires": {
|
||||
"ansi-styles": "1.1.0",
|
||||
"escape-string-regexp": "1.0.5",
|
||||
"has-ansi": "0.1.0",
|
||||
"strip-ansi": "0.3.0",
|
||||
"supports-color": "0.2.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"supports-color": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-0.2.0.tgz",
|
||||
"integrity": "sha1-2S3iaU6z9nMjlz1649i1W0wiGQo="
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"configstore": {
|
||||
@ -1353,6 +1385,14 @@
|
||||
"function-bind": "1.1.1"
|
||||
}
|
||||
},
|
||||
"has-ansi": {
|
||||
"version": "0.1.0",
|
||||
"resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-0.1.0.tgz",
|
||||
"integrity": "sha1-hPJlqujA5qiKEtcCKJS3VoiUxi4=",
|
||||
"requires": {
|
||||
"ansi-regex": "0.2.1"
|
||||
}
|
||||
},
|
||||
"has-flag": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz",
|
||||
@ -2854,6 +2894,14 @@
|
||||
"safe-buffer": "5.1.1"
|
||||
}
|
||||
},
|
||||
"strip-ansi": {
|
||||
"version": "0.3.0",
|
||||
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-0.3.0.tgz",
|
||||
"integrity": "sha1-JfSOoiynkYfzF0pNuHWTR7sSYiA=",
|
||||
"requires": {
|
||||
"ansi-regex": "0.2.1"
|
||||
}
|
||||
},
|
||||
"strip-bom": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz",
|
||||
|
||||
@ -18,6 +18,7 @@
|
||||
"builder": "node ./scripts/build-script.js",
|
||||
"linter": "node ./scripts/lint-script.js",
|
||||
"tagger": "node ./scripts/tag-script.js",
|
||||
"webber": "node ./scripts/web-script.js",
|
||||
"start": "concurrently --kill-others \"nodemon -e js,md -i README.md -x \\\"npm run build-list\\\"\" \"live-server ./build\""
|
||||
},
|
||||
"repository": {
|
||||
|
||||
@ -55,7 +55,7 @@ try {
|
||||
for(let tag of [...new Set(Object.entries(tagDbData).map(t => t[1]))].filter(v => v).sort((a,b) => a.localeCompare(b))){
|
||||
output +=`### ${capitalize(tag, true)}\n`;
|
||||
for(let taggedSnippet of Object.entries(tagDbData).filter(v => v[1] === tag))
|
||||
output += `* [${taggedSnippet[0][0].toUpperCase() + taggedSnippet[0].replace(/-/g,' ').slice(1)}](#${taggedSnippet[0].replace(/\(/g,'').replace(/\)/g,'').toLowerCase()})\n`
|
||||
output += `* [\`${taggedSnippet[0]}\`](#${taggedSnippet[0].toLowerCase()})\n`
|
||||
output += '\n';
|
||||
}
|
||||
// Loop over tags and snippets to create the list of snippets
|
||||
|
||||
81
scripts/web-script.js
Normal file
81
scripts/web-script.js
Normal file
@ -0,0 +1,81 @@
|
||||
/*
|
||||
This is the builder script that generates the README file.
|
||||
Run using `npm run builder`.
|
||||
*/
|
||||
// Load modules
|
||||
const fs = require('fs-extra'), path = require('path'), chalk = require('chalk'),
|
||||
md = require('markdown-it')();
|
||||
// Set variables for paths
|
||||
const snippetsPath = './snippets', staticPartsPath = './static-parts', docsPath = './docs';
|
||||
// Set variables for script
|
||||
let snippets = {}, startPart = '', endPart = '', output = '', tagDbData = {};
|
||||
// Load helper functions (these are from existing snippets in 30 seconds of code!)
|
||||
const objectFromPairs = arr => arr.reduce((a, v) => (a[v[0]] = v[1], a), {});
|
||||
const capitalize = (str, lowerRest = false) => str.slice(0, 1).toUpperCase() + (lowerRest ? str.slice(1).toLowerCase() : str.slice(1));
|
||||
// Start the timer of the script
|
||||
console.time('Builder');
|
||||
// Synchronously read all snippets and sort them as necessary (case-insensitive)
|
||||
try {
|
||||
let snippetFilenames = fs.readdirSync(snippetsPath);
|
||||
snippetFilenames.sort((a, b) => {
|
||||
a = a.toLowerCase();
|
||||
b = b.toLowerCase();
|
||||
if (a < b) return -1;
|
||||
if (a > b) return 1;
|
||||
return 0;
|
||||
});
|
||||
// Store the data read from each snippet in the appropriate object
|
||||
for(let snippet of snippetFilenames) snippets[snippet] = fs.readFileSync(path.join(snippetsPath,snippet),'utf8');
|
||||
}
|
||||
catch (err){ // Handle errors (hopefully not!)
|
||||
console.log(`${chalk.red('ERROR!')} During snippet loading: ${err}`);
|
||||
process.exit(1);
|
||||
}
|
||||
// Load static parts for the index.html file
|
||||
try {
|
||||
startPart = fs.readFileSync(path.join(staticPartsPath,'index-start.html'),'utf8');
|
||||
endPart = fs.readFileSync(path.join(staticPartsPath,'index-end.html'),'utf8');
|
||||
}
|
||||
catch (err){ // Handle errors (hopefully not!)
|
||||
console.log(`${chalk.red('ERROR!')} During static part loading: ${err}`);
|
||||
process.exit(1);
|
||||
}
|
||||
// Load tag data from the database
|
||||
try {
|
||||
tagDbData = objectFromPairs(fs.readFileSync('tag_database','utf8').split('\n').slice(0,-1).map(v => v.split(':').slice(0,2)));
|
||||
}
|
||||
catch (err){ // Handle errors (hopefully not!)
|
||||
console.log(`${chalk.red('ERROR!')} During tag database loading: ${err}`);
|
||||
process.exit(1);
|
||||
}
|
||||
// Create the output for the index.html file
|
||||
try {
|
||||
// Add the start static part
|
||||
output += `${startPart+'\n'}`;
|
||||
// Loop over tags and snippets to create the table of contents
|
||||
for(let tag of [...new Set(Object.entries(tagDbData).map(t => t[1]))].filter(v => v).sort((a,b) => a.localeCompare(b))){
|
||||
output +=`<h3>`+md.render(`${capitalize(tag, true)}\n`).replace(/<p>/g,'').replace(/<\/p>/g,'')+`</h3>`;
|
||||
for(let taggedSnippet of Object.entries(tagDbData).filter(v => v[1] === tag))
|
||||
output += md.render(`[${taggedSnippet[0]}](#${taggedSnippet[0].toLowerCase()})\n`).replace(/<p>/g,'').replace(/<\/p>/g,'').replace(/<a/g,'<a class="sublink-1"');
|
||||
output += '\n';
|
||||
}
|
||||
output += `</nav><main class="col-sm-12 col-md-8 col-lg-9" style="height: 100%;overflow-y: auto; background: #eee;">`;
|
||||
// Loop over tags and snippets to create the list of snippets
|
||||
for(let tag of [...new Set(Object.entries(tagDbData).map(t => t[1]))].filter(v => v).sort((a,b) => a.localeCompare(b))){
|
||||
output +=md.render(`## ${capitalize(tag, true)}\n`).replace(/<h2>/g,'<h2 style="text-align:center;">');
|
||||
for(let taggedSnippet of Object.entries(tagDbData).filter(v => v[1] === tag))
|
||||
output += '<div class="card fluid"><div class="section double-padded">' + md.render(`\n${snippets[taggedSnippet[0]+'.md']}`).replace(/<h3/g,`<h3 id="${taggedSnippet[0].toLowerCase()}"`).replace(/<\/h3>/g,'</h3></div><div class="section double-padded">') + '</div></div><br/>';
|
||||
}
|
||||
// Add the ending static part
|
||||
output += `\n${endPart+'\n'}`;
|
||||
// Write to the index.html file
|
||||
fs.writeFileSync(path.join(docsPath,'index.html'), output);
|
||||
}
|
||||
catch (err){ // Handle errors (hopefully not!)
|
||||
console.log(`${chalk.red('ERROR!')} During index.html generation: ${err}`);
|
||||
process.exit(1);
|
||||
}
|
||||
// Log a success message
|
||||
console.log(`${chalk.green('SUCCESS!')} index.html file generated!`);
|
||||
// Log the time taken
|
||||
console.timeEnd('Builder');
|
||||
@ -1,4 +1,6 @@
|
||||
### Snippet title
|
||||
### functionName
|
||||
|
||||
Explain briefly what the snippet does.
|
||||
|
||||
Explain briefly how the snippet works.
|
||||
|
||||
|
||||
@ -1,9 +1,11 @@
|
||||
### JSON to date
|
||||
### JSONToDate
|
||||
|
||||
Converts a JSON object to a date.
|
||||
|
||||
Use `Date()`, to convert dates in JSON format to readable format (`dd/mm/yyyy`).
|
||||
|
||||
```js
|
||||
const jsonToDate = arr => {
|
||||
const JSONToDate = arr => {
|
||||
const dt = new Date(parseInt(arr.toString().substr(6)));
|
||||
return `${ dt.getDate() }/${ dt.getMonth() + 1 }/${ dt.getFullYear() }`
|
||||
};
|
||||
@ -1,9 +1,11 @@
|
||||
### Write JSON to file
|
||||
### JSONToFile
|
||||
|
||||
Writes a JSON object to a file.
|
||||
|
||||
Use `fs.writeFile()`, template literals and `JSON.stringify()` to write a `json` object to a `.json` file.
|
||||
|
||||
```js
|
||||
const fs = require('fs');
|
||||
const jsonToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2))
|
||||
const JSONToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2))
|
||||
// jsonToFile({test: "is passed"}, 'testJsonFile') -> writes the object to 'testJsonFile.json'
|
||||
```
|
||||
@ -1,8 +1,10 @@
|
||||
### RGB to hexadecimal
|
||||
### RGBToHex
|
||||
|
||||
Converts the values of RGB components to a colorcode.
|
||||
|
||||
Convert given RGB parameters to hexadecimal string using bitwise left-shift operator (`<<`) and `toString(16)`, then `padStart(6,'0')` to get a 6-digit hexadecimal value.
|
||||
|
||||
```js
|
||||
const rgbToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
|
||||
const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
|
||||
// rgbToHex(255, 165, 1) -> 'ffa501'
|
||||
```
|
||||
@ -1,9 +1,11 @@
|
||||
### UUID generator
|
||||
### UUIDGenerator
|
||||
|
||||
Generates a UUID.
|
||||
|
||||
Use `crypto` API to generate a UUID, compliant with [RFC4122](https://www.ietf.org/rfc/rfc4122.txt) version 4.
|
||||
|
||||
```js
|
||||
const uuidGenerator = () =>
|
||||
const UUIDGenerator = () =>
|
||||
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
|
||||
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
|
||||
);
|
||||
@ -1,4 +1,6 @@
|
||||
### Anagrams of string (with duplicates)
|
||||
### anagrams
|
||||
|
||||
Generates all anagrams of a string (contains duplicates).
|
||||
|
||||
Use recursion.
|
||||
For each letter in the given string, create all the partial anagrams for the rest of its letters.
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
### Average of array of numbers
|
||||
### arrayAverage
|
||||
|
||||
Returns the average of an array of numbers.
|
||||
|
||||
Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array.
|
||||
|
||||
```js
|
||||
const average = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length;
|
||||
const arrayAverage = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length;
|
||||
// average([1,2,3]) -> 2
|
||||
```
|
||||
@ -1,4 +1,6 @@
|
||||
### Get max value from array
|
||||
### arrayMax
|
||||
|
||||
Returns the maximum value in an array.
|
||||
|
||||
Use `Math.max()` combined with the spread operator (`...`) to get the maximum value in the array.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Get min value from array
|
||||
### arrayMin
|
||||
|
||||
Returns the minimum value in an array.
|
||||
|
||||
Use `Math.min()` combined with the spread operator (`...`) to get the minimum value in the array.
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
### Sum of array of numbers
|
||||
### arraySum
|
||||
|
||||
Returns the sum of an array of numbers.
|
||||
|
||||
Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`.
|
||||
|
||||
```js
|
||||
const sumArrayNumbers = arr => arr.reduce((acc, val) => acc + val, 0);
|
||||
const arraySum = arr => arr.reduce((acc, val) => acc + val, 0);
|
||||
// sum([1,2,3,4]) -> 10
|
||||
```
|
||||
@ -1,4 +1,6 @@
|
||||
### Bottom visible
|
||||
### bottomVisible
|
||||
|
||||
Returns `true` if the bottom of the page is visible, `false` otherwise.
|
||||
|
||||
Use `scrollY`, `scrollHeight` and `clientHeight` to determine if the bottom of the page is visible.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Capitalize first letter
|
||||
### Capitalize
|
||||
|
||||
Capitalizes the first letter of a string.
|
||||
|
||||
Use destructuring and `toUpperCase()` to capitalize first letter, `...rest` to get array of characters after first letter and then `Array.join('')` to make it a string again.
|
||||
Omit the `lowerRest` parameter to keep the rest of the string intact, or set it to `true` to convert to lower case.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Capitalize first letter of every word
|
||||
### capitalizeEveryWord
|
||||
|
||||
Capitalizes the first letter of every word in a string.
|
||||
|
||||
Use `replace()` to match the first character of each word and `toUpperCase()` to capitalize it.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Chain asynchronous functions
|
||||
### chainAsync
|
||||
|
||||
Chains asynchronous functions.
|
||||
|
||||
Loop through an array of functions containing asynchronous events, calling `next` when each asynchronous event has completed.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Chunk array
|
||||
### chunk
|
||||
|
||||
Chunks an array into smaller arrays of a specified size.
|
||||
|
||||
Use `Array.from()` to create a new array, that fits the number of chunks that will be produced.
|
||||
Use `Array.slice()` to map each element of the new array to a chunk the length of `size`.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Clean JSON object
|
||||
### cleanObj
|
||||
|
||||
Removes any properties except the ones specified from a JSON object.
|
||||
|
||||
Use `Object.keys()` method to loop over given json object and deleting keys that are not `include`d in given array.
|
||||
also if you give it a special key(`childIndicator`) it will search deeply inside it to apply function to inner objects too.
|
||||
@ -1,4 +1,6 @@
|
||||
### Collatz algorithm
|
||||
### collatz
|
||||
|
||||
Applies the Collatz algorithm.
|
||||
|
||||
If `n` is even, return `n/2`. Otherwise return `3n+1`.
|
||||
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Compact
|
||||
### compact
|
||||
|
||||
Removes falsey values from an array.
|
||||
|
||||
Use `Array.filter()` to filter out falsey values (`false`, `null`, `0`, `""`, `undefined`, and `NaN`).
|
||||
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Compose functions
|
||||
### compose
|
||||
|
||||
Performs right-to-left function composition.
|
||||
|
||||
Use `Array.reduce()` to perform right-to-left function composition.
|
||||
The last (rightmost) function can accept one or more arguments; the remaining functions must be unary.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Count occurrences of a value in array
|
||||
### countOccurrences
|
||||
|
||||
Counts the occurences of a value in an array.
|
||||
|
||||
Use `Array.reduce()` to increment a counter each time you encounter the specific value inside the array.
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
### Current URL
|
||||
### currentURL
|
||||
|
||||
Returns the current URL.
|
||||
|
||||
Use `window.location.href` to get current URL.
|
||||
|
||||
```js
|
||||
const currentUrl = () => window.location.href;
|
||||
const currentURL = () => window.location.href;
|
||||
// currentUrl() -> 'https://google.com'
|
||||
```
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Curry
|
||||
### curry
|
||||
|
||||
Curries a function.
|
||||
|
||||
Use recursion.
|
||||
If the number of provided arguments (`args`) is sufficient, call the passed function `f`.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Deep flatten array
|
||||
### deepFlatten
|
||||
|
||||
Deep flattens an array.
|
||||
|
||||
Use recursion.
|
||||
Use `Array.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array.
|
||||
@ -1,4 +1,6 @@
|
||||
### Array difference
|
||||
### difference
|
||||
|
||||
Returns the difference between two arrays.
|
||||
|
||||
Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values not contained in `b`.
|
||||
|
||||
|
||||
@ -1,7 +1,9 @@
|
||||
### Number to array of digits
|
||||
### digitize
|
||||
|
||||
Converts a number to an array of digits.
|
||||
|
||||
Convert the number to a string, using spread operators in ES6(`[...string]`) build an array.
|
||||
Use `Array.map()` and `parseInt()` to transform each value to an integer.
|
||||
Use `Array.map()` and `parseInt()` to transform each value to an integer.
|
||||
|
||||
```js
|
||||
const digitize = n => [...''+n].map(i => parseInt(i));
|
||||
@ -1,4 +1,6 @@
|
||||
### Distance between two points
|
||||
### distance
|
||||
|
||||
Returns the distance between two points.
|
||||
|
||||
Use `Math.hypot()` to calculate the Euclidean distance between two points.
|
||||
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
### Unique values of array
|
||||
### distinctValuesOfArray
|
||||
|
||||
Returns all the distinct values of an array.
|
||||
|
||||
Use ES6 `Set` and the `...rest` operator to discard all duplicated values.
|
||||
|
||||
```js
|
||||
const uniqueValuesOfArray = arr => [...new Set(arr)];
|
||||
const distinctValuesOfArray = arr => [...new Set(arr)];
|
||||
// unique([1,2,2,3,4,4,5]) -> [1,2,3,4,5]
|
||||
```
|
||||
@ -1,6 +1,8 @@
|
||||
### Drop elements in array
|
||||
### dropElements
|
||||
|
||||
Loop through the array, using `Array.shift()` to drop the first element of the array until the returned value from the function is `true`.
|
||||
Removes elements in an array until the passed function returns `true`. Returns the remaining elements in the array.
|
||||
|
||||
Loop through the array, using `Array.shift()` to drop the first element of the array until the returned value from the function is `true`.
|
||||
Returns the remaining elements.
|
||||
|
||||
```js
|
||||
@ -1,4 +1,6 @@
|
||||
### Element is visible in viewport
|
||||
### elementIsVisibleInViewport
|
||||
|
||||
Returns `true` if the element specified is visible in the viewport, `false` otherwise.
|
||||
|
||||
Use `Element.getBoundingClientRect()` and the `window.inner(Width|Height)` values
|
||||
to determine if a given element is visible in the viewport.
|
||||
@ -1,4 +1,6 @@
|
||||
### Escape regular expression
|
||||
### escapeRegExp
|
||||
|
||||
Escapes a string to use in a regular expression.
|
||||
|
||||
Use `replace()` to escape special characters.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Take every nth element
|
||||
### everyNth
|
||||
|
||||
Returns every nth element in an array.
|
||||
|
||||
Use `Array.filter()` to create a new array that contains every nth element of a given array.
|
||||
|
||||
@ -1,10 +1,12 @@
|
||||
### 3-digit hexcode to 6-digit hexcode
|
||||
### extendHex
|
||||
|
||||
Use `Array.map()`, `split()` and `Array.join()` to join the mapped array for converting a three-digit RGB notated hexadecimal color-code to the six-digit form.
|
||||
Extends a 3-digit color code to a 6-digit color code.
|
||||
|
||||
Use `Array.map()`, `split()` and `Array.join()` to join the mapped array for converting a 3-digit RGB notated hexadecimal color-code to the 6-digit form.
|
||||
`Array.slice()` is used to remove `#` from string start since it's added once.
|
||||
```js
|
||||
const extendHex = shortHex =>
|
||||
'#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split().map(x => x+x).join()
|
||||
'#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split('').map(x => x+x).join('')
|
||||
// convertHex('#03f') -> '#0033ff'
|
||||
// convertHex('05a') -> '#0055aa'
|
||||
```
|
||||
@ -1,4 +1,6 @@
|
||||
### Factorial
|
||||
### factorial
|
||||
|
||||
Calculates the factorial of a number.
|
||||
|
||||
Use recursion.
|
||||
If `n` is less than or equal to `1`, return `1`.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Fibonacci array generator
|
||||
### fibonacci
|
||||
|
||||
Generates an array, containing the Fibonacci sequence, up until the nth term.
|
||||
|
||||
Create an empty array of the specific length, initializing the first two values (`0` and `1`).
|
||||
Use `Array.reduce()` to add values into the array, using the sum of the last two values, except for the first two.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Filter out non-unique values in an array
|
||||
### filterNonUnique
|
||||
|
||||
Filters out the non-unique values in an array.
|
||||
|
||||
Use `Array.filter()` for an array containing only the unique values.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Flatten array
|
||||
### flatten
|
||||
|
||||
Flattens an array.
|
||||
|
||||
Use `Array.reduce()` to get all elements inside the array and `concat()` to flatten them.
|
||||
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Flatten array up to depth
|
||||
### flattenDepth
|
||||
|
||||
Flattens an array up to the specified depth.
|
||||
|
||||
Use recursion, decrementing `depth` by 1 for each level of depth.
|
||||
Use `Array.reduce()` and `Array.concat()` to merge elements or arrays.
|
||||
@ -1,10 +1,12 @@
|
||||
### Convert string from camelcase
|
||||
### fromCamelCase
|
||||
|
||||
Converts a string from camelcase.
|
||||
|
||||
Use `replace()` to remove underscores, hyphens and spaces and convert words to camelcase.
|
||||
Omit the scond argument to use a default separator of '_'.
|
||||
Omit the scond argument to use a default separator of `_`.
|
||||
|
||||
```js
|
||||
const fromCamelCase = (str, separator = '_') =>
|
||||
const fromCamelCase = (str, separator = '_') =>
|
||||
str.replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2')
|
||||
.replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2').toLowerCase();
|
||||
// fromCamelCase('someDatabaseFieldName', ' ') -> 'some database field name'
|
||||
@ -1,4 +1,6 @@
|
||||
### Log function name
|
||||
### functionName
|
||||
|
||||
Logs the name of a function.
|
||||
|
||||
Use `console.debug()` and the `name` property of the passed method to log the method's name to the `debug` channel of the console.
|
||||
|
||||
@ -1,10 +1,12 @@
|
||||
### Greatest common divisor (GCD)
|
||||
### gcd
|
||||
|
||||
Calculates the greatest common divisor between two numbers.
|
||||
|
||||
Use recursion.
|
||||
Base case is when `y` equals `0`. In this case, return `x`.
|
||||
Otherwise, return the GCD of `y` and the remainder of the division `x/y`.
|
||||
|
||||
```js
|
||||
const greatestCommonDivisor = (x, y) => !y ? x : gcd(y, x % y);
|
||||
const gcd = (x, y) => !y ? x : gcd(y, x % y);
|
||||
// gcd (8, 36) -> 4
|
||||
```
|
||||
@ -1,4 +1,6 @@
|
||||
### Get days difference between dates
|
||||
### getDaysDiffBetweenDates
|
||||
|
||||
Returns the difference (in days) between two dates.
|
||||
|
||||
Calculate the difference (in days) between to `Date` objects.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Get scroll position
|
||||
### getScrollPosition
|
||||
|
||||
Returns the scroll position of the current page.
|
||||
|
||||
Use `pageXOffset` and `pageYOffset` if they are defined, otherwise `scrollLeft` and `scrollTop`.
|
||||
You can omit `el` to use a default value of `window`.
|
||||
@ -1,4 +1,6 @@
|
||||
### Get native type of value
|
||||
### getType
|
||||
|
||||
Returns the native type of a value.
|
||||
|
||||
Returns lower-cased constructor name of value, "undefined" or "null" if value is undefined or null
|
||||
|
||||
@ -1,10 +1,12 @@
|
||||
### URL parameters
|
||||
### getURLParameters
|
||||
|
||||
Returns an object containing the parameters of the current URL.
|
||||
|
||||
Use `match()` with an appropriate regular expression to get all key-value pairs, `Array.reduce()` to map and combine them into a single object.
|
||||
Pass `location.search` as the argument to apply to the current `url`.
|
||||
|
||||
```js
|
||||
const getUrlParameters = url =>
|
||||
const getURLParameters = url =>
|
||||
url.match(/([^?=&]+)(=([^&]*))/g).reduce(
|
||||
(a, v) => (a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1), a), {}
|
||||
);
|
||||
@ -1,4 +1,6 @@
|
||||
### Group by
|
||||
### groupBy
|
||||
|
||||
Groups the element of an array based on the given function.
|
||||
|
||||
Use `Array.map()` to map the values of an array to a function or property name.
|
||||
Use `Array.reduce()` to create an object, where the keys are produced from the mapped results.
|
||||
@ -1,4 +1,6 @@
|
||||
### Hamming distance
|
||||
### hammingDistance
|
||||
|
||||
Calculates the Hamming distance between two values.
|
||||
|
||||
Use XOR operator (`^`) to find the bit difference between the two numbers, convert to binary string using `toString(2)`.
|
||||
Count and return the number of `1`s in the string, using `match(/1/g)`.
|
||||
@ -1,4 +1,6 @@
|
||||
### Head of list
|
||||
### head
|
||||
|
||||
Returns the head of a list.
|
||||
|
||||
Use `arr[0]` to return the first element of the passed array.
|
||||
|
||||
|
||||
@ -1,11 +0,0 @@
|
||||
### Hexcode to RGB
|
||||
|
||||
Use bitwise right-shift operator and mask bits with `&` (and) operator to convert a hexadecimal color code (prefixed with `#`) to a string with the RGB values.
|
||||
|
||||
```js
|
||||
const hexToRgb = hex => {
|
||||
const h = parseInt(hex.slice(1), 16);
|
||||
return `rgb(${h >> 16}, ${(h & 0x00ff00) >> 8}, ${h & 0x0000ff})`;
|
||||
}
|
||||
// hexToRgb('#27ae60') -> 'rgb(39, 174, 96)'
|
||||
```
|
||||
17
snippets/hexToRGB.md
Normal file
17
snippets/hexToRGB.md
Normal file
@ -0,0 +1,17 @@
|
||||
### hexToRGB
|
||||
|
||||
Converts a colorcode to a `rgb()` string.
|
||||
|
||||
Use bitwise right-shift operator and mask bits with `&` (and) operator to convert a hexadecimal color code (prefixed with `#`) to a string with the RGB values. In case it's a 3-digit-colorcode, do the same with the 6-digit-colorcode extended by the extendHex() function (ref. `extendHex` snippet)
|
||||
|
||||
```js
|
||||
const hexToRgb = hex => {
|
||||
const extendHex = shortHex =>
|
||||
'#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split('').map(x => x+x).join('');
|
||||
return hex.slice(1).length==3 ?
|
||||
`rgb(${parseInt(extendHex(hex).slice(1), 16) >> 16}, ${(parseInt(extendHex(hex).slice(1), 16) & 0x00ff00) >> 8}, ${parseInt(extendHex(hex).slice(1), 16) & 0x0000ff})`:
|
||||
`rgb(${parseInt(hex.slice(1), 16) >> 16}, ${(parseInt(hex.slice(1), 16) & 0x00ff00) >> 8}, ${parseInt(hex.slice(1), 16) & 0x0000ff})`;
|
||||
}
|
||||
// hexToRgb('#27ae60') -> 'rgb(39, 174, 96)'
|
||||
// hexToRgb('#acd') -> 'rgb(170, 204, 221)'
|
||||
```
|
||||
@ -1,4 +1,6 @@
|
||||
### Initial of list
|
||||
### initial
|
||||
|
||||
Returns all the elements of an array except the last one.
|
||||
|
||||
Use `arr.slice(0,-1)`to return all but the last element of the array.
|
||||
|
||||
|
||||
@ -1,10 +1,12 @@
|
||||
### Initialize array with range
|
||||
### initializeArrayWithRange
|
||||
|
||||
Initialized an array containing the numbers in the specified range.
|
||||
|
||||
Use `Array(end-start)` to create an array of the desired length, `Array.map()` to fill with the desired values in a range.
|
||||
You can omit `start` to use a default value of `0`.
|
||||
|
||||
```js
|
||||
const initializeArrayRange = (end, start = 0) =>
|
||||
const initializeArrayWithRange = (end, start = 0) =>
|
||||
Array.from({ length: end - start }).map((v, i) => i + start);
|
||||
// initializeArrayRange(5) -> [0,1,2,3,4]
|
||||
```
|
||||
@ -1,9 +1,11 @@
|
||||
### Initialize array with values
|
||||
### initializeArrayWithValues
|
||||
|
||||
Initializes and fills an array with the specified values.
|
||||
|
||||
Use `Array(n)` to create an array of the desired length, `fill(v)` to fill it with the desired values.
|
||||
You can omit `value` to use a default value of `0`.
|
||||
|
||||
```js
|
||||
const initializeArray = (n, value = 0) => Array(n).fill(value);
|
||||
const initializeArrayWithValues = (n, value = 0) => Array(n).fill(value);
|
||||
// initializeArray(5, 2) -> [2,2,2,2,2]
|
||||
```
|
||||
@ -1,4 +1,6 @@
|
||||
### Array intersection
|
||||
### intersection
|
||||
|
||||
Returns a list of elements that exist in both arrays.
|
||||
|
||||
Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values contained in `b`.
|
||||
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Is array
|
||||
### isArray
|
||||
|
||||
Checks if the given argument is an array.
|
||||
|
||||
Use `Array.isArray()` to check if a value is classified as an array.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Is boolean
|
||||
### isBoolean
|
||||
|
||||
Checks if the given argument is a native boolean element.
|
||||
|
||||
Use `typeof` to check if a value is classified as a boolean primitive.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Divisible by number
|
||||
### isDivisible
|
||||
|
||||
Checks if the first numeric argument is divisible by the second one.
|
||||
|
||||
Use the modulo operator (`%`) to check if the remainder is equal to `0`.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Even or odd number
|
||||
### isEven
|
||||
|
||||
Returns `true` if the given number is even, `false` otherwise.
|
||||
|
||||
Checks whether a number is odd or even using the modulo (`%`) operator.
|
||||
Returns `true` if the number is even, `false` if the number is odd.
|
||||
@ -1,4 +1,6 @@
|
||||
### Is function
|
||||
### isFunction
|
||||
|
||||
Checks if the given argument is a function.
|
||||
|
||||
Use `typeof` to check if a value is classified as a function primitive.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Is number
|
||||
### isNumber
|
||||
|
||||
Checks if the given argument is a number.
|
||||
|
||||
Use `typeof` to check if a value is classified as a number primitive.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Is string
|
||||
### isString
|
||||
|
||||
Checks if the given argument is a string.
|
||||
|
||||
Use `typeof` to check if a value is classified as a string primitive.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Is symbol
|
||||
### isSymbol
|
||||
|
||||
Checks if the given argument is a symbol.
|
||||
|
||||
Use `typeof` to check if a value is classified as a symbol primitive.
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
### Last of list
|
||||
### last
|
||||
|
||||
Returns the last element in an array.
|
||||
|
||||
Use `arr.length - 1` to compute index of the last element of the given array and returning it.
|
||||
|
||||
```js
|
||||
const lastOfArray = arr => arr[arr.length - 1];
|
||||
const last = arr => arr[arr.length - 1];
|
||||
// last([1,2,3]) -> 3
|
||||
```
|
||||
@ -1,10 +1,12 @@
|
||||
### Least common multiple (LCM)
|
||||
### lcm
|
||||
|
||||
Returns the least common multiple of two numbers.
|
||||
|
||||
Use the greatest common divisor (GCD) formula and `Math.abs()` to determine the least common multiple.
|
||||
The GCD formula uses recursion.
|
||||
|
||||
```js
|
||||
const leastCommonMultiple = (x,y) => {
|
||||
const lcm = (x,y) => {
|
||||
const gcd = (x, y) => !y ? x : gcd(y, x % y);
|
||||
return Math.abs(x*y)/(gcd(x,y));
|
||||
};
|
||||
@ -1,4 +1,6 @@
|
||||
### Median of array of numbers
|
||||
### median
|
||||
|
||||
Returns the median of an array of numbers.
|
||||
|
||||
Find the middle of the array, use `Array.sort()` to sort the values.
|
||||
Return the number at the midpoint if `length` is odd, otherwise the average of the two middle numbers.
|
||||
@ -1,4 +1,6 @@
|
||||
### Nth element of array
|
||||
### nthElement
|
||||
|
||||
Returns the nth element of an array.
|
||||
|
||||
Use `Array.slice()` to get an array containing the nth element at the first place.
|
||||
If the index is out of bounds, return `[]`.
|
||||
@ -1,4 +1,6 @@
|
||||
### Object from key-value pairs
|
||||
### objectFromPairs
|
||||
|
||||
Creates an object from the given key-value pairs.
|
||||
|
||||
Use `Array.reduce()` to create and combine key-value pairs.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Object to key-value pairs
|
||||
### objectToPairs
|
||||
|
||||
Creates an array of key-value pair arrays from an object.
|
||||
|
||||
Use `Object.keys()` and `Array.map()` to iterate over the object's keys and produce an array with key-value pairs.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Check for palindrome
|
||||
### palindrome
|
||||
|
||||
Returns `true` if the given string is a palindrome, `false` otherwise.
|
||||
|
||||
Convert string `toLowerCase()` and use `replace()` to remove non-alphanumeric characters from it.
|
||||
Then, `split('')` into individual characters, `reverse()`, `join('')` and compare to the original, unreversed string, after converting it `tolowerCase()`.
|
||||
|
||||
@ -1,10 +1,11 @@
|
||||
### Percentile
|
||||
### percentile
|
||||
|
||||
Use `Array.reduce()` to calculate how many numbers are below the value and how many are the same value and
|
||||
apply the percentile formula.
|
||||
Uses the percentile formula to calculate how many numbers in the given array are less or equal to the given value.
|
||||
|
||||
Use `Array.reduce()` to calculate how many numbers are below the value and how many are the same value and apply the percentile formula.
|
||||
|
||||
```js
|
||||
const percentile = (arr, val) =>
|
||||
const percentile = (arr, val) =>
|
||||
100 * arr.reduce((acc,v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), 0) / arr.length;
|
||||
// percentile([1,2,3,4,5,6,7,8,9,10], 6) -> 55
|
||||
```
|
||||
|
||||
@ -1,10 +1,11 @@
|
||||
### Pick
|
||||
### pick
|
||||
|
||||
Use `Array.reduce()` to convert the filtered/picked keys back to a object with the corresponding key:value pair if the key exist in the obj.
|
||||
Picks the key-value pairs corresponding to the given keys from an object.
|
||||
|
||||
Use `Array.reduce()` to convert the filtered/picked keys back to a object with the corresponding key-value pair if the key exist in the obj.
|
||||
|
||||
```js
|
||||
const pick = (obj, arr) =>
|
||||
arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {});
|
||||
// pick({ 'a': 1, 'b': '2', 'c': 3 }, ['a', 'c']) -> { 'a': 1, 'c': 3 }
|
||||
// pick(object, ['a', 'c'])['a'] -> 1
|
||||
```
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Pipe functions
|
||||
### pipe
|
||||
|
||||
Performs left-to-right function composition.
|
||||
|
||||
Use `Array.reduce()` with the spread operator (`...`) to perform left-to-right function composition.
|
||||
The first (leftmost) function can accept one or more arguments; the remaining functions must be unary.
|
||||
@ -1,4 +1,6 @@
|
||||
### Powerset
|
||||
### powerset
|
||||
|
||||
Returns the powerset of a given array of numbers.
|
||||
|
||||
Use `Array.reduce()` combined with `Array.map()` to iterate over elements and combine into an array containing all combinations.
|
||||
|
||||
|
||||
@ -1,7 +1,9 @@
|
||||
### Promisify
|
||||
### promisify
|
||||
|
||||
Use currying to return a function returning a `Promise` that calls the original function.
|
||||
Use the `...rest` operator to pass in all the parameters.
|
||||
Converts an asynchronous function to return a promise.
|
||||
|
||||
Use currying to return a function returning a `Promise` that calls the original function.
|
||||
Use the `...rest` operator to pass in all the parameters.
|
||||
|
||||
*In Node 8+, you can use [`util.promisify`](https://nodejs.org/api/util.html#util_util_promisify_original)*
|
||||
|
||||
|
||||
@ -1,6 +1,8 @@
|
||||
### Array pull (mutates array)
|
||||
### pull
|
||||
|
||||
Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed.
|
||||
Mutates the original array to filter out the values specified.
|
||||
|
||||
Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed.
|
||||
Use `Array.length = 0` to mutate the passed in array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
|
||||
|
||||
```js
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Random integer in range
|
||||
### randomIntegerInRange
|
||||
|
||||
Returns a random integer in the specified range.
|
||||
|
||||
Use `Math.random()` to generate a random number and map it to the desired range, using `Math.floor()` to make it an integer.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Random number in range
|
||||
### randomNumberInRange
|
||||
|
||||
Returns a random number in the specified range.
|
||||
|
||||
Use `Math.random()` to generate a random value, map it to the desired range using multiplication.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Read file as array of lines
|
||||
### readFileLines
|
||||
|
||||
Returns an array of lines from the specified file.
|
||||
|
||||
Use `readFileSync` function in `fs` node package to create a `Buffer` from a file.
|
||||
convert buffer to string using `toString(encoding)` function.
|
||||
@ -6,7 +8,7 @@ creating an array from contents of file by `split`ing file content line by line(
|
||||
|
||||
```js
|
||||
const fs = require('fs');
|
||||
const readFileToArray = filename => fs.readFileSync(filename).toString('UTF8').split('\n');
|
||||
const readFileLines = filename => fs.readFileSync(filename).toString('UTF8').split('\n');
|
||||
/*
|
||||
contents of test.txt :
|
||||
line1
|
||||
@ -1,4 +1,6 @@
|
||||
### Redirect to URL
|
||||
### redirect
|
||||
|
||||
Redirects to a specified URL.
|
||||
|
||||
Use `window.location.href` or `window.location.replace()` to redirect to `url`.
|
||||
Pass a second argument to simulate a link click (`true` - default) or an HTTP redirect (`false`).
|
||||
@ -1,4 +1,6 @@
|
||||
### Array remove
|
||||
### remove
|
||||
|
||||
Removes elements from an array for which the given function returns `false`.
|
||||
|
||||
Use `Array.filter()` to find array elements that return truthy values and `Array.reduce()` to remove elements using `Array.splice()`.
|
||||
The `func` is invoked with three arguments (`value, index, array`).
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Reverse a string
|
||||
### reverseString
|
||||
|
||||
Reverses a string.
|
||||
|
||||
Use array destructuring and `Array.reverse()` to reverse the order of the characters in the string.
|
||||
Combine characters to get a string using `join('')`.
|
||||
@ -1,4 +1,6 @@
|
||||
### Round number to n digits
|
||||
### round
|
||||
|
||||
Rounds a number to a specified amount of digits.
|
||||
|
||||
Use `Math.round()` and template literals to round the number to the specified number of digits.
|
||||
Omit the second argument, `decimals` to round to an integer.
|
||||
@ -1,6 +1,8 @@
|
||||
### Run promises in series
|
||||
### runPromisesInSeries
|
||||
|
||||
Run an array of promises in series using `Array.reduce()` by creating a promise chain, where each promise returns the next promise when resolved.
|
||||
Runs an array of promises in series.
|
||||
|
||||
Use `Array.reduce()` to create a promise chain, where each promise returns the next promise when resolved.
|
||||
|
||||
```js
|
||||
const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());
|
||||
@ -1,4 +1,6 @@
|
||||
### Array sample
|
||||
### sample
|
||||
|
||||
Returns a random element from an array.
|
||||
|
||||
Use `Math.random()` to generate a random number, multiply it with `length` and round it of to the nearest whole number using `Math.floor()`.
|
||||
This method also works with strings.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Scroll to top
|
||||
### scrollToTop
|
||||
|
||||
Smooth-scrolls to the top of the page.
|
||||
|
||||
Get distance from top using `document.documentElement.scrollTop` or `document.body.scrollTop`.
|
||||
Scroll by a fraction of the distance from top. Use `window.requestAnimationFrame()` to animate the scrolling.
|
||||
@ -1,4 +1,6 @@
|
||||
### Shallow clone object
|
||||
### shallowClone
|
||||
|
||||
Creates a shallow clone of an object.
|
||||
|
||||
Use `Object.assign()` and an empty object (`{}`) to create a shallow clone of the original.
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
### Shuffle array
|
||||
### shuffle
|
||||
|
||||
Randomizes the order of the values of an array.
|
||||
|
||||
Use `Array.sort()` to reorder elements, using `Math.random()` in the comparator.
|
||||
|
||||
```js
|
||||
const shuffleArray = arr => arr.sort(() => Math.random() - 0.5);
|
||||
const shuffle = arr => arr.sort(() => Math.random() - 0.5);
|
||||
// shuffle([1,2,3]) -> [2,3,1]
|
||||
```
|
||||
@ -1,4 +1,6 @@
|
||||
### Similarity between arrays
|
||||
### similarity
|
||||
|
||||
Returns an array of elements that appear in both arrays.
|
||||
|
||||
Use `filter()` to remove values that are not part of `values`, determined using `includes()`.
|
||||
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Sleep
|
||||
### sleep
|
||||
|
||||
Delays the execution of an asynchronous function.
|
||||
|
||||
Delay executing part of an `async` function, by putting it to sleep, returning a `Promise`.
|
||||
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Sort characters in string (alphabetical)
|
||||
### sortCharactersInString
|
||||
|
||||
Alphabetically sorts the characters in a string.
|
||||
|
||||
Split the string using `split('')`, `Array.sort()` utilizing `localeCompare()`, recombine using `join('')`.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Speech synthesis (experimental)
|
||||
### speechSynthesis
|
||||
|
||||
Performs speech synthesis (experimental).
|
||||
|
||||
Use `SpeechSynthesisUtterance.voice` and `window.speechSynthesis.getVoices()` to convert a message to speech.
|
||||
Use `window.speechSynthesis.speak()` to play the message.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user