Snippet format update

To match the starter (for the migration)
This commit is contained in:
Angelos Chalaris
2019-08-13 10:29:12 +03:00
parent a5164f392a
commit 611729214a
381 changed files with 1951 additions and 1989 deletions

24
migrator.js Normal file
View File

@ -0,0 +1,24 @@
const snippets = require('./snippet_data/snippets.json');
const fs = require('fs-extra');
const path = require('path');
snippets.data.forEach(snippet => {
fs.writeFileSync(
path.join(
snippet.meta.archived ? './snippets_archive' : './snippets',
`${snippet.attributes.fileName}`),
`---
title: ${snippet.id}
tags: ${snippet.attributes.tags.join(',')}
---
${snippet.attributes.text}
\`\`\`js
${snippet.attributes.codeBlocks.es6}
\`\`\`
\`\`\`js
${snippet.attributes.codeBlocks.example}
\`\`\``);
});

45
package-lock.json generated
View File

@ -3488,7 +3488,7 @@
"version": "1.2.5",
"bundled": true,
"requires": {
"minipass": "2.2.4"
"minipass": "^2.2.1"
}
},
"fs.realpath": {
@ -3606,17 +3606,16 @@
"minipass": {
"version": "2.2.4",
"bundled": true,
"optional": true,
"requires": {
"safe-buffer": "5.1.1",
"yallist": "3.0.2"
"safe-buffer": "^5.1.1",
"yallist": "^3.0.0"
}
},
"minizlib": {
"version": "1.1.0",
"bundled": true,
"requires": {
"minipass": "2.2.4"
"minipass": "^2.2.1"
}
},
"mkdirp": {
@ -3651,16 +3650,16 @@
"dev": true,
"optional": true,
"requires": {
"detect-libc": "1.0.3",
"mkdirp": "0.5.1",
"needle": "2.2.0",
"nopt": "4.0.1",
"npm-packlist": "1.1.10",
"npmlog": "4.1.2",
"rc": "1.2.7",
"rimraf": "2.6.2",
"semver": "5.5.0",
"tar": "4.4.1"
"detect-libc": "^1.0.2",
"mkdirp": "^0.5.1",
"needle": "^2.2.0",
"nopt": "^4.0.1",
"npm-packlist": "^1.1.6",
"npmlog": "^4.0.2",
"rc": "^1.1.7",
"rimraf": "^2.6.1",
"semver": "^5.3.0",
"tar": "^4"
}
},
"nopt": {
@ -3802,8 +3801,7 @@
},
"safe-buffer": {
"version": "5.1.1",
"bundled": true,
"optional": true
"bundled": true
},
"safer-buffer": {
"version": "2.1.2",
@ -3893,8 +3891,7 @@
},
"yallist": {
"version": "3.0.2",
"bundled": true,
"optional": true
"bundled": true
}
}
},
@ -6049,11 +6046,11 @@
"integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=",
"dev": true,
"requires": {
"ansi-styles": "2.2.1",
"escape-string-regexp": "1.0.5",
"has-ansi": "2.0.0",
"strip-ansi": "3.0.1",
"supports-color": "2.0.0"
"ansi-styles": "^2.2.1",
"escape-string-regexp": "^1.0.2",
"has-ansi": "^2.0.0",
"strip-ansi": "^3.0.0",
"supports-color": "^2.0.0"
}
},
"cross-spawn": {

View File

@ -10,13 +10,11 @@
"glossary:keymaker": "node ./scripts/glossary/keyword.js",
"builder": "node ./scripts/build.js",
"linter": "node ./scripts/lint.js",
"tagger": "node ./scripts/tag.js",
"webber": "node ./scripts/web.js",
"tester": "node ./scripts/tdd.js",
"extractor": "node ./scripts/extract.js",
"vscoder": "node ./scripts/vscodegen.js",
"packager": "node ./scripts/module.js",
"localizer": "node ./scripts/localize.js",
"test": "jest --verbose --coverage"
},
"repository": {

View File

@ -1,66 +0,0 @@
/*
This is the tagger script that updates the tag_databse file and logs stats for snippet tags.
Run using `npm run tagger`.
*/
// Load modules
const fs = require('fs-extra'),
{ black, blue, green, yellow, red, bgWhite } = require('kleur');
const util = require('./util');
if (util.isTravisCI() && /^Travis build: \d+/g.test(process.env['TRAVIS_COMMIT_MESSAGE'])) {
console.log(`${green('NOBUILD')} Tagging terminated, parent commit is a Travis build!`);
process.exit(0);
}
// Set variables for paths
const snippetsPath = './snippets';
// Set variables for script
let snippets = {},
output = '',
tagDbData = {},
missingTags = 0,
tagDbStats = {};
// Start the timer of the script
console.time('Tagger');
// Synchronously read all snippets and sort them as necessary (case-insensitive)
snippets = util.readSnippets(snippetsPath);
// Load tag data from the database
tagDbData = util.readTags();
tagDbStats = Object.entries(tagDbData).reduce((acc, val) => {
val[1].forEach(v => (acc.hasOwnProperty(v) ? acc[v]++ : (acc[v] = 1)));
return acc;
}, {});
// Update the listing of snippets in tag_database and log the statistics, along with missing scripts
try {
for (let snippet of Object.entries(snippets)) {
if (
tagDbData.hasOwnProperty(snippet[0].slice(0, -3)) &&
tagDbData[snippet[0].slice(0, -3)].join(',').trim()
) {
output += `${snippet[0].slice(0, -3)}:${tagDbData[snippet[0].slice(0, -3)]
.join(',')
.trim()}\n`;
} else {
output += `${snippet[0].slice(0, -3)}:uncategorized\n`;
missingTags++;
console.log(`${yellow('Tagged uncategorized:')} ${snippet[0].slice(0, -3)}`);
}
}
// Write to tag_database
fs.writeFileSync('tag_database', output);
} catch (err) {
// Handle errors (hopefully not!)
console.log(`${red('ERROR!')} During tag_database generation: ${err}`);
process.exit(1);
}
// Log statistics for the tag_database file
console.log(`\n${bgWhite(black('=== TAG STATS ==='))}`);
for (let tagData of Object.entries(tagDbStats)
.filter(v => v[0] !== 'undefined')
.sort((a, b) => a[0].localeCompare(b[0])))
console.log(`${green(tagData[0])}: ${tagData[1]} snippets`);
console.log(
`${blue("New untagged snippets (will be tagged as 'uncategorized'):")} ${missingTags}\n`
);
// Log a success message
console.log(`${green('SUCCESS!')} tag_database file updated!`);
// Log the time taken
console.timeEnd('Tagger');

View File

@ -1,4 +1,7 @@
### CSVToArray
---
title: CSVToArray
tags: string,array,utility,intermediate
---
Converts a comma-separated values (CSV) string to a 2D array.
@ -19,4 +22,4 @@ const CSVToArray = (data, delimiter = ',', omitFirstRow = false) =>
CSVToArray('a,b\nc,d'); // [['a','b'],['c','d']];
CSVToArray('a;b\nc;d', ';'); // [['a','b'],['c','d']];
CSVToArray('col1,col2\na,b\nc,d', ',', true); // [['a','b'],['c','d']];
```
```

View File

@ -1,4 +1,7 @@
### CSVToJSON
---
title: CSVToJSON
tags: string,array,object,advanced
---
Converts a comma-separated values (CSV) string to a 2D array of objects.
The first row of the string is used as the title row.
@ -24,4 +27,4 @@ const CSVToJSON = (data, delimiter = ',') => {
```js
CSVToJSON('col1,col2\na,b\nc,d'); // [{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}];
CSVToJSON('col1;col2\na;b\nc;d', ';'); // [{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}];
```
```

View File

@ -1,4 +1,7 @@
### JSONToFile
---
title: JSONToFile
tags: node,json,intermediate
---
Writes a JSON object to a file.
@ -12,4 +15,4 @@ const JSONToFile = (obj, filename) =>
```js
JSONToFile({ test: 'is passed' }, 'testJsonFile'); // writes the object to 'testJsonFile.json'
```
```

View File

@ -1,4 +1,7 @@
### JSONtoCSV
---
title: JSONtoCSV
tags: array,string,object,advanced
---
Converts an array of objects to a comma-separated values (CSV) string that contains only the `columns` specified.
@ -23,4 +26,4 @@ const JSONtoCSV = (arr, columns, delimiter = ',') =>
```js
JSONtoCSV([{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }], ['a', 'b']); // 'a,b\n"1","2"\n"3","4"\n"6",""\n"","7"'
JSONtoCSV([{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }], ['a', 'b'], ';'); // 'a;b\n"1";"2"\n"3";"4"\n"6";""\n"";"7"'
```
```

View File

@ -1,4 +1,7 @@
### RGBToHex
---
title: RGBToHex
tags: utility,intermediate
---
Converts the values of RGB components to a color code.
@ -10,4 +13,4 @@ const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6
```js
RGBToHex(255, 165, 1); // 'ffa501'
```
```

View File

@ -1,4 +1,7 @@
### URLJoin
---
title: URLJoin
tags: string,utility,regexp,advanced
---
Joins all given URL segments together, then normalizes the resulting URL.
@ -18,4 +21,4 @@ const URLJoin = (...args) =>
```js
URLJoin('http://www.google.com', 'a', '/b/cd', '?foo=123', '?bar=foo'); // 'http://www.google.com/a/b/cd?foo=123&bar=foo'
```
```

View File

@ -1,4 +1,7 @@
### UUIDGeneratorBrowser
---
title: UUIDGeneratorBrowser
tags: browser,utility,random,intermediate
---
Generates a UUID in a browser.
@ -13,4 +16,4 @@ const UUIDGeneratorBrowser = () =>
```js
UUIDGeneratorBrowser(); // '7982fcfe-5721-4632-bede-6000885be57d'
```
```

View File

@ -1,4 +1,7 @@
### UUIDGeneratorNode
---
title: UUIDGeneratorNode
tags: node,utility,random,intermediate
---
Generates a UUID in Node.JS.
@ -14,4 +17,4 @@ const UUIDGeneratorNode = () =>
```js
UUIDGeneratorNode(); // '79c7c136-60ee-40a2-beb2-856f1feabefc'
```
```

View File

@ -1,4 +1,7 @@
### all
---
title: all
tags: array,function,beginner
---
Returns `true` if the provided predicate function returns `true` for all elements in a collection, `false` otherwise.
@ -12,4 +15,4 @@ const all = (arr, fn = Boolean) => arr.every(fn);
```js
all([4, 2, 3], x => x > 1); // true
all([1, 2, 3]); // true
```
```

View File

@ -1,4 +1,7 @@
### allEqual
---
title: allEqual
tags: array,function,beginner
---
Check if all elements in an array are equal.
@ -12,4 +15,4 @@ const allEqual = arr => arr.every(val => val === arr[0]);
```js
allEqual([1, 2, 3, 4, 5, 6]); // false
allEqual([1, 1, 1, 1]); // true
```
```

View File

@ -1,4 +1,7 @@
### any
---
title: any
tags: array,function,beginner
---
Returns `true` if the provided predicate function returns `true` for at least one element in a collection, `false` otherwise.
@ -12,4 +15,4 @@ const any = (arr, fn = Boolean) => arr.some(fn);
```js
any([0, 1, 2, 0], x => x >= 2); // true
any([0, 0, 1, 0]); // true
```
```

View File

@ -1,4 +1,7 @@
### approximatelyEqual
---
title: approximatelyEqual
tags: math,beginner
---
Checks if two numbers are approximately equal to each other.
@ -11,4 +14,4 @@ const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsi
```js
approximatelyEqual(Math.PI / 2.0, 1.5708); // true
```
```

View File

@ -1,4 +1,7 @@
### arrayToCSV
---
title: arrayToCSV
tags: array,string,utility,intermediate
---
Converts a 2D array to a comma-separated values (CSV) string.
@ -17,4 +20,4 @@ const arrayToCSV = (arr, delimiter = ',') =>
arrayToCSV([['a', 'b'], ['c', 'd']]); // '"a","b"\n"c","d"'
arrayToCSV([['a', 'b'], ['c', 'd']], ';'); // '"a";"b"\n"c";"d"'
arrayToCSV([['a', '"b" great'], ['c', 3.1415]]); // '"a","""b"" great"\n"c",3.1415'
```
```

View File

@ -1,4 +1,7 @@
### arrayToHtmlList
---
title: arrayToHtmlList
tags: browser,array,intermediate
---
Converts the given array elements into `<li>` tags and appends them to the list of the given id.
@ -14,4 +17,4 @@ const arrayToHtmlList = (arr, listID) =>
```js
arrayToHtmlList(['item 1', 'item 2'], 'myListID');
```
```

View File

@ -1,4 +1,7 @@
### ary
---
title: ary
tags: adapter,function,intermediate
---
Creates a function that accepts up to `n` arguments, ignoring any additional arguments.
@ -11,4 +14,4 @@ const ary = (fn, n) => (...args) => fn(...args.slice(0, n));
```js
const firstTwoMax = ary(Math.max, 2);
[[2, 6, 'a'], [8, 4, 6], [10]].map(x => firstTwoMax(...x)); // [6, 8, 10]
```
```

View File

@ -1,4 +1,7 @@
### atob
---
title: atob
tags: node,string,utility,beginner
---
Decodes a string of data which has been encoded using base-64 encoding.
@ -10,4 +13,4 @@ const atob = str => Buffer.from(str, 'base64').toString('binary');
```js
atob('Zm9vYmFy'); // 'foobar'
```
```

View File

@ -1,4 +1,7 @@
### attempt
---
title: attempt
tags: function,intermediate
---
Attempts to invoke a function with the provided arguments, returning either the result or the caught error object.
@ -19,4 +22,4 @@ var elements = attempt(function(selector) {
return document.querySelectorAll(selector);
}, '>_>');
if (elements instanceof Error) elements = []; // elements = []
```
```

View File

@ -1,4 +1,7 @@
### average
---
title: average
tags: math,array,beginner
---
Returns the average of two or more numbers.
@ -11,4 +14,4 @@ const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.leng
```js
average(...[1, 2, 3]); // 2
average(1, 2, 3); // 2
```
```

View File

@ -1,4 +1,7 @@
### averageBy
---
title: averageBy
tags: math,array,function,intermediate
---
Returns the average of an array, after mapping each element to a value using the provided function.
@ -13,4 +16,4 @@ const averageBy = (arr, fn) =>
```js
averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 5
averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 5
```
```

View File

@ -1,4 +1,7 @@
### bifurcate
---
title: bifurcate
tags: array,intermediate
---
Splits values into two groups. If an element in `filter` is truthy, the corresponding element in the collection belongs to the first group; otherwise, it belongs to the second group.
@ -11,4 +14,4 @@ const bifurcate = (arr, filter) =>
```js
bifurcate(['beep', 'boop', 'foo', 'bar'], [true, true, false, true]); // [ ['beep', 'boop', 'bar'], ['foo'] ]
```
```

View File

@ -1,4 +1,7 @@
### bifurcateBy
---
title: bifurcateBy
tags: array,function,intermediate
---
Splits values into two groups according to a predicate function, which specifies which group an element in the input collection belongs to. If the predicate function returns a truthy value, the collection element belongs to the first group; otherwise, it belongs to the second group.
@ -11,4 +14,4 @@ const bifurcateBy = (arr, fn) =>
```js
bifurcateBy(['beep', 'boop', 'foo', 'bar'], x => x[0] === 'b'); // [ ['beep', 'boop', 'bar'], ['foo'] ]
```
```

View File

@ -1,4 +1,7 @@
### bind
---
title: bind
tags: function,object,intermediate
---
Creates a function that invokes `fn` with a given context, optionally adding any additional supplied parameters to the beginning of the arguments.
@ -16,4 +19,4 @@ function greet(greeting, punctuation) {
const freddy = { user: 'fred' };
const freddyBound = bind(greet, freddy);
console.log(freddyBound('hi', '!')); // 'hi fred!'
```
```

View File

@ -1,4 +1,7 @@
### bindAll
---
title: bindAll
tags: object,function,intermediate
---
Binds methods of an object to the object itself, overwriting the existing method.
@ -25,4 +28,4 @@ var view = {
};
bindAll(view, 'click');
jQuery(element).on('click', view.click); // Logs 'clicked docs' when clicked.
```
```

View File

@ -1,4 +1,7 @@
### bindKey
---
title: bindKey
tags: function,object,intermediate
---
Creates a function that invokes the method at a given key of an object, optionally adding any additional supplied parameters to the beginning of the arguments.
@ -19,4 +22,4 @@ const freddy = {
};
const freddyBound = bindKey(freddy, 'greet');
console.log(freddyBound('hi', '!')); // 'hi fred!'
```
```

View File

@ -1,4 +1,7 @@
### binomialCoefficient
---
title: binomialCoefficient
tags: math,intermediate
---
Evaluates the binomial coefficient of two integers `n` and `k`.
@ -23,4 +26,4 @@ const binomialCoefficient = (n, k) => {
```js
binomialCoefficient(8, 2); // 28
```
```

View File

@ -1,4 +1,7 @@
### bottomVisible
---
title: bottomVisible
tags: browser,intermediate
---
Returns `true` if the bottom of the page is visible, `false` otherwise.
@ -12,4 +15,4 @@ const bottomVisible = () =>
```js
bottomVisible(); // true
```
```

View File

@ -1,4 +1,7 @@
### btoa
---
title: btoa
tags: node,string,utility,beginner
---
Creates a base-64 encoded ASCII string from a String object in which each character in the string is treated as a byte of binary data.
@ -10,4 +13,4 @@ const btoa = str => Buffer.from(str, 'binary').toString('base64');
```js
btoa('foobar'); // 'Zm9vYmFy'
```
```

View File

@ -1,4 +1,7 @@
### byteSize
---
title: byteSize
tags: string,beginner
---
Returns the length of a string in bytes.
@ -11,4 +14,4 @@ const byteSize = str => new Blob([str]).size;
```js
byteSize('😀'); // 4
byteSize('Hello World'); // 11
```
```

View File

@ -1,13 +1,16 @@
### call
---
title: call
tags: adapter,function,intermediate
---
Given a key and a set of arguments, call them when given a context. Primarily useful in composition.
Use a closure to call a stored key with stored arguments.
Use a closure to call a stored key with stored arguments.
```js
const call = (key, ...args) => context => context[key](...args);
```
```
```js
Promise.resolve([1, 2, 3])
.then(call('map', x => 2 * x))
@ -16,4 +19,4 @@ const map = call.bind(null, 'map');
Promise.resolve([1, 2, 3])
.then(map(x => 2 * x))
.then(console.log); // [ 2, 4, 6 ]
```
```

View File

@ -1,4 +1,7 @@
### capitalize
---
title: capitalize
tags: string,array,intermediate
---
Capitalizes the first letter of a string.
@ -13,4 +16,4 @@ const capitalize = ([first, ...rest], lowerRest = false) =>
```js
capitalize('fooBar'); // 'FooBar'
capitalize('fooBar', true); // 'Foobar'
```
```

View File

@ -1,4 +1,7 @@
### capitalizeEveryWord
---
title: capitalizeEveryWord
tags: string,regexp,intermediate
---
Capitalizes the first letter of every word in a string.
@ -10,4 +13,4 @@ const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperC
```js
capitalizeEveryWord('hello world!'); // 'Hello World!'
```
```

View File

@ -1,4 +1,7 @@
### castArray
---
title: castArray
tags: utility,array,type,beginner
---
Casts the provided value as an array if it's not one.
@ -11,4 +14,4 @@ const castArray = val => (Array.isArray(val) ? val : [val]);
```js
castArray('foo'); // ['foo']
castArray([1]); // [1]
```
```

View File

@ -1,4 +1,7 @@
### chainAsync
---
title: chainAsync
tags: function,intermediate
---
Chains asynchronous functions.
@ -30,4 +33,4 @@ chainAsync([
console.log('2 second');
}
]);
```
```

View File

@ -1,4 +1,7 @@
### checkProp
---
title: checkProp
tags: function,object,utility,beginner
---
Given a `predicate` function and a `prop` string, this curried function will then take an `object` to inspect by calling the property and passing it to the predicate.
@ -9,22 +12,6 @@ const checkProp = (predicate, prop) => obj => !!predicate(obj[prop]);
```
```js
const lengthIs4 = checkProp(l => l === 4, 'length');
lengthIs4([]); // false
lengthIs4([1,2,3,4]); // true
@ -42,4 +29,4 @@ const noLength(l => l === undefined, 'length');
noLength([]); // false
noLength({}); // true
noLength(new Set()); // true
```
```

View File

@ -1,4 +1,7 @@
### chunk
---
title: chunk
tags: array,intermediate
---
Chunks an array into smaller arrays of a specified size.
@ -15,4 +18,4 @@ const chunk = (arr, size) =>
```js
chunk([1, 2, 3, 4, 5], 2); // [[1,2],[3,4],[5]]
```
```

View File

@ -1,4 +1,7 @@
### clampNumber
---
title: clampNumber
tags: math,beginner
---
Clamps `num` within the inclusive range specified by the boundary values `a` and `b`.
@ -12,4 +15,4 @@ const clampNumber = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.
```js
clampNumber(2, 3, 5); // 3
clampNumber(1, -1, -5); // -1
```
```

View File

@ -1,4 +1,7 @@
### cloneRegExp
---
title: cloneRegExp
tags: utility,regexp,intermediate
---
Clones a regular expression.
@ -11,4 +14,4 @@ const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags);
```js
const regExp = /lorem ipsum/gi;
const regExp2 = cloneRegExp(regExp); // /lorem ipsum/gi
```
```

View File

@ -1,4 +1,7 @@
### coalesce
---
title: coalesce
tags: utility,beginner
---
Returns the first non-null/undefined argument.
@ -10,4 +13,4 @@ const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_));
```js
coalesce(null, undefined, '', NaN, 'Waldo'); // ""
```
```

View File

@ -1,4 +1,7 @@
### coalesceFactory
---
title: coalesceFactory
tags: utility,intermediate
---
Returns a customized coalesce function that returns the first argument that returns `true` from the provided argument validation function.
@ -11,4 +14,4 @@ const coalesceFactory = valid => (...args) => args.find(valid);
```js
const customCoalesce = coalesceFactory(_ => ![null, undefined, '', NaN].includes(_));
customCoalesce(undefined, null, NaN, '', 'Waldo'); // "Waldo"
```
```

View File

@ -1,17 +1,20 @@
### collectInto
---
title: collectInto
tags: adapter,function,array,intermediate
---
Changes a function that accepts an array into a variadic function.
Given a function, return a closure that collects all inputs into an array-accepting function.
Given a function, return a closure that collects all inputs into an array-accepting function.
```js
const collectInto = fn => (...args) => fn(args);
```
```
```js
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));
Pall(p1, p2, p3).then(console.log); // [1, 2, 3] (after about 2 seconds)
```
```

View File

@ -1,4 +1,7 @@
### colorize
---
title: colorize
tags: node,utility,string,intermediate
---
Add special characters to text to print in color in the console (combined with `console.log()`).
@ -30,4 +33,4 @@ const colorize = (...args) => ({
console.log(colorize('foo').red); // 'foo' (red letters)
console.log(colorize('foo', 'bar').bgBlue); // 'foo bar' (blue background)
console.log(colorize(colorize('foo').yellow, colorize('foo').green).bgWhite); // 'foo bar' (first word in yellow letters, second word in green letters, white background for both)
```
```

View File

@ -1,4 +1,7 @@
### compact
---
title: compact
tags: array,beginner
---
Removes falsy values from an array.
@ -10,4 +13,4 @@ const compact = arr => arr.filter(Boolean);
```js
compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); // [ 1, 2, 3, 'a', 's', 34 ]
```
```

View File

@ -1,4 +1,7 @@
### compactWhitespace
---
title: compactWhitespace
tags: string,regexp,beginner
---
Returns a string with whitespaces compacted.
@ -11,4 +14,4 @@ const compactWhitespace = str => str.replace(/\s{2,}/g, ' ');
```js
compactWhitespace('Lorem Ipsum'); // 'Lorem Ipsum'
compactWhitespace('Lorem \n Ipsum'); // 'Lorem Ipsum'
```
```

View File

@ -1,4 +1,7 @@
### compose
---
title: compose
tags: function,intermediate
---
Performs right-to-left function composition.
@ -17,4 +20,4 @@ const multiplyAndAdd5 = compose(
multiply
);
multiplyAndAdd5(5, 2); // 15
```
```

View File

@ -1,4 +1,7 @@
### composeRight
---
title: composeRight
tags: function,intermediate
---
Performs left-to-right function composition.
@ -14,4 +17,4 @@ const add = (x, y) => x + y;
const square = x => x * x;
const addAndSquare = composeRight(add, square);
addAndSquare(1, 2); // 9
```
```

View File

@ -1,4 +1,7 @@
### converge
---
title: converge
tags: function,intermediate
---
Accepts a converging function and a list of branching functions and returns a function that applies each branching function to the arguments and the results of the branching functions are passed as arguments to the converging function.
@ -15,4 +18,4 @@ const average = converge((a, b) => a / b, [
arr => arr.length
]);
average([1, 2, 3, 4, 5, 6, 7]); // 4
```
```

View File

@ -1,4 +1,7 @@
### copyToClipboard
---
title: copyToClipboard
tags: browser,string,advanced
---
⚠️ **NOTICE:** The same functionality can be easily implemented by using the new asynchronous Clipboard API, which is still experimental but should be used in the future instead of this snippet. Find out more about it [here](https://github.com/w3c/clipboard-apis/blob/master/explainer.adoc#writing-to-the-clipboard).
@ -33,4 +36,4 @@ const copyToClipboard = str => {
```js
copyToClipboard('Lorem ipsum'); // 'Lorem ipsum' copied to clipboard.
```
```

View File

@ -1,4 +1,7 @@
### countBy
---
title: countBy
tags: array,object,intermediate
---
Groups the elements of an array based on the given function and returns the count of elements in each group.
@ -16,4 +19,4 @@ const countBy = (arr, fn) =>
```js
countBy([6.1, 4.2, 6.3], Math.floor); // {4: 1, 6: 2}
countBy(['one', 'two', 'three'], 'length'); // {3: 2, 5: 1}
```
```

View File

@ -1,4 +1,7 @@
### countOccurrences
---
title: countOccurrences
tags: array,intermediate
---
Counts the occurrences of a value in an array.
@ -10,4 +13,4 @@ const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 :
```js
countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3
```
```

View File

@ -1,4 +1,7 @@
### counter
---
title: counter
tags: browser,advanced
---
Creates a counter with the specified range, step and duration for the specified selector.
@ -24,4 +27,4 @@ const counter = (selector, start, end, step = 1, duration = 2000) => {
```js
counter('#my-id', 1, 1000, 5, 2000); // Creates a 2-second timer for the element with id="my-id"
```
```

View File

@ -1,4 +1,7 @@
### createDirIfNotExists
---
title: createDirIfNotExists
tags: node,beginner
---
Creates a directory, if it does not exist.
@ -11,4 +14,4 @@ const createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : u
```js
createDirIfNotExists('test'); // creates the directory 'test', if it doesn't exist
```
```

View File

@ -1,4 +1,7 @@
### createElement
---
title: createElement
tags: browser,utility,beginner
---
Creates an element from a string (without appending it to the document).
If the given string contains multiple elements, only the first one will be returned.
@ -22,4 +25,4 @@ const el = createElement(
</div>`
);
console.log(el.className); // 'container'
```
```

View File

@ -1,4 +1,7 @@
### createEventHub
---
title: createEventHub
tags: browser,event,advanced
---
Creates a pub/sub ([publishsubscribe](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern)) event hub with `emit`, `on`, and `off` methods.
@ -43,4 +46,4 @@ hub.emit('increment'); // `increment` variable is now 1
// Unsubscribe: stop a specific handler from listening to the 'message' event
hub.off('message', handler);
```
```

View File

@ -1,4 +1,7 @@
### currentURL
---
title: currentURL
tags: browser,url,beginner
---
Returns the current URL.
@ -10,4 +13,4 @@ const currentURL = () => window.location.href;
```js
currentURL(); // 'https://google.com'
```
```

View File

@ -1,4 +1,7 @@
### curry
---
title: curry
tags: function,recursion,intermediate
---
Curries a function.
@ -15,4 +18,4 @@ const curry = (fn, arity = fn.length, ...args) =>
```js
curry(Math.pow)(2)(10); // 1024
curry(Math.min, 3)(10)(50)(2); // 2
```
```

View File

@ -1,4 +1,7 @@
### dayOfYear
---
title: dayOfYear
tags: date,beginner
---
Gets the day of the year from a `Date` object.
@ -12,4 +15,4 @@ const dayOfYear = date =>
```js
dayOfYear(new Date()); // 272
```
```

View File

@ -1,4 +1,7 @@
### debounce
---
title: debounce
tags: function,intermediate
---
Creates a debounced function that delays invoking the provided function until at least `ms` milliseconds have elapsed since the last time it was invoked.
@ -23,4 +26,4 @@ window.addEventListener(
console.log(window.innerHeight);
}, 250)
); // Will log the window dimensions at most every 250ms
```
```

View File

@ -1,4 +1,7 @@
### decapitalize
---
title: decapitalize
tags: string,array,intermediate
---
Decapitalizes the first letter of a string.
@ -13,4 +16,4 @@ const decapitalize = ([first, ...rest], upperRest = false) =>
```js
decapitalize('FooBar'); // 'fooBar'
decapitalize('FooBar', true); // 'fOOBAR'
```
```

View File

@ -1,4 +1,7 @@
### deepClone
---
title: deepClone
tags: object,recursion,intermediate
---
Creates a deep clone of an object.
@ -23,4 +26,4 @@ const deepClone = obj => {
```js
const a = { foo: 'bar', obj: { a: 1, b: 2 } };
const b = deepClone(a); // a !== b, a.obj !== b.obj
```
```

View File

@ -1,4 +1,7 @@
### deepFlatten
---
title: deepFlatten
tags: array,recursion,intermediate
---
Deep flattens an array.
@ -12,4 +15,4 @@ const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFla
```js
deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5]
```
```

View File

@ -1,4 +1,7 @@
### deepFreeze
---
title: deepFreeze
tags: object,recursion,intermediate
---
Deep freezes an object.
@ -19,4 +22,4 @@ const o = deepFreeze([1, [2, 3]]);
o[0] = 3; // not allowed
o[1][0] = 4; // not allowed as well
```
```

View File

@ -1,4 +1,7 @@
### deepGet
---
title: deepGet
tags: object,intermediate
---
Returns the target value in a nested JSON object, based on the `keys` array.
@ -22,4 +25,4 @@ const data = {
};
deepGet(data, ['foo', 'foz', index]); // get 3
deepGet(data, ['foo', 'bar', 'baz', 8, 'foz']); // null
```
```

View File

@ -1,4 +1,7 @@
### deepMapKeys
---
title: deepMapKeys
tags: object,recursion,advanced
---
Deep maps an object keys.
@ -49,4 +52,4 @@ const upperKeysObj = deepMapKeys(obj, key => key.toUpperCase());
}
}
*/
```
```

View File

@ -1,4 +1,7 @@
### defaults
---
title: defaults
tags: object,intermediate
---
Assigns default values for all properties in an object that are `undefined`.
@ -10,4 +13,4 @@ const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj
```js
defaults({ a: 1 }, { b: 2 }, { b: 6 }, { a: 3 }); // { a: 1, b: 2 }
```
```

View File

@ -1,4 +1,7 @@
### defer
---
title: defer
tags: function,intermediate
---
Defers invoking a function until the current call stack has cleared.
@ -16,4 +19,4 @@ defer(console.log, 'a'), console.log('b'); // logs 'b' then 'a'
document.querySelector('#someElement').innerHTML = 'Hello';
longRunningFunction(); // Browser will not update the HTML until this has finished
defer(longRunningFunction); // Browser will update the HTML then run the function
```
```

View File

@ -1,4 +1,7 @@
### degreesToRads
---
title: degreesToRads
tags: math,beginner
---
Converts an angle from degrees to radians.
@ -10,4 +13,4 @@ const degreesToRads = deg => (deg * Math.PI) / 180.0;
```js
degreesToRads(90.0); // ~1.5708
```
```

View File

@ -1,4 +1,7 @@
### delay
---
title: delay
tags: function,intermediate
---
Invokes the provided function after `wait` milliseconds.
@ -17,4 +20,4 @@ delay(
1000,
'later'
); // Logs 'later' after one second.
```
```

View File

@ -1,4 +1,7 @@
### detectDeviceType
---
title: detectDeviceType
tags: browser,intermediate
---
Detects whether the website is being opened in a mobile device or a desktop/laptop.
@ -13,4 +16,4 @@ const detectDeviceType = () =>
```js
detectDeviceType(); // "Mobile" or "Desktop"
```
```

View File

@ -1,4 +1,7 @@
### difference
---
title: difference
tags: array,math,beginner
---
Returns the difference between two arrays.
@ -13,4 +16,4 @@ const difference = (a, b) => {
```js
difference([1, 2, 3], [1, 2, 4]); // [3]
```
```

View File

@ -1,4 +1,7 @@
### differenceBy
---
title: differenceBy
tags: array,function,intermediate
---
Returns the difference between two arrays, after applying the provided function to each array element of both.
@ -14,4 +17,4 @@ const differenceBy = (a, b, fn) => {
```js
differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [1]
differenceBy([{ x: 2 }, { x: 1 }], [{ x: 1 }], v => v.x); // [2]
```
```

View File

@ -1,4 +1,7 @@
### differenceWith
---
title: differenceWith
tags: array,function,intermediate
---
Filters out all values from an array for which the comparator function does not return `true`.
@ -10,4 +13,4 @@ const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => co
```js
differenceWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0], (a, b) => Math.round(a) === Math.round(b)); // [1, 1.2]
```
```

View File

@ -1,4 +1,7 @@
### dig
---
title: dig
tags: object,recursion,intermediate
---
Returns the target value in a nested JSON object, based on the given key.
@ -25,4 +28,4 @@ const data = {
};
dig(data, 'level3'); // 'some data'
dig(data, 'level4'); // undefined
```
```

View File

@ -1,4 +1,7 @@
### digitize
---
title: digitize
tags: math,array,beginner
---
Converts a number to an array of digits.
@ -11,4 +14,4 @@ const digitize = n => [...`${n}`].map(i => parseInt(i));
```js
digitize(123); // [1, 2, 3]
```
```

View File

@ -1,4 +1,7 @@
### distance
---
title: distance
tags: math,beginner
---
Returns the distance between two points.
@ -10,4 +13,4 @@ const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
```js
distance(1, 1, 2, 3); // 2.23606797749979
```
```

View File

@ -1,4 +1,7 @@
### drop
---
title: drop
tags: array,beginner
---
Returns a new array with `n` elements removed from the left.
@ -12,4 +15,4 @@ const drop = (arr, n = 1) => arr.slice(n);
drop([1, 2, 3]); // [2,3]
drop([1, 2, 3], 2); // [3]
drop([1, 2, 3], 42); // []
```
```

View File

@ -1,4 +1,7 @@
### dropRight
---
title: dropRight
tags: array,beginner
---
Returns a new array with `n` elements removed from the right.
@ -12,4 +15,4 @@ const dropRight = (arr, n = 1) => arr.slice(0, -n);
dropRight([1, 2, 3]); // [1,2]
dropRight([1, 2, 3], 2); // [1]
dropRight([1, 2, 3], 42); // []
```
```

View File

@ -1,4 +1,7 @@
### dropRightWhile
---
title: dropRightWhile
tags: array,function,intermediate
---
Removes elements from the end of an array until the passed function returns `true`. Returns the remaining elements in the array.
@ -15,4 +18,4 @@ const dropRightWhile = (arr, func) => {
```js
dropRightWhile([1, 2, 3, 4], n => n < 3); // [1, 2]
```
```

View File

@ -1,4 +1,7 @@
### dropWhile
---
title: dropWhile
tags: array,function,intermediate
---
Removes elements in an array until the passed function returns `true`. Returns the remaining elements in the array.
@ -14,4 +17,4 @@ const dropWhile = (arr, func) => {
```js
dropWhile([1, 2, 3, 4], n => n >= 3); // [3,4]
```
```

View File

@ -1,4 +1,7 @@
### elementContains
---
title: elementContains
tags: browser,intermediate
---
Returns `true` if the `parent` element contains the `child` element, `false` otherwise.
@ -11,4 +14,4 @@ const elementContains = (parent, child) => parent !== child && parent.contains(c
```js
elementContains(document.querySelector('head'), document.querySelector('title')); // true
elementContains(document.querySelector('body'), document.querySelector('body')); // false
```
```

View File

@ -1,4 +1,7 @@
### elementIsVisibleInViewport
---
title: elementIsVisibleInViewport
tags: browser,advanced
---
Returns `true` if the element specified is visible in the viewport, `false` otherwise.
@ -22,4 +25,4 @@ const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
// e.g. 100x100 viewport and a 10x10px element at position {top: -1, left: 0, bottom: 9, right: 10}
elementIsVisibleInViewport(el); // false - (not fully visible)
elementIsVisibleInViewport(el, true); // true - (partially visible)
```
```

View File

@ -1,4 +1,7 @@
### elo
---
title: elo
tags: math,array,advanced
---
Computes the new ratings between two or more opponents using the [Elo rating system](https://en.wikipedia.org/wiki/Elo_rating_system). It takes an array
of pre-ratings and returns an array containing post-ratings.
@ -39,4 +42,4 @@ For teams, each rating can adjusted based on own team's average rating vs.
average rating of opposing team, with the score being added to their
own individual rating by supplying it as the third argument.
*/
```
```

View File

@ -1,4 +1,7 @@
### equals
---
title: equals
tags: object,array,type,advanced
---
Performs a deep comparison between two values to determine if they are equivalent.
@ -21,4 +24,4 @@ const equals = (a, b) => {
```js
equals({ a: [2, { e: 3 }], b: [4], c: 'foo' }, { a: [2, { e: 3 }], b: [4], c: 'foo' }); // true
```
```

View File

@ -1,4 +1,7 @@
### escapeHTML
---
title: escapeHTML
tags: string,browser,regexp,intermediate
---
Escapes a string for use in HTML.
@ -21,4 +24,4 @@ const escapeHTML = str =>
```js
escapeHTML('<a href="#">Me & you</a>'); // '&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;'
```
```

View File

@ -1,4 +1,7 @@
### escapeRegExp
---
title: escapeRegExp
tags: string,regexp,intermediate
---
Escapes a string to use in a regular expression.
@ -10,4 +13,4 @@ const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
```js
escapeRegExp('(test)'); // \\(test\\)
```
```

View File

@ -1,4 +1,7 @@
### everyNth
---
title: everyNth
tags: array,beginner
---
Returns every nth element in an array.
@ -10,4 +13,4 @@ const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);
```js
everyNth([1, 2, 3, 4, 5, 6], 2); // [ 2, 4, 6 ]
```
```

View File

@ -1,4 +1,7 @@
### extendHex
---
title: extendHex
tags: utility,string,intermediate
---
Extends a 3-digit color code to a 6-digit color code.
@ -18,4 +21,4 @@ const extendHex = shortHex =>
```js
extendHex('#03f'); // '#0033ff'
extendHex('05a'); // '#0055aa'
```
```

View File

@ -1,4 +1,7 @@
### factorial
---
title: factorial
tags: math,recursion,beginner
---
Calculates the factorial of a number.
@ -20,4 +23,4 @@ const factorial = n =>
```js
factorial(6); // 720
```
```

View File

@ -1,4 +1,7 @@
### fibonacci
---
title: fibonacci
tags: math,array,beginner
---
Generates an array, containing the Fibonacci sequence, up until the nth term.
@ -15,4 +18,4 @@ const fibonacci = n =>
```js
fibonacci(6); // [0, 1, 1, 2, 3, 5]
```
```

View File

@ -1,13 +1,16 @@
### filterFalsy
---
title: filterFalsy
tags: array,beginner
---
Filters out the falsy values in an array.
Use `Array.prototype.filter()` to get an array containing only truthy values.
Use `Array.prototype.filter()` to get an array containing only truthy values.
```js
const filterFalsy = arr => arr.filter(Boolean);
```
```
```js
filterFalsy(['', true, {}, false, 'sample', 1, 0]); // [true, {}, 'sample', 1]
```
```

View File

@ -1,4 +1,7 @@
### filterNonUnique
---
title: filterNonUnique
tags: array,beginner
---
Filters out the non-unique values in an array.
@ -10,4 +13,4 @@ const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexO
```js
filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1, 3, 5]
```
```

View File

@ -1,4 +1,7 @@
### filterNonUniqueBy
---
title: filterNonUniqueBy
tags: array,function,intermediate
---
Filters out the non-unique values in an array, based on a provided comparator function.
@ -21,4 +24,4 @@ filterNonUniqueBy(
],
(a, b) => a.id == b.id
); // [ { id: 2, value: 'c' } ]
```
```

View File

@ -1,4 +1,7 @@
### findKey
---
title: findKey
tags: object,function,intermediate
---
Returns the first key that satisfies the provided testing function. Otherwise `undefined` is returned.
@ -17,4 +20,4 @@ findKey(
},
o => o['active']
); // 'barney'
```
```

View File

@ -1,4 +1,7 @@
### findLast
---
title: findLast
tags: array,beginner
---
Returns the last element for which the provided function returns a truthy value.
@ -10,4 +13,4 @@ const findLast = (arr, fn) => arr.filter(fn).pop();
```js
findLast([1, 2, 3, 4], n => n % 2 === 1); // 3
```
```

View File

@ -1,4 +1,7 @@
### findLastIndex
---
title: findLastIndex
tags: array,function,intermediate
---
Returns the index of the last element for which the provided function returns a truthy value.
@ -17,4 +20,4 @@ const findLastIndex = (arr, fn) =>
```js
findLastIndex([1, 2, 3, 4], n => n % 2 === 1); // 2 (index of the value 3)
findLastIndex([1, 2, 3, 4], n => n === 5); // -1 (default value when not found)
```
```

View File

@ -1,4 +1,7 @@
### findLastKey
---
title: findLastKey
tags: object,function,intermediate
---
Returns the last key that satisfies the provided testing function.
Otherwise `undefined` is returned.
@ -22,4 +25,4 @@ findLastKey(
},
o => o['active']
); // 'pebbles'
```
```

View File

@ -1,4 +1,7 @@
### flatten
---
title: flatten
tags: array,intermediate
---
Flattens an array up to the specified depth.
@ -15,4 +18,4 @@ const flatten = (arr, depth = 1) =>
```js
flatten([1, [2], 3, 4]); // [1, 2, 3, 4]
flatten([1, [2, [3, [4, 5], 6], 7], 8], 2); // [1, 2, 3, [4, 5], 6, 7, 8]
```
```

Some files were not shown because too many files have changed in this diff Show More