Added linting, processed current snippets
This commit is contained in:
75
README.md
75
README.md
@ -51,7 +51,7 @@
|
|||||||
* [Random integer in range](#random-integer-in-range)
|
* [Random integer in range](#random-integer-in-range)
|
||||||
* [Random number in range](#random-number-in-range)
|
* [Random number in range](#random-number-in-range)
|
||||||
* [Randomize order of array](#randomize-order-of-array)
|
* [Randomize order of array](#randomize-order-of-array)
|
||||||
* [Redirect to url](#redirect-to-url)
|
* [Redirect to URL](#redirect-to-url)
|
||||||
* [Reverse a string](#reverse-a-string)
|
* [Reverse a string](#reverse-a-string)
|
||||||
* [RGB to hexadecimal](#rgb-to-hexadecimal)
|
* [RGB to hexadecimal](#rgb-to-hexadecimal)
|
||||||
* [Run promises in series](#run-promises-in-series)
|
* [Run promises in series](#run-promises-in-series)
|
||||||
@ -78,10 +78,10 @@ Base cases are for string `length` equal to `2` or `1`.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const anagrams = str => {
|
const anagrams = str => {
|
||||||
if(str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];
|
if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];
|
||||||
return str.split('').reduce( (acc, letter, i) =>
|
return str.split('').reduce((acc, letter, i) =>
|
||||||
acc.concat(anagrams(str.slice(0, i) + str.slice(i + 1)).map( val => letter + val )), []);
|
acc.concat(anagrams(str.slice(0, i) + str.slice(i + 1)).map(val => letter + val)), []);
|
||||||
}
|
};
|
||||||
// anagrams('abc') -> ['abc','acb','bac','bca','cab','cba']
|
// anagrams('abc') -> ['abc','acb','bac','bca','cab','cba']
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -90,8 +90,7 @@ const anagrams = str => {
|
|||||||
Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array.
|
Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const average = arr =>
|
const average = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length;
|
||||||
arr.reduce( (acc , val) => acc + val, 0) / arr.length;
|
|
||||||
// average([1,2,3]) -> 2
|
// average([1,2,3]) -> 2
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -100,7 +99,7 @@ const average = arr =>
|
|||||||
Use `scrollY`, `scrollHeight` and `clientHeight` to determine if the bottom of the page is visible.
|
Use `scrollY`, `scrollHeight` and `clientHeight` to determine if the bottom of the page is visible.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const bottomVisible = _ =>
|
const bottomVisible = _ =>
|
||||||
document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight || document.documentElement.clientHeight;
|
document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight || document.documentElement.clientHeight;
|
||||||
// bottomVisible() -> true
|
// bottomVisible() -> true
|
||||||
```
|
```
|
||||||
@ -121,7 +120,7 @@ Omit the `lowerRest` parameter to keep the rest of the string intact, or set it
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const capitalize = (str, lowerRest = false) =>
|
const capitalize = (str, lowerRest = false) =>
|
||||||
str.slice(0, 1).toUpperCase() + (lowerRest? str.slice(1).toLowerCase() : str.slice(1));
|
str.slice(0, 1).toUpperCase() + (lowerRest ? str.slice(1).toLowerCase() : str.slice(1));
|
||||||
// capitalize('myName', true) -> 'Myname'
|
// capitalize('myName', true) -> 'Myname'
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -130,7 +129,7 @@ const capitalize = (str, lowerRest = false) =>
|
|||||||
Loop through an array of functions containing asynchronous events, calling `next` when each asynchronous event has completed.
|
Loop through an array of functions containing asynchronous events, calling `next` when each asynchronous event has completed.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const chainAsync = fns => { let curr = 0; const next = () => fns[curr++](next); next(); }
|
const chainAsync = fns => { let curr = 0; const next = () => fns[curr++](next); next(); };
|
||||||
/*
|
/*
|
||||||
chainAsync([
|
chainAsync([
|
||||||
next => { console.log('0 seconds'); setTimeout(next, 1000); },
|
next => { console.log('0 seconds'); setTimeout(next, 1000); },
|
||||||
@ -159,7 +158,7 @@ If the original array can't be split evenly, the final chunk will contain the re
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const chunk = (arr, size) =>
|
const chunk = (arr, size) =>
|
||||||
Array.apply(null, {length: Math.ceil(arr.length/size)}).map((v, i) => arr.slice(i*size, i*size+size));
|
Array.apply(null, {length: Math.ceil(arr.length / size)}).map((v, i) => arr.slice(i * size, i * size + size));
|
||||||
// chunk([1,2,3,4,5], 2) -> [[1,2],[3,4],5]
|
// chunk([1,2,3,4,5], 2) -> [[1,2],[3,4],5]
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -207,7 +206,7 @@ Use `Array.reduce()` to get all elements that are not arrays, flatten each eleme
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const deepFlatten = arr =>
|
const deepFlatten = arr =>
|
||||||
arr.reduce( (a, v) => a.concat( Array.isArray(v) ? deepFlatten(v) : v ), []);
|
arr.reduce((a, v) => a.concat(Array.isArray(v) ? deepFlatten(v) : v), []);
|
||||||
// deepFlatten([1,[2],[[3],4],5]) -> [1,2,3,4,5]
|
// deepFlatten([1,[2],[[3],4],5]) -> [1,2,3,4,5]
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -274,8 +273,8 @@ Create an empty array of the specific length, initializing the first two values
|
|||||||
Use `Array.reduce()` to add values into the array, using the sum of the last two values, except for the first two.
|
Use `Array.reduce()` to add values into the array, using the sum of the last two values, except for the first two.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const fibonacci = n =>
|
const fibonacci = n =>
|
||||||
Array(n).fill(0).reduce((acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),[]);
|
Array(n).fill(0).reduce((acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), []);
|
||||||
// fibonacci(5) -> [0,1,1,2,3]
|
// fibonacci(5) -> [0,1,1,2,3]
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -293,7 +292,7 @@ const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexO
|
|||||||
Use `Array.reduce()` to get all elements inside the array and `concat()` to flatten them.
|
Use `Array.reduce()` to get all elements inside the array and `concat()` to flatten them.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const flatten = arr => arr.reduce( (a, v) => a.concat(v), []);
|
const flatten = arr => arr.reduce((a, v) => a.concat(v), []);
|
||||||
// flatten([1,[2],3,4]) -> [1,2,3,4]
|
// flatten([1,[2],3,4]) -> [1,2,3,4]
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -321,7 +320,7 @@ Returns lower-cased constructor name of value, "undefined" or "null" if value is
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const getType = v =>
|
const getType = v =>
|
||||||
v === undefined ? "undefined" : v === null ? "null" : v.constructor.name.toLowerCase();
|
v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
|
||||||
// getType(new Set([1,2,3])) -> "set"
|
// getType(new Set([1,2,3])) -> "set"
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -332,8 +331,8 @@ You can omit `el` to use a default value of `window`.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const getScrollPos = (el = window) =>
|
const getScrollPos = (el = window) =>
|
||||||
( {x: (el.pageXOffset !== undefined) ? el.pageXOffset : el.scrollLeft,
|
({x: (el.pageXOffset !== undefined) ? el.pageXOffset : el.scrollLeft,
|
||||||
y: (el.pageYOffset !== undefined) ? el.pageYOffset : el.scrollTop} );
|
y: (el.pageYOffset !== undefined) ? el.pageYOffset : el.scrollTop});
|
||||||
// getScrollPos() -> {x: 0, y: 200}
|
// getScrollPos() -> {x: 0, y: 200}
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -344,7 +343,7 @@ 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`.
|
Otherwise, return the GCD of `y` and the remainder of the division `x/y`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const gcd = (x , y) => !y ? x : gcd(y, x % y);
|
const gcd = (x, y) => !y ? x : gcd(y, x % y);
|
||||||
// gcd (8, 36) -> 4
|
// gcd (8, 36) -> 4
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -355,7 +354,7 @@ Count and return the number of `1`s in the string, using `match(/1/g)`.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const hammingDistance = (num1, num2) =>
|
const hammingDistance = (num1, num2) =>
|
||||||
((num1^num2).toString(2).match(/1/g) || '').length;
|
((num1 ^ num2).toString(2).match(/1/g) || '').length;
|
||||||
// hammingDistance(2,3) -> 1
|
// hammingDistance(2,3) -> 1
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -373,7 +372,7 @@ const head = arr => arr[0];
|
|||||||
Return `arr.slice(0,-1)`.
|
Return `arr.slice(0,-1)`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const initial = arr => arr.slice(0,-1);
|
const initial = arr => arr.slice(0, -1);
|
||||||
// initial([1,2,3]) -> [1,2]
|
// initial([1,2,3]) -> [1,2]
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -384,7 +383,7 @@ You can omit `start` to use a default value of `0`.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const initializeArrayRange = (end, start = 0) =>
|
const initializeArrayRange = (end, start = 0) =>
|
||||||
Array.apply(null, Array(end-start)).map( (v,i) => i + start );
|
Array.apply(null, Array(end - start)).map((v, i) => i + start);
|
||||||
// initializeArrayRange(5) -> [0,1,2,3,4]
|
// initializeArrayRange(5) -> [0,1,2,3,4]
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -417,7 +416,7 @@ const timeTaken = callback => {
|
|||||||
const t0 = performance.now(), r = callback();
|
const t0 = performance.now(), r = callback();
|
||||||
console.log(performance.now() - t0);
|
console.log(performance.now() - t0);
|
||||||
return r;
|
return r;
|
||||||
}
|
};
|
||||||
// timeTaken(() => Math.pow(2, 10)) -> 1024 (0.010000000009313226 logged in console)
|
// timeTaken(() => Math.pow(2, 10)) -> 1024 (0.010000000009313226 logged in console)
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -428,9 +427,9 @@ Return the number at the midpoint if `length` is odd, otherwise the average of t
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const median = arr => {
|
const median = arr => {
|
||||||
const mid = Math.floor(arr.length / 2), nums = arr.sort((a,b) => a - b);
|
const mid = Math.floor(arr.length / 2), nums = arr.sort((a, b) => a - b);
|
||||||
return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
|
return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
|
||||||
}
|
};
|
||||||
// median([5,6,50,1,-5]) -> 5
|
// median([5,6,50,1,-5]) -> 5
|
||||||
// median([0,10,-2,7]) -> 3.5
|
// median([0,10,-2,7]) -> 3.5
|
||||||
```
|
```
|
||||||
@ -440,7 +439,7 @@ const median = arr => {
|
|||||||
Use `Array.reduce()` to create and combine key-value pairs.
|
Use `Array.reduce()` to create and combine key-value pairs.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const objectFromPairs = arr => arr.reduce((a,v) => (a[v[0]] = v[1], a), {});
|
const objectFromPairs = arr => arr.reduce((a, v) => (a[v[0]] = v[1], a), {});
|
||||||
// objectFromPairs([['a',1],['b',2]]) -> {a: 1, b: 2}
|
// objectFromPairs([['a',1],['b',2]]) -> {a: 1, b: 2}
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -470,7 +469,7 @@ Use `Array.reduce()` combined with `Array.map()` to iterate over elements and co
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const powerset = arr =>
|
const powerset = arr =>
|
||||||
arr.reduce( (a,v) => a.concat(a.map( r => [v].concat(r) )), [[]]);
|
arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]);
|
||||||
// powerset([1,2]) -> [[], [1], [2], [2,1]]
|
// powerset([1,2]) -> [[], [1], [2], [2,1]]
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -515,7 +514,7 @@ const randomInRange = (min, max) => Math.random() * (max - min) + min;
|
|||||||
Use `Array.sort()` to reorder elements, utilizing `Math.random()` to randomize the sorting.
|
Use `Array.sort()` to reorder elements, utilizing `Math.random()` to randomize the sorting.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const randomizeOrder = arr => arr.sort( (a,b) => Math.random() >= 0.5 ? -1 : 1);
|
const randomizeOrder = arr => arr.sort((a, b) => Math.random() >= 0.5 ? -1 : 1);
|
||||||
// randomizeOrder([1,2,3]) -> [1,3,2]
|
// randomizeOrder([1,2,3]) -> [1,3,2]
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -567,11 +566,11 @@ Scroll by a fraction of the distance from top. Use `window.requestAnimationFrame
|
|||||||
```js
|
```js
|
||||||
const scrollToTop = _ => {
|
const scrollToTop = _ => {
|
||||||
const c = document.documentElement.scrollTop || document.body.scrollTop;
|
const c = document.documentElement.scrollTop || document.body.scrollTop;
|
||||||
if(c > 0) {
|
if (c > 0) {
|
||||||
window.requestAnimationFrame(scrollToTop);
|
window.requestAnimationFrame(scrollToTop);
|
||||||
window.scrollTo(0, c - c/8);
|
window.scrollTo(0, c - c / 8);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
// scrollToTop()
|
// scrollToTop()
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -583,8 +582,8 @@ Use `Array.sort()` to sort the elements of the original array based on the rando
|
|||||||
```js
|
```js
|
||||||
const shuffle = arr => {
|
const shuffle = arr => {
|
||||||
let r = arr.map(Math.random);
|
let r = arr.map(Math.random);
|
||||||
return arr.sort((a,b) => r[a] - r[b]);
|
return arr.sort((a, b) => r[a] - r[b]);
|
||||||
}
|
};
|
||||||
// shuffle([1,2,3]) -> [2, 1, 3]
|
// shuffle([1,2,3]) -> [2, 1, 3]
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -603,7 +602,7 @@ Split the string using `split('')`, `Array.sort()` utilizing `localeCompare()`,
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const sortCharactersInString = str =>
|
const sortCharactersInString = str =>
|
||||||
str.split('').sort( (a,b) => a.localeCompare(b) ).join('');
|
str.split('').sort((a, b) => a.localeCompare(b)).join('');
|
||||||
// sortCharactersInString('cabbage') -> 'aabbceg'
|
// sortCharactersInString('cabbage') -> 'aabbceg'
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -612,7 +611,7 @@ const sortCharactersInString = str =>
|
|||||||
Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`.
|
Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const sum = arr => arr.reduce( (acc , val) => acc + val, 0);
|
const sum = arr => arr.reduce((acc, val) => acc + val, 0);
|
||||||
// sum([1,2,3,4]) -> 10
|
// sum([1,2,3,4]) -> 10
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -642,7 +641,7 @@ Return the string truncated to the desired length, with `...` appended to the en
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const truncate = (str, num) =>
|
const truncate = (str, num) =>
|
||||||
str.length > num ? str.slice(0, num > 3 ? num-3 : num) + '...' : str;
|
str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str;
|
||||||
// truncate('boomerang', 7) -> 'boom...'
|
// truncate('boomerang', 7) -> 'boom...'
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -663,7 +662,7 @@ Pass `location.search` as the argument to apply to the current `url`.
|
|||||||
```js
|
```js
|
||||||
const getUrlParameters = url =>
|
const getUrlParameters = url =>
|
||||||
url.match(/([^?=&]+)(=([^&]*))?/g).reduce(
|
url.match(/([^?=&]+)(=([^&]*))?/g).reduce(
|
||||||
(a,v) => (a[v.slice(0,v.indexOf('='))] = v.slice(v.indexOf('=')+1), a), {}
|
(a, v) => (a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1), a), {}
|
||||||
);
|
);
|
||||||
// getUrlParameters('http://url.com/page?name=Adam&surname=Smith') -> {name: 'Adam', surname: 'Smith'}
|
// getUrlParameters('http://url.com/page?name=Adam&surname=Smith') -> {name: 'Adam', surname: 'Smith'}
|
||||||
```
|
```
|
||||||
@ -674,7 +673,7 @@ Use `crypto` API to generate a UUID, compliant with [RFC4122](https://www.ietf.o
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const uuid = _ =>
|
const uuid = _ =>
|
||||||
( [1e7]+-1e3+-4e3+-8e3+-1e11 ).replace( /[018]/g, c =>
|
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
|
||||||
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
|
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
|
||||||
);
|
);
|
||||||
// uuid() -> '7982fcfe-5721-4632-bede-6000885be57d'
|
// uuid() -> '7982fcfe-5721-4632-bede-6000885be57d'
|
||||||
|
|||||||
3
currentSnippet.js
Normal file
3
currentSnippet.js
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
|
||||||
|
const valueOrDefault = (value, d) => value || d;
|
||||||
|
// valueOrDefault(NaN, 30) -> 30
|
||||||
1421
package-lock.json
generated
1421
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -4,7 +4,8 @@
|
|||||||
"fs-extra": "^4.0.2",
|
"fs-extra": "^4.0.2",
|
||||||
"live-server": "^1.2.0",
|
"live-server": "^1.2.0",
|
||||||
"markdown-it": "^8.4.0",
|
"markdown-it": "^8.4.0",
|
||||||
"nodemon": "^1.12.1"
|
"nodemon": "^1.12.1",
|
||||||
|
"semistandard": "^11.0.0"
|
||||||
},
|
},
|
||||||
"name": "30-seconds-of-code",
|
"name": "30-seconds-of-code",
|
||||||
"description": "A collection of useful Javascript snippets.",
|
"description": "A collection of useful Javascript snippets.",
|
||||||
@ -13,6 +14,7 @@
|
|||||||
"devDependencies": {},
|
"devDependencies": {},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build-list": "node ./scripts/builder.js",
|
"build-list": "node ./scripts/builder.js",
|
||||||
|
"lint": "node ./scripts/lintSnippet.js",
|
||||||
"start": "concurrently --kill-others \"nodemon -e js,md -i README.md -x \\\"npm run build-list\\\"\" \"live-server ./build\""
|
"start": "concurrently --kill-others \"nodemon -e js,md -i README.md -x \\\"npm run build-list\\\"\" \"live-server ./build\""
|
||||||
},
|
},
|
||||||
"repository": {
|
"repository": {
|
||||||
|
|||||||
@ -6,6 +6,8 @@ var staticPartsPath = './static-parts';
|
|||||||
|
|
||||||
var snippets = {}, startPart = '', endPart = '', output = '';
|
var snippets = {}, startPart = '', endPart = '', output = '';
|
||||||
|
|
||||||
|
console.time('Builder');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
var snippetFilenames = fs.readdirSync(snippetsPath);
|
var snippetFilenames = fs.readdirSync(snippetsPath);
|
||||||
snippetFilenames.sort((a, b) => {
|
snippetFilenames.sort((a, b) => {
|
||||||
@ -51,3 +53,5 @@ catch (err){
|
|||||||
console.log('Error during README generation: '+err);
|
console.log('Error during README generation: '+err);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
console.timeEnd('Builder');
|
||||||
|
|||||||
31
scripts/lintSnippet.js
Normal file
31
scripts/lintSnippet.js
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
var fs = require('fs-extra');
|
||||||
|
var cp = require('child_process');
|
||||||
|
var path = require('path');
|
||||||
|
|
||||||
|
var snippetsPath = './snippets';
|
||||||
|
var snippetFilename = '';
|
||||||
|
|
||||||
|
console.time('Linter');
|
||||||
|
|
||||||
|
if(process.argv.length < 3){
|
||||||
|
console.log('Please specify the filename of a snippet to be linted.');
|
||||||
|
console.log('Example usage: npm run lint "snippet-file.md"');
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
snippetFilename = process.argv[2];
|
||||||
|
let snippetData = fs.readFileSync(path.join(snippetsPath,snippetFilename),'utf8');
|
||||||
|
try {
|
||||||
|
let originalCode = snippetData.slice(snippetData.indexOf('```js')+5,snippetData.lastIndexOf('```'));
|
||||||
|
fs.writeFileSync('currentSnippet.js',`${originalCode}`);
|
||||||
|
cp.exec('semistandard "currentSnippet.js" --fix',{},(error, stdOut, stdErr) => {
|
||||||
|
let lintedCode = fs.readFileSync('currentSnippet.js','utf8');
|
||||||
|
fs.writeFile(path.join(snippetsPath,snippetFilename), `${snippetData.slice(0, snippetData.indexOf('```js')+5)+lintedCode+'```\n'}`);
|
||||||
|
console.timeEnd('Linter');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (err){
|
||||||
|
console.log('Error during snippet loading: '+err);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
242
semi-snippets.js
Normal file
242
semi-snippets.js
Normal file
@ -0,0 +1,242 @@
|
|||||||
|
|
||||||
|
const anagrams = str => {
|
||||||
|
if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];
|
||||||
|
return str.split('').reduce((acc, letter, i) =>
|
||||||
|
acc.concat(anagrams(str.slice(0, i) + str.slice(i + 1)).map(val => letter + val)), []);
|
||||||
|
};
|
||||||
|
// anagrams('abc') -> ['abc','acb','bac','bca','cab','cba']
|
||||||
|
|
||||||
|
const average = arr =>
|
||||||
|
arr.reduce((acc, val) => acc + val, 0) / arr.length;
|
||||||
|
// average([1,2,3]) -> 2
|
||||||
|
|
||||||
|
const bottomVisible = _ =>
|
||||||
|
document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight || document.documentElement.clientHeight;
|
||||||
|
// bottomVisible() -> true
|
||||||
|
|
||||||
|
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
|
||||||
|
// capitalizeEveryWord('hello world!') -> 'Hello World!'
|
||||||
|
|
||||||
|
const capitalize = (str, lowerRest = false) =>
|
||||||
|
str.slice(0, 1).toUpperCase() + (lowerRest ? str.slice(1).toLowerCase() : str.slice(1));
|
||||||
|
// capitalize('myName', true) -> 'Myname'
|
||||||
|
|
||||||
|
const chainAsync = fns => { let curr = 0; const next = () => fns[curr++](next); next(); };
|
||||||
|
/*
|
||||||
|
chainAsync([
|
||||||
|
next => { console.log('0 seconds'); setTimeout(next, 1000); },
|
||||||
|
next => { console.log('1 second'); setTimeout(next, 1000); },
|
||||||
|
next => { console.log('2 seconds'); }
|
||||||
|
])
|
||||||
|
*/
|
||||||
|
|
||||||
|
const palindrome = str =>
|
||||||
|
str.toLowerCase().replace(/[\W_]/g, '').split('').reverse().join('') === str.toLowerCase().replace(/[\W_]/g, '');
|
||||||
|
// palindrome('taco cat') -> true
|
||||||
|
|
||||||
|
const chunk = (arr, size) =>
|
||||||
|
Array.apply(null, {length: Math.ceil(arr.length / size)}).map((v, i) => arr.slice(i * size, i * size + size));
|
||||||
|
// chunk([1,2,3,4,5], 2) -> [[1,2],[3,4],5]
|
||||||
|
|
||||||
|
const countOccurrences = (arr, value) => arr.reduce((a, v) => v === value ? a + 1 : a + 0, 0);
|
||||||
|
// countOccurrences([1,1,2,1,2,3], 1) -> 3
|
||||||
|
|
||||||
|
const currentUrl = _ => window.location.href;
|
||||||
|
// currentUrl() -> 'https://google.com'
|
||||||
|
|
||||||
|
const curry = (f, arity = f.length, next) =>
|
||||||
|
(next = prevArgs =>
|
||||||
|
nextArg => {
|
||||||
|
const args = [ ...prevArgs, nextArg ];
|
||||||
|
return args.length >= arity ? f(...args) : next(args);
|
||||||
|
}
|
||||||
|
)([]);
|
||||||
|
// curry(Math.pow)(2)(10) -> 1024
|
||||||
|
// curry(Math.min, 3)(10)(50)(2) -> 2
|
||||||
|
|
||||||
|
const deepFlatten = arr =>
|
||||||
|
arr.reduce((a, v) => a.concat(Array.isArray(v) ? deepFlatten(v) : v), []);
|
||||||
|
// deepFlatten([1,[2],[[3],4],5]) -> [1,2,3,4,5]
|
||||||
|
|
||||||
|
const difference = (arr, values) => arr.filter(v => !values.includes(v));
|
||||||
|
// difference([1,2,3], [1,2]) -> [3]
|
||||||
|
|
||||||
|
const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
|
||||||
|
// distance(1,1, 2,3) -> 2.23606797749979
|
||||||
|
|
||||||
|
const isDivisible = (dividend, divisor) => dividend % divisor === 0;
|
||||||
|
// isDivisible(6,3) -> true
|
||||||
|
|
||||||
|
const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||||
|
// escapeRegExp('(test)') -> \\(test\\)
|
||||||
|
|
||||||
|
const isEven = num => Math.abs(num) % 2 === 0;
|
||||||
|
// isEven(3) -> false
|
||||||
|
|
||||||
|
const factorial = n => n <= 1 ? 1 : n * factorial(n - 1);
|
||||||
|
// factorial(6) -> 720
|
||||||
|
|
||||||
|
const fibonacci = n =>
|
||||||
|
Array(n).fill(0).reduce((acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), []);
|
||||||
|
// fibonacci(5) -> [0,1,1,2,3]
|
||||||
|
|
||||||
|
const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));
|
||||||
|
// filterNonUnique([1,2,2,3,4,4,5]) -> [1,3,5]
|
||||||
|
|
||||||
|
const flatten = arr => arr.reduce((a, v) => a.concat(v), []);
|
||||||
|
// flatten([1,[2],3,4]) -> [1,2,3,4]
|
||||||
|
|
||||||
|
const arrayMax = arr => Math.max(...arr);
|
||||||
|
// arrayMax([10, 1, 5]) -> 10
|
||||||
|
|
||||||
|
const arrayMin = arr => Math.min(...arr);
|
||||||
|
// arrayMin([10, 1, 5]) -> 1
|
||||||
|
|
||||||
|
const getType = v =>
|
||||||
|
v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
|
||||||
|
// getType(new Set([1,2,3])) -> "set"
|
||||||
|
|
||||||
|
const getScrollPos = (el = window) =>
|
||||||
|
({x: (el.pageXOffset !== undefined) ? el.pageXOffset : el.scrollLeft,
|
||||||
|
y: (el.pageYOffset !== undefined) ? el.pageYOffset : el.scrollTop});
|
||||||
|
// getScrollPos() -> {x: 0, y: 200}
|
||||||
|
|
||||||
|
const gcd = (x, y) => !y ? x : gcd(y, x % y);
|
||||||
|
// gcd (8, 36) -> 4
|
||||||
|
|
||||||
|
const hammingDistance = (num1, num2) =>
|
||||||
|
((num1 ^ num2).toString(2).match(/1/g) || '').length;
|
||||||
|
// hammingDistance(2,3) -> 1
|
||||||
|
|
||||||
|
const head = arr => arr[0];
|
||||||
|
// head([1,2,3]) -> 1
|
||||||
|
|
||||||
|
const initial = arr => arr.slice(0, -1);
|
||||||
|
// initial([1,2,3]) -> [1,2]
|
||||||
|
|
||||||
|
const initializeArrayRange = (end, start = 0) =>
|
||||||
|
Array.apply(null, Array(end - start)).map((v, i) => i + start);
|
||||||
|
// initializeArrayRange(5) -> [0,1,2,3,4]
|
||||||
|
|
||||||
|
const initializeArray = (n, value = 0) => Array(n).fill(value);
|
||||||
|
// initializeArray(5, 2) -> [2,2,2,2,2]
|
||||||
|
|
||||||
|
const last = arr => arr.slice(-1)[0];
|
||||||
|
// last([1,2,3]) -> 3
|
||||||
|
|
||||||
|
const timeTaken = callback => {
|
||||||
|
const t0 = performance.now(), r = callback();
|
||||||
|
console.log(performance.now() - t0);
|
||||||
|
return r;
|
||||||
|
};
|
||||||
|
// timeTaken(() => Math.pow(2, 10)) -> 1024 (0.010000000009313226 logged in console)
|
||||||
|
|
||||||
|
const median = arr => {
|
||||||
|
const mid = Math.floor(arr.length / 2), nums = arr.sort((a, b) => a - b);
|
||||||
|
return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
|
||||||
|
};
|
||||||
|
// median([5,6,50,1,-5]) -> 5
|
||||||
|
// median([0,10,-2,7]) -> 3.5
|
||||||
|
|
||||||
|
const objectFromPairs = arr => arr.reduce((a, v) => (a[v[0]] = v[1], a), {});
|
||||||
|
// objectFromPairs([['a',1],['b',2]]) -> {a: 1, b: 2}
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
const pipe = (...funcs) => arg => funcs.reduce((acc, func) => func(acc), arg);
|
||||||
|
// pipe(btoa, x => x.toUpperCase())("Test") -> "VGVZDA=="
|
||||||
|
|
||||||
|
const powerset = arr =>
|
||||||
|
arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]);
|
||||||
|
// powerset([1,2]) -> [[], [1], [2], [2,1]]
|
||||||
|
|
||||||
|
const promisify = func =>
|
||||||
|
(...args) =>
|
||||||
|
new Promise((resolve, reject) =>
|
||||||
|
func(...args, (err, result) =>
|
||||||
|
err ? reject(err) : resolve(result))
|
||||||
|
);
|
||||||
|
// const delay = promisify((d, cb) => setTimeout(cb, d))
|
||||||
|
// delay(2000).then(() => console.log('Hi!')) -> Promise resolves after 2s
|
||||||
|
|
||||||
|
const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
|
||||||
|
// randomIntegerInRange(0, 5) -> 2
|
||||||
|
|
||||||
|
const randomInRange = (min, max) => Math.random() * (max - min) + min;
|
||||||
|
// randomInRange(2,10) -> 6.0211363285087005
|
||||||
|
|
||||||
|
const randomizeOrder = arr => arr.sort((a, b) => Math.random() >= 0.5 ? -1 : 1);
|
||||||
|
// randomizeOrder([1,2,3]) -> [1,3,2]
|
||||||
|
|
||||||
|
const redirect = (url, asLink = true) =>
|
||||||
|
asLink ? window.location.href = url : window.location.replace(url);
|
||||||
|
// redirect('https://google.com')
|
||||||
|
|
||||||
|
const reverseString = str => [...str].reverse().join('');
|
||||||
|
// reverseString('foobar') -> 'raboof'
|
||||||
|
|
||||||
|
const rgbToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
|
||||||
|
// rgbToHex(255, 165, 1) -> 'ffa501'
|
||||||
|
|
||||||
|
const series = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());
|
||||||
|
// const delay = (d) => new Promise(r => setTimeout(r, d))
|
||||||
|
// series([() => delay(1000), () => delay(2000)]) -> executes each promise sequentially, taking a total of 3 seconds to complete
|
||||||
|
|
||||||
|
const scrollToTop = _ => {
|
||||||
|
const c = document.documentElement.scrollTop || document.body.scrollTop;
|
||||||
|
if (c > 0) {
|
||||||
|
window.requestAnimationFrame(scrollToTop);
|
||||||
|
window.scrollTo(0, c - c / 8);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// scrollToTop()
|
||||||
|
|
||||||
|
const shuffle = arr => {
|
||||||
|
let r = arr.map(Math.random);
|
||||||
|
return arr.sort((a, b) => r[a] - r[b]);
|
||||||
|
};
|
||||||
|
// shuffle([1,2,3]) -> [2, 1, 3]
|
||||||
|
|
||||||
|
const similarity = (arr, values) => arr.filter(v => values.includes(v));
|
||||||
|
// similarity([1,2,3], [1,2,4]) -> [1,2]
|
||||||
|
|
||||||
|
const sortCharactersInString = str =>
|
||||||
|
str.split('').sort((a, b) => a.localeCompare(b)).join('');
|
||||||
|
// sortCharactersInString('cabbage') -> 'aabbceg'
|
||||||
|
|
||||||
|
const sum = arr => arr.reduce((acc, val) => acc + val, 0);
|
||||||
|
// sum([1,2,3,4]) -> 10
|
||||||
|
|
||||||
|
[varA, varB] = [varB, varA];
|
||||||
|
// [x, y] = [y, x]
|
||||||
|
|
||||||
|
const tail = arr => arr.length > 1 ? arr.slice(1) : arr;
|
||||||
|
// tail([1,2,3]) -> [2,3]
|
||||||
|
// tail([1]) -> [1]
|
||||||
|
|
||||||
|
const truncate = (str, num) =>
|
||||||
|
str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str;
|
||||||
|
// truncate('boomerang', 7) -> 'boom...'
|
||||||
|
|
||||||
|
const unique = arr => [...new Set(arr)];
|
||||||
|
// unique([1,2,2,3,4,4,5]) -> [1,2,3,4,5]
|
||||||
|
|
||||||
|
const getUrlParameters = url =>
|
||||||
|
url.match(/([^?=&]+)(=([^&]*))?/g).reduce(
|
||||||
|
(a, v) => (a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1), a), {}
|
||||||
|
);
|
||||||
|
// getUrlParameters('http://url.com/page?name=Adam&surname=Smith') -> {name: 'Adam', surname: 'Smith'}
|
||||||
|
|
||||||
|
const uuid = _ =>
|
||||||
|
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
|
||||||
|
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
|
||||||
|
);
|
||||||
|
// uuid() -> '7982fcfe-5721-4632-bede-6000885be57d'
|
||||||
|
|
||||||
|
const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n);
|
||||||
|
// validateNumber('10') -> true
|
||||||
|
|
||||||
|
const valueOrDefault = (value, d) => value || d;
|
||||||
|
// valueOrDefault(NaN, 30) -> 30
|
||||||
302
snippets.js
Normal file
302
snippets.js
Normal file
@ -0,0 +1,302 @@
|
|||||||
|
|
||||||
|
const anagrams = str => {
|
||||||
|
if(str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];
|
||||||
|
return str.split('').reduce( (acc, letter, i) =>
|
||||||
|
acc.concat(anagrams(str.slice(0, i) + str.slice(i + 1)).map( val => letter + val )), []);
|
||||||
|
}
|
||||||
|
// anagrams('abc') -> ['abc','acb','bac','bca','cab','cba']
|
||||||
|
|
||||||
|
|
||||||
|
const average = arr =>
|
||||||
|
arr.reduce( (acc , val) => acc + val, 0) / arr.length;
|
||||||
|
// average([1,2,3]) -> 2
|
||||||
|
|
||||||
|
|
||||||
|
const bottomVisible = _ =>
|
||||||
|
document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight || document.documentElement.clientHeight;
|
||||||
|
// bottomVisible() -> true
|
||||||
|
|
||||||
|
|
||||||
|
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
|
||||||
|
// capitalizeEveryWord('hello world!') -> 'Hello World!'
|
||||||
|
|
||||||
|
|
||||||
|
const capitalize = (str, lowerRest = false) =>
|
||||||
|
str.slice(0, 1).toUpperCase() + (lowerRest? str.slice(1).toLowerCase() : str.slice(1));
|
||||||
|
// capitalize('myName', true) -> 'Myname'
|
||||||
|
|
||||||
|
|
||||||
|
const chainAsync = fns => { let curr = 0; const next = () => fns[curr++](next); next(); }
|
||||||
|
/*
|
||||||
|
chainAsync([
|
||||||
|
next => { console.log('0 seconds'); setTimeout(next, 1000); },
|
||||||
|
next => { console.log('1 second'); setTimeout(next, 1000); },
|
||||||
|
next => { console.log('2 seconds'); }
|
||||||
|
])
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
const palindrome = str =>
|
||||||
|
str.toLowerCase().replace(/[\W_]/g,'').split('').reverse().join('') === str.toLowerCase().replace(/[\W_]/g,'');
|
||||||
|
// palindrome('taco cat') -> true
|
||||||
|
|
||||||
|
|
||||||
|
const chunk = (arr, size) =>
|
||||||
|
Array.apply(null, {length: Math.ceil(arr.length/size)}).map((v, i) => arr.slice(i*size, i*size+size));
|
||||||
|
// chunk([1,2,3,4,5], 2) -> [[1,2],[3,4],5]
|
||||||
|
|
||||||
|
|
||||||
|
const countOccurrences = (arr, value) => arr.reduce((a, v) => v === value ? a + 1 : a + 0, 0);
|
||||||
|
// countOccurrences([1,1,2,1,2,3], 1) -> 3
|
||||||
|
|
||||||
|
|
||||||
|
const currentUrl = _ => window.location.href;
|
||||||
|
// currentUrl() -> 'https://google.com'
|
||||||
|
|
||||||
|
|
||||||
|
const curry = (f, arity = f.length, next) =>
|
||||||
|
(next = prevArgs =>
|
||||||
|
nextArg => {
|
||||||
|
const args = [ ...prevArgs, nextArg ];
|
||||||
|
return args.length >= arity ? f(...args) : next(args);
|
||||||
|
}
|
||||||
|
)([]);
|
||||||
|
// curry(Math.pow)(2)(10) -> 1024
|
||||||
|
// curry(Math.min, 3)(10)(50)(2) -> 2
|
||||||
|
|
||||||
|
|
||||||
|
const deepFlatten = arr =>
|
||||||
|
arr.reduce( (a, v) => a.concat( Array.isArray(v) ? deepFlatten(v) : v ), []);
|
||||||
|
// deepFlatten([1,[2],[[3],4],5]) -> [1,2,3,4,5]
|
||||||
|
|
||||||
|
|
||||||
|
const difference = (arr, values) => arr.filter(v => !values.includes(v));
|
||||||
|
// difference([1,2,3], [1,2]) -> [3]
|
||||||
|
|
||||||
|
|
||||||
|
const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
|
||||||
|
// distance(1,1, 2,3) -> 2.23606797749979
|
||||||
|
|
||||||
|
|
||||||
|
const isDivisible = (dividend, divisor) => dividend % divisor === 0;
|
||||||
|
// isDivisible(6,3) -> true
|
||||||
|
|
||||||
|
|
||||||
|
const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||||
|
// escapeRegExp('(test)') -> \\(test\\)
|
||||||
|
|
||||||
|
|
||||||
|
const isEven = num => Math.abs(num) % 2 === 0;
|
||||||
|
// isEven(3) -> false
|
||||||
|
|
||||||
|
|
||||||
|
const factorial = n => n <= 1 ? 1 : n * factorial(n - 1);
|
||||||
|
// factorial(6) -> 720
|
||||||
|
|
||||||
|
|
||||||
|
const fibonacci = n =>
|
||||||
|
Array(n).fill(0).reduce((acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),[]);
|
||||||
|
// fibonacci(5) -> [0,1,1,2,3]
|
||||||
|
|
||||||
|
|
||||||
|
const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));
|
||||||
|
// filterNonUnique([1,2,2,3,4,4,5]) -> [1,3,5]
|
||||||
|
|
||||||
|
|
||||||
|
const flatten = arr => arr.reduce( (a, v) => a.concat(v), []);
|
||||||
|
// flatten([1,[2],3,4]) -> [1,2,3,4]
|
||||||
|
|
||||||
|
|
||||||
|
const arrayMax = arr => Math.max(...arr);
|
||||||
|
// arrayMax([10, 1, 5]) -> 10
|
||||||
|
|
||||||
|
|
||||||
|
const arrayMin = arr => Math.min(...arr);
|
||||||
|
// arrayMin([10, 1, 5]) -> 1
|
||||||
|
|
||||||
|
|
||||||
|
const getType = v =>
|
||||||
|
v === undefined ? "undefined" : v === null ? "null" : v.constructor.name.toLowerCase();
|
||||||
|
// getType(new Set([1,2,3])) -> "set"
|
||||||
|
|
||||||
|
|
||||||
|
const getScrollPos = (el = window) =>
|
||||||
|
( {x: (el.pageXOffset !== undefined) ? el.pageXOffset : el.scrollLeft,
|
||||||
|
y: (el.pageYOffset !== undefined) ? el.pageYOffset : el.scrollTop} );
|
||||||
|
// getScrollPos() -> {x: 0, y: 200}
|
||||||
|
|
||||||
|
|
||||||
|
const gcd = (x , y) => !y ? x : gcd(y, x % y);
|
||||||
|
// gcd (8, 36) -> 4
|
||||||
|
|
||||||
|
|
||||||
|
const hammingDistance = (num1, num2) =>
|
||||||
|
((num1^num2).toString(2).match(/1/g) || '').length;
|
||||||
|
// hammingDistance(2,3) -> 1
|
||||||
|
|
||||||
|
|
||||||
|
const head = arr => arr[0];
|
||||||
|
// head([1,2,3]) -> 1
|
||||||
|
|
||||||
|
|
||||||
|
const initial = arr => arr.slice(0,-1);
|
||||||
|
// initial([1,2,3]) -> [1,2]
|
||||||
|
|
||||||
|
|
||||||
|
const initializeArrayRange = (end, start = 0) =>
|
||||||
|
Array.apply(null, Array(end-start)).map( (v,i) => i + start );
|
||||||
|
// initializeArrayRange(5) -> [0,1,2,3,4]
|
||||||
|
|
||||||
|
|
||||||
|
const initializeArray = (n, value = 0) => Array(n).fill(value);
|
||||||
|
// initializeArray(5, 2) -> [2,2,2,2,2]
|
||||||
|
|
||||||
|
|
||||||
|
const last = arr => arr.slice(-1)[0];
|
||||||
|
// last([1,2,3]) -> 3
|
||||||
|
|
||||||
|
|
||||||
|
const timeTaken = callback => {
|
||||||
|
const t0 = performance.now(), r = callback();
|
||||||
|
console.log(performance.now() - t0);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
// timeTaken(() => Math.pow(2, 10)) -> 1024 (0.010000000009313226 logged in console)
|
||||||
|
|
||||||
|
|
||||||
|
const median = arr => {
|
||||||
|
const mid = Math.floor(arr.length / 2), nums = arr.sort((a,b) => a - b);
|
||||||
|
return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
|
||||||
|
}
|
||||||
|
// median([5,6,50,1,-5]) -> 5
|
||||||
|
// median([0,10,-2,7]) -> 3.5
|
||||||
|
|
||||||
|
|
||||||
|
const objectFromPairs = arr => arr.reduce((a,v) => (a[v[0]] = v[1], a), {});
|
||||||
|
// objectFromPairs([['a',1],['b',2]]) -> {a: 1, b: 2}
|
||||||
|
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
const pipe = (...funcs) => arg => funcs.reduce((acc, func) => func(acc), arg);
|
||||||
|
// pipe(btoa, x => x.toUpperCase())("Test") -> "VGVZDA=="
|
||||||
|
|
||||||
|
|
||||||
|
const powerset = arr =>
|
||||||
|
arr.reduce( (a,v) => a.concat(a.map( r => [v].concat(r) )), [[]]);
|
||||||
|
// powerset([1,2]) -> [[], [1], [2], [2,1]]
|
||||||
|
|
||||||
|
|
||||||
|
const promisify = func =>
|
||||||
|
(...args) =>
|
||||||
|
new Promise((resolve, reject) =>
|
||||||
|
func(...args, (err, result) =>
|
||||||
|
err ? reject(err) : resolve(result))
|
||||||
|
);
|
||||||
|
// const delay = promisify((d, cb) => setTimeout(cb, d))
|
||||||
|
// delay(2000).then(() => console.log('Hi!')) -> Promise resolves after 2s
|
||||||
|
|
||||||
|
|
||||||
|
const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
|
||||||
|
// randomIntegerInRange(0, 5) -> 2
|
||||||
|
|
||||||
|
|
||||||
|
const randomInRange = (min, max) => Math.random() * (max - min) + min;
|
||||||
|
// randomInRange(2,10) -> 6.0211363285087005
|
||||||
|
|
||||||
|
|
||||||
|
const randomizeOrder = arr => arr.sort( (a,b) => Math.random() >= 0.5 ? -1 : 1);
|
||||||
|
// randomizeOrder([1,2,3]) -> [1,3,2]
|
||||||
|
|
||||||
|
|
||||||
|
const redirect = (url, asLink = true) =>
|
||||||
|
asLink ? window.location.href = url : window.location.replace(url);
|
||||||
|
// redirect('https://google.com')
|
||||||
|
|
||||||
|
|
||||||
|
const reverseString = str => [...str].reverse().join('');
|
||||||
|
// reverseString('foobar') -> 'raboof'
|
||||||
|
|
||||||
|
|
||||||
|
const rgbToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
|
||||||
|
// rgbToHex(255, 165, 1) -> 'ffa501'
|
||||||
|
|
||||||
|
|
||||||
|
const series = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());
|
||||||
|
// const delay = (d) => new Promise(r => setTimeout(r, d))
|
||||||
|
// series([() => delay(1000), () => delay(2000)]) -> executes each promise sequentially, taking a total of 3 seconds to complete
|
||||||
|
|
||||||
|
|
||||||
|
const scrollToTop = _ => {
|
||||||
|
const c = document.documentElement.scrollTop || document.body.scrollTop;
|
||||||
|
if(c > 0) {
|
||||||
|
window.requestAnimationFrame(scrollToTop);
|
||||||
|
window.scrollTo(0, c - c/8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// scrollToTop()
|
||||||
|
|
||||||
|
|
||||||
|
const shuffle = arr => {
|
||||||
|
let r = arr.map(Math.random);
|
||||||
|
return arr.sort((a,b) => r[a] - r[b]);
|
||||||
|
}
|
||||||
|
// shuffle([1,2,3]) -> [2, 1, 3]
|
||||||
|
|
||||||
|
|
||||||
|
const similarity = (arr, values) => arr.filter(v => values.includes(v));
|
||||||
|
// similarity([1,2,3], [1,2,4]) -> [1,2]
|
||||||
|
|
||||||
|
|
||||||
|
const sortCharactersInString = str =>
|
||||||
|
str.split('').sort( (a,b) => a.localeCompare(b) ).join('');
|
||||||
|
// sortCharactersInString('cabbage') -> 'aabbceg'
|
||||||
|
|
||||||
|
|
||||||
|
const sum = arr => arr.reduce( (acc , val) => acc + val, 0);
|
||||||
|
// sum([1,2,3,4]) -> 10
|
||||||
|
|
||||||
|
|
||||||
|
[varA, varB] = [varB, varA];
|
||||||
|
// [x, y] = [y, x]
|
||||||
|
|
||||||
|
|
||||||
|
const tail = arr => arr.length > 1 ? arr.slice(1) : arr;
|
||||||
|
// tail([1,2,3]) -> [2,3]
|
||||||
|
// tail([1]) -> [1]
|
||||||
|
|
||||||
|
|
||||||
|
const truncate = (str, num) =>
|
||||||
|
str.length > num ? str.slice(0, num > 3 ? num-3 : num) + '...' : str;
|
||||||
|
// truncate('boomerang', 7) -> 'boom...'
|
||||||
|
|
||||||
|
|
||||||
|
const unique = arr => [...new Set(arr)];
|
||||||
|
// unique([1,2,2,3,4,4,5]) -> [1,2,3,4,5]
|
||||||
|
|
||||||
|
|
||||||
|
const getUrlParameters = url =>
|
||||||
|
url.match(/([^?=&]+)(=([^&]*))?/g).reduce(
|
||||||
|
(a,v) => (a[v.slice(0,v.indexOf('='))] = v.slice(v.indexOf('=')+1), a), {}
|
||||||
|
);
|
||||||
|
// getUrlParameters('http://url.com/page?name=Adam&surname=Smith') -> {name: 'Adam', surname: 'Smith'}
|
||||||
|
|
||||||
|
|
||||||
|
const uuid = _ =>
|
||||||
|
( [1e7]+-1e3+-4e3+-8e3+-1e11 ).replace( /[018]/g, c =>
|
||||||
|
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
|
||||||
|
);
|
||||||
|
// uuid() -> '7982fcfe-5721-4632-bede-6000885be57d'
|
||||||
|
|
||||||
|
|
||||||
|
const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n);
|
||||||
|
// validateNumber('10') -> true
|
||||||
|
|
||||||
|
|
||||||
|
const valueOrDefault = (value, d) => value || d;
|
||||||
|
// valueOrDefault(NaN, 30) -> 30
|
||||||
|
|
||||||
|
|
||||||
@ -6,7 +6,7 @@ Pass `location.search` as the argument to apply to the current `url`.
|
|||||||
```js
|
```js
|
||||||
const getUrlParameters = url =>
|
const getUrlParameters = url =>
|
||||||
url.match(/([^?=&]+)(=([^&]*))?/g).reduce(
|
url.match(/([^?=&]+)(=([^&]*))?/g).reduce(
|
||||||
(a,v) => (a[v.slice(0,v.indexOf('='))] = v.slice(v.indexOf('=')+1), a), {}
|
(a, v) => (a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1), a), {}
|
||||||
);
|
);
|
||||||
// getUrlParameters('http://url.com/page?name=Adam&surname=Smith') -> {name: 'Adam', surname: 'Smith'}
|
// getUrlParameters('http://url.com/page?name=Adam&surname=Smith') -> {name: 'Adam', surname: 'Smith'}
|
||||||
```
|
```
|
||||||
|
|||||||
@ -4,7 +4,7 @@ Use `crypto` API to generate a UUID, compliant with [RFC4122](https://www.ietf.o
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const uuid = _ =>
|
const uuid = _ =>
|
||||||
( [1e7]+-1e3+-4e3+-8e3+-1e11 ).replace( /[018]/g, c =>
|
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
|
||||||
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
|
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
|
||||||
);
|
);
|
||||||
// uuid() -> '7982fcfe-5721-4632-bede-6000885be57d'
|
// uuid() -> '7982fcfe-5721-4632-bede-6000885be57d'
|
||||||
|
|||||||
@ -7,9 +7,9 @@ Base cases are for string `length` equal to `2` or `1`.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const anagrams = str => {
|
const anagrams = str => {
|
||||||
if(str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];
|
if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];
|
||||||
return str.split('').reduce( (acc, letter, i) =>
|
return str.split('').reduce((acc, letter, i) =>
|
||||||
acc.concat(anagrams(str.slice(0, i) + str.slice(i + 1)).map( val => letter + val )), []);
|
acc.concat(anagrams(str.slice(0, i) + str.slice(i + 1)).map(val => letter + val)), []);
|
||||||
}
|
};
|
||||||
// anagrams('abc') -> ['abc','acb','bac','bca','cab','cba']
|
// anagrams('abc') -> ['abc','acb','bac','bca','cab','cba']
|
||||||
```
|
```
|
||||||
|
|||||||
@ -3,7 +3,6 @@
|
|||||||
Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array.
|
Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const average = arr =>
|
const average = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length;
|
||||||
arr.reduce( (acc , val) => acc + val, 0) / arr.length;
|
|
||||||
// average([1,2,3]) -> 2
|
// average([1,2,3]) -> 2
|
||||||
```
|
```
|
||||||
|
|||||||
@ -3,7 +3,7 @@
|
|||||||
Use `scrollY`, `scrollHeight` and `clientHeight` to determine if the bottom of the page is visible.
|
Use `scrollY`, `scrollHeight` and `clientHeight` to determine if the bottom of the page is visible.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const bottomVisible = _ =>
|
const bottomVisible = _ =>
|
||||||
document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight || document.documentElement.clientHeight;
|
document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight || document.documentElement.clientHeight;
|
||||||
// bottomVisible() -> true
|
// bottomVisible() -> true
|
||||||
```
|
```
|
||||||
|
|||||||
@ -5,6 +5,6 @@ Omit the `lowerRest` parameter to keep the rest of the string intact, or set it
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const capitalize = (str, lowerRest = false) =>
|
const capitalize = (str, lowerRest = false) =>
|
||||||
str.slice(0, 1).toUpperCase() + (lowerRest? str.slice(1).toLowerCase() : str.slice(1));
|
str.slice(0, 1).toUpperCase() + (lowerRest ? str.slice(1).toLowerCase() : str.slice(1));
|
||||||
// capitalize('myName', true) -> 'Myname'
|
// capitalize('myName', true) -> 'Myname'
|
||||||
```
|
```
|
||||||
|
|||||||
@ -3,7 +3,7 @@
|
|||||||
Loop through an array of functions containing asynchronous events, calling `next` when each asynchronous event has completed.
|
Loop through an array of functions containing asynchronous events, calling `next` when each asynchronous event has completed.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const chainAsync = fns => { let curr = 0; const next = () => fns[curr++](next); next(); }
|
const chainAsync = fns => { let curr = 0; const next = () => fns[curr++](next); next(); };
|
||||||
/*
|
/*
|
||||||
chainAsync([
|
chainAsync([
|
||||||
next => { console.log('0 seconds'); setTimeout(next, 1000); },
|
next => { console.log('0 seconds'); setTimeout(next, 1000); },
|
||||||
|
|||||||
@ -6,6 +6,6 @@ If the original array can't be split evenly, the final chunk will contain the re
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const chunk = (arr, size) =>
|
const chunk = (arr, size) =>
|
||||||
Array.apply(null, {length: Math.ceil(arr.length/size)}).map((v, i) => arr.slice(i*size, i*size+size));
|
Array.apply(null, {length: Math.ceil(arr.length / size)}).map((v, i) => arr.slice(i * size, i * size + size));
|
||||||
// chunk([1,2,3,4,5], 2) -> [[1,2],[3,4],5]
|
// chunk([1,2,3,4,5], 2) -> [[1,2],[3,4],5]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -5,6 +5,6 @@ Use `Array.reduce()` to get all elements that are not arrays, flatten each eleme
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const deepFlatten = arr =>
|
const deepFlatten = arr =>
|
||||||
arr.reduce( (a, v) => a.concat( Array.isArray(v) ? deepFlatten(v) : v ), []);
|
arr.reduce((a, v) => a.concat(Array.isArray(v) ? deepFlatten(v) : v), []);
|
||||||
// deepFlatten([1,[2],[[3],4],5]) -> [1,2,3,4,5]
|
// deepFlatten([1,[2],[[3],4],5]) -> [1,2,3,4,5]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -4,7 +4,7 @@ Create an empty array of the specific length, initializing the first two values
|
|||||||
Use `Array.reduce()` to add values into the array, using the sum of the last two values, except for the first two.
|
Use `Array.reduce()` to add values into the array, using the sum of the last two values, except for the first two.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const fibonacci = n =>
|
const fibonacci = n =>
|
||||||
Array(n).fill(0).reduce((acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),[]);
|
Array(n).fill(0).reduce((acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), []);
|
||||||
// fibonacci(5) -> [0,1,1,2,3]
|
// fibonacci(5) -> [0,1,1,2,3]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -3,6 +3,6 @@
|
|||||||
Use `Array.reduce()` to get all elements inside the array and `concat()` to flatten them.
|
Use `Array.reduce()` to get all elements inside the array and `concat()` to flatten them.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const flatten = arr => arr.reduce( (a, v) => a.concat(v), []);
|
const flatten = arr => arr.reduce((a, v) => a.concat(v), []);
|
||||||
// flatten([1,[2],3,4]) -> [1,2,3,4]
|
// flatten([1,[2],3,4]) -> [1,2,3,4]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -4,6 +4,6 @@ Returns lower-cased constructor name of value, "undefined" or "null" if value is
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const getType = v =>
|
const getType = v =>
|
||||||
v === undefined ? "undefined" : v === null ? "null" : v.constructor.name.toLowerCase();
|
v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
|
||||||
// getType(new Set([1,2,3])) -> "set"
|
// getType(new Set([1,2,3])) -> "set"
|
||||||
```
|
```
|
||||||
|
|||||||
@ -5,7 +5,7 @@ You can omit `el` to use a default value of `window`.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const getScrollPos = (el = window) =>
|
const getScrollPos = (el = window) =>
|
||||||
( {x: (el.pageXOffset !== undefined) ? el.pageXOffset : el.scrollLeft,
|
({x: (el.pageXOffset !== undefined) ? el.pageXOffset : el.scrollLeft,
|
||||||
y: (el.pageYOffset !== undefined) ? el.pageYOffset : el.scrollTop} );
|
y: (el.pageYOffset !== undefined) ? el.pageYOffset : el.scrollTop});
|
||||||
// getScrollPos() -> {x: 0, y: 200}
|
// getScrollPos() -> {x: 0, y: 200}
|
||||||
```
|
```
|
||||||
|
|||||||
@ -5,6 +5,6 @@ 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`.
|
Otherwise, return the GCD of `y` and the remainder of the division `x/y`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const gcd = (x , y) => !y ? x : gcd(y, x % y);
|
const gcd = (x, y) => !y ? x : gcd(y, x % y);
|
||||||
// gcd (8, 36) -> 4
|
// gcd (8, 36) -> 4
|
||||||
```
|
```
|
||||||
|
|||||||
@ -5,6 +5,6 @@ Count and return the number of `1`s in the string, using `match(/1/g)`.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const hammingDistance = (num1, num2) =>
|
const hammingDistance = (num1, num2) =>
|
||||||
((num1^num2).toString(2).match(/1/g) || '').length;
|
((num1 ^ num2).toString(2).match(/1/g) || '').length;
|
||||||
// hammingDistance(2,3) -> 1
|
// hammingDistance(2,3) -> 1
|
||||||
```
|
```
|
||||||
|
|||||||
@ -3,6 +3,6 @@
|
|||||||
Return `arr.slice(0,-1)`.
|
Return `arr.slice(0,-1)`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const initial = arr => arr.slice(0,-1);
|
const initial = arr => arr.slice(0, -1);
|
||||||
// initial([1,2,3]) -> [1,2]
|
// initial([1,2,3]) -> [1,2]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -5,6 +5,6 @@ You can omit `start` to use a default value of `0`.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const initializeArrayRange = (end, start = 0) =>
|
const initializeArrayRange = (end, start = 0) =>
|
||||||
Array.apply(null, Array(end-start)).map( (v,i) => i + start );
|
Array.apply(null, Array(end - start)).map((v, i) => i + start);
|
||||||
// initializeArrayRange(5) -> [0,1,2,3,4]
|
// initializeArrayRange(5) -> [0,1,2,3,4]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -8,6 +8,6 @@ const timeTaken = callback => {
|
|||||||
const t0 = performance.now(), r = callback();
|
const t0 = performance.now(), r = callback();
|
||||||
console.log(performance.now() - t0);
|
console.log(performance.now() - t0);
|
||||||
return r;
|
return r;
|
||||||
}
|
};
|
||||||
// timeTaken(() => Math.pow(2, 10)) -> 1024 (0.010000000009313226 logged in console)
|
// timeTaken(() => Math.pow(2, 10)) -> 1024 (0.010000000009313226 logged in console)
|
||||||
```
|
```
|
||||||
|
|||||||
@ -5,9 +5,9 @@ Return the number at the midpoint if `length` is odd, otherwise the average of t
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const median = arr => {
|
const median = arr => {
|
||||||
const mid = Math.floor(arr.length / 2), nums = arr.sort((a,b) => a - b);
|
const mid = Math.floor(arr.length / 2), nums = arr.sort((a, b) => a - b);
|
||||||
return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
|
return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
|
||||||
}
|
};
|
||||||
// median([5,6,50,1,-5]) -> 5
|
// median([5,6,50,1,-5]) -> 5
|
||||||
// median([0,10,-2,7]) -> 3.5
|
// median([0,10,-2,7]) -> 3.5
|
||||||
```
|
```
|
||||||
|
|||||||
@ -3,6 +3,6 @@
|
|||||||
Use `Array.reduce()` to create and combine key-value pairs.
|
Use `Array.reduce()` to create and combine key-value pairs.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const objectFromPairs = arr => arr.reduce((a,v) => (a[v[0]] = v[1], a), {});
|
const objectFromPairs = arr => arr.reduce((a, v) => (a[v[0]] = v[1], a), {});
|
||||||
// objectFromPairs([['a',1],['b',2]]) -> {a: 1, b: 2}
|
// objectFromPairs([['a',1],['b',2]]) -> {a: 1, b: 2}
|
||||||
```
|
```
|
||||||
|
|||||||
@ -4,6 +4,6 @@ Use `Array.reduce()` combined with `Array.map()` to iterate over elements and co
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const powerset = arr =>
|
const powerset = arr =>
|
||||||
arr.reduce( (a,v) => a.concat(a.map( r => [v].concat(r) )), [[]]);
|
arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]);
|
||||||
// powerset([1,2]) -> [[], [1], [2], [2,1]]
|
// powerset([1,2]) -> [[], [1], [2], [2,1]]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -3,6 +3,6 @@
|
|||||||
Use `Array.sort()` to reorder elements, utilizing `Math.random()` to randomize the sorting.
|
Use `Array.sort()` to reorder elements, utilizing `Math.random()` to randomize the sorting.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const randomizeOrder = arr => arr.sort( (a,b) => Math.random() >= 0.5 ? -1 : 1);
|
const randomizeOrder = arr => arr.sort((a, b) => Math.random() >= 0.5 ? -1 : 1);
|
||||||
// randomizeOrder([1,2,3]) -> [1,3,2]
|
// randomizeOrder([1,2,3]) -> [1,3,2]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,10 +6,10 @@ Scroll by a fraction of the distance from top. Use `window.requestAnimationFrame
|
|||||||
```js
|
```js
|
||||||
const scrollToTop = _ => {
|
const scrollToTop = _ => {
|
||||||
const c = document.documentElement.scrollTop || document.body.scrollTop;
|
const c = document.documentElement.scrollTop || document.body.scrollTop;
|
||||||
if(c > 0) {
|
if (c > 0) {
|
||||||
window.requestAnimationFrame(scrollToTop);
|
window.requestAnimationFrame(scrollToTop);
|
||||||
window.scrollTo(0, c - c/8);
|
window.scrollTo(0, c - c / 8);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
// scrollToTop()
|
// scrollToTop()
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,7 +6,7 @@ Use `Array.sort()` to sort the elements of the original array based on the rando
|
|||||||
```js
|
```js
|
||||||
const shuffle = arr => {
|
const shuffle = arr => {
|
||||||
let r = arr.map(Math.random);
|
let r = arr.map(Math.random);
|
||||||
return arr.sort((a,b) => r[a] - r[b]);
|
return arr.sort((a, b) => r[a] - r[b]);
|
||||||
}
|
};
|
||||||
// shuffle([1,2,3]) -> [2, 1, 3]
|
// shuffle([1,2,3]) -> [2, 1, 3]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -4,6 +4,6 @@ Split the string using `split('')`, `Array.sort()` utilizing `localeCompare()`,
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const sortCharactersInString = str =>
|
const sortCharactersInString = str =>
|
||||||
str.split('').sort( (a,b) => a.localeCompare(b) ).join('');
|
str.split('').sort((a, b) => a.localeCompare(b)).join('');
|
||||||
// sortCharactersInString('cabbage') -> 'aabbceg'
|
// sortCharactersInString('cabbage') -> 'aabbceg'
|
||||||
```
|
```
|
||||||
|
|||||||
@ -3,6 +3,6 @@
|
|||||||
Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`.
|
Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const sum = arr => arr.reduce( (acc , val) => acc + val, 0);
|
const sum = arr => arr.reduce((acc, val) => acc + val, 0);
|
||||||
// sum([1,2,3,4]) -> 10
|
// sum([1,2,3,4]) -> 10
|
||||||
```
|
```
|
||||||
|
|||||||
@ -5,6 +5,6 @@ Return the string truncated to the desired length, with `...` appended to the en
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const truncate = (str, num) =>
|
const truncate = (str, num) =>
|
||||||
str.length > num ? str.slice(0, num > 3 ? num-3 : num) + '...' : str;
|
str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str;
|
||||||
// truncate('boomerang', 7) -> 'boom...'
|
// truncate('boomerang', 7) -> 'boom...'
|
||||||
```
|
```
|
||||||
|
|||||||
Reference in New Issue
Block a user