Merge branch 'snippet-restructuring'
This commit is contained in:
@ -28,7 +28,7 @@ Here's what you can do to help:
|
|||||||
- Use ES6 notation to define your function. For example `const myFunction = ( arg1, arg2 ) => { }`.
|
- Use ES6 notation to define your function. For example `const myFunction = ( arg1, arg2 ) => { }`.
|
||||||
- Please use Javacript [Semi-Standard Style](https://github.com/Flet/semistandard).
|
- Please use Javacript [Semi-Standard Style](https://github.com/Flet/semistandard).
|
||||||
- Try to keep your snippets' code short and to the point. Use modern techniques and features. Make sure to test your code before submitting.
|
- Try to keep your snippets' code short and to the point. Use modern techniques and features. Make sure to test your code before submitting.
|
||||||
- All snippets must be followed by one (more if necessary) test case after the code, on a new line, in the form of a comment, along with the expected output. The syntax for this is `myFunction('testInput') -> 'testOutput'`. Use multiline comments only if necessary.
|
- All snippets must be followed by one (more if necessary) test case after the code, in a new block enclosed inside ` ```js ` and ` ``` `. The syntax for this is `myFunction('testInput') // 'testOutput'`. Use multiline examples only if necessary.
|
||||||
- Try to make your function name unique, so that it does not conflict with existing snippets.
|
- Try to make your function name unique, so that it does not conflict with existing snippets.
|
||||||
- Snippet functions do not have to handle errors in input, unless it's necessary (e.g. a mathematical function that cannot be extended to negative numbers should handle negative input appropriately).
|
- Snippet functions do not have to handle errors in input, unless it's necessary (e.g. a mathematical function that cannot be extended to negative numbers should handle negative input appropriately).
|
||||||
- Snippets should be short (usually below 10 lines). If your snippet is longer than that, you can still submit it, and we can help you shorten it or figure out ways to improve it.
|
- Snippets should be short (usually below 10 lines). If your snippet is longer than that, you can still submit it, and we can help you shorten it or figure out ways to improve it.
|
||||||
|
|||||||
722
docs/index.html
722
docs/index.html
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
@ -114,7 +114,10 @@ code, pre, kbd, code *, pre *, kbd *, code[class*="language-"], pre[class*="lang
|
|||||||
font-family: 'Inconsolata', Menlo, Consolas, monospace !important;
|
font-family: 'Inconsolata', Menlo, Consolas, monospace !important;
|
||||||
}
|
}
|
||||||
code, kbd { font-size: 1em; }
|
code, kbd { font-size: 1em; }
|
||||||
code { transform: scale(1); } /* Deals with the issue described in #243 */
|
code {
|
||||||
|
padding: 0; // Should make the first line's left padding the same as all other lines and avoid that annoying little step.
|
||||||
|
transform: scale(1); /* Deals with the issue described in #243 */
|
||||||
|
}
|
||||||
pre { font-size: 1rem; border: 0.0625rem solid var(--secondary-border-color); border-radius: var(--universal-border-radius);}
|
pre { font-size: 1rem; border: 0.0625rem solid var(--secondary-border-color); border-radius: var(--universal-border-radius);}
|
||||||
.group{position:relative;margin-top:2em;margin-bottom:-1em}
|
.group{position:relative;margin-top:2em;margin-bottom:-1em}
|
||||||
.search{font-size:14px;margin-top:-.1em;display:block;width:100%;border:none;border-bottom:1px solid var(--nav-link-color)}
|
.search{font-size:14px;margin-top:-.1em;display:block;width:100%;border:none;border-bottom:1px solid var(--nav-link-color)}
|
||||||
|
|||||||
@ -25,7 +25,8 @@ try {
|
|||||||
console.time(`Linter (${snippet})`);
|
console.time(`Linter (${snippet})`);
|
||||||
// Synchronously read data from the snippet, get the code, write it to a temporary file
|
// Synchronously read data from the snippet, get the code, write it to a temporary file
|
||||||
let snippetData = fs.readFileSync(path.join(snippetsPath,snippet),'utf8');
|
let snippetData = fs.readFileSync(path.join(snippetsPath,snippet),'utf8');
|
||||||
let originalCode = snippetData.slice(snippetData.indexOf('```js')+5,snippetData.lastIndexOf('```'));
|
let codeStart = snippetData.indexOf('```js'), codeEnd = snippetData.search(/```[\n\r\s]+```js/g);
|
||||||
|
let originalCode = snippetData.slice(codeStart+5,codeEnd);
|
||||||
while(jobCounter >= 20){
|
while(jobCounter >= 20){
|
||||||
setTimeout(()=>{},1000);
|
setTimeout(()=>{},1000);
|
||||||
}
|
}
|
||||||
@ -36,7 +37,7 @@ try {
|
|||||||
cp.exec(`semistandard "${tempSnippet}.temp.js" --fix`,{},(error, stdOut, stdErr) => {
|
cp.exec(`semistandard "${tempSnippet}.temp.js" --fix`,{},(error, stdOut, stdErr) => {
|
||||||
jobCounter += 1;
|
jobCounter += 1;
|
||||||
let lintedCode = fs.readFileSync(`${tempSnippet}.temp.js`,'utf8');
|
let lintedCode = fs.readFileSync(`${tempSnippet}.temp.js`,'utf8');
|
||||||
fs.writeFile(path.join(snippetsPath,snippet), `${snippetData.slice(0, snippetData.indexOf('```js')+5)+lintedCode+'```\n'}`);
|
fs.writeFile(path.join(snippetsPath,snippet), `${snippetData.slice(0, codeStart+5)+lintedCode+snippetData.slice(codeEnd)}`);
|
||||||
fs.unlink(`${tempSnippet}.temp.js`);
|
fs.unlink(`${tempSnippet}.temp.js`);
|
||||||
// Log a success message
|
// Log a success message
|
||||||
console.log(`${chalk.green('SUCCESS!')} Linted snippet: ${snippet}`);
|
console.log(`${chalk.green('SUCCESS!')} Linted snippet: ${snippet}`);
|
||||||
|
|||||||
@ -7,5 +7,8 @@ Explain briefly how the snippet works.
|
|||||||
```js
|
```js
|
||||||
const functionName = arguments =>
|
const functionName = arguments =>
|
||||||
{functionBody}
|
{functionBody}
|
||||||
// functionName(sampleInput) -> sampleOutput
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
functionName('sampleInput') // 'sampleOutput'
|
||||||
```
|
```
|
||||||
@ -9,5 +9,8 @@ const JSONToDate = arr => {
|
|||||||
const dt = new Date(parseInt(arr.toString().substr(6)));
|
const dt = new Date(parseInt(arr.toString().substr(6)));
|
||||||
return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`;
|
return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`;
|
||||||
};
|
};
|
||||||
// JSONToDate(/Date(1489525200000)/) -> "14/3/2017"
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
JSONToDate(/Date(1489525200000)/) // "14/3/2017"
|
||||||
```
|
```
|
||||||
|
|||||||
@ -7,5 +7,8 @@ Use `fs.writeFile()`, template literals and `JSON.stringify()` to write a `json`
|
|||||||
```js
|
```js
|
||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
const JSONToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2));
|
const JSONToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2));
|
||||||
// JSONToFile({test: "is passed"}, 'testJsonFile') -> writes the object to 'testJsonFile.json'
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
JSONToFile({test: "is passed"}, 'testJsonFile') // writes the object to 'testJsonFile.json'
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Convert given RGB parameters to hexadecimal string using bitwise left-shift oper
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
|
const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
|
||||||
// RGBToHex(255, 165, 1) -> 'ffa501'
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
RGBToHex(255, 165, 1) // 'ffa501'
|
||||||
```
|
```
|
||||||
|
|||||||
@ -9,5 +9,8 @@ const UUIDGenerator = () =>
|
|||||||
([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)
|
||||||
);
|
);
|
||||||
// UUIDGenerator() -> '7982fcfe-5721-4632-bede-6000885be57d'
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
UUIDGenerator() // '7982fcfe-5721-4632-bede-6000885be57d'
|
||||||
```
|
```
|
||||||
|
|||||||
@ -13,5 +13,8 @@ const anagrams = 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']
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
anagrams('abc') // ['abc','acb','bac','bca','cab','cba']
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Use `Array.reduce()` to add each value to an accumulator, initialized with a val
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const arrayAverage = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length;
|
const arrayAverage = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length;
|
||||||
// arrayAverage([1,2,3]) -> 2
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
arrayAverage([1,2,3]) // 2
|
||||||
```
|
```
|
||||||
|
|||||||
@ -9,6 +9,9 @@ const arrayGcd = arr => {
|
|||||||
const gcd = (x, y) => !y ? x : gcd(y, x % y);
|
const gcd = (x, y) => !y ? x : gcd(y, x % y);
|
||||||
return arr.reduce((a, b) => gcd(a, b));
|
return arr.reduce((a, b) => gcd(a, b));
|
||||||
};
|
};
|
||||||
// arrayGcd([1,2,3,4,5]) -> 1
|
```
|
||||||
// arrayGcd([4,8,12]) -> 4
|
|
||||||
|
```js
|
||||||
|
arrayGcd([1,2,3,4,5]) // 1
|
||||||
|
arrayGcd([4,8,12]) // 4
|
||||||
```
|
```
|
||||||
|
|||||||
@ -10,6 +10,9 @@ const arrayLcm = arr => {
|
|||||||
const lcm = (x, y) => (x * y) / gcd(x, y);
|
const lcm = (x, y) => (x * y) / gcd(x, y);
|
||||||
return arr.reduce((a, b) => lcm(a, b));
|
return arr.reduce((a, b) => lcm(a, b));
|
||||||
};
|
};
|
||||||
// arrayLcm([1,2,3,4,5]) -> 60
|
```
|
||||||
// arrayLcm([4,8,12]) -> 24
|
|
||||||
|
```js
|
||||||
|
arrayLcm([1,2,3,4,5]) // 60
|
||||||
|
arrayLcm([4,8,12]) // 24
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Use `Math.max()` combined with the spread operator (`...`) to get the maximum va
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const arrayMax = arr => Math.max(...arr);
|
const arrayMax = arr => Math.max(...arr);
|
||||||
// arrayMax([10, 1, 5]) -> 10
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
arrayMax([10, 1, 5]) // 10
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Use `Math.min()` combined with the spread operator (`...`) to get the minimum va
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const arrayMin = arr => Math.min(...arr);
|
const arrayMin = arr => Math.min(...arr);
|
||||||
// arrayMin([10, 1, 5]) -> 1
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
arrayMin([10, 1, 5]) // 1
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Use `Array.reduce()` to add each value to an accumulator, initialized with a val
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const arraySum = arr => arr.reduce((acc, val) => acc + val, 0);
|
const arraySum = arr => arr.reduce((acc, val) => acc + val, 0);
|
||||||
// arraySum([1,2,3,4]) -> 10
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
arraySum([1,2,3,4]) // 10
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Use `Array.map()` and `document.querySelector()` to create a list of html tags.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const arrayToHtmlList = (arr, listID) => arr.map(item => document.querySelector('#' + listID).innerHTML += `<li>${item}</li>`);
|
const arrayToHtmlList = (arr, listID) => arr.map(item => document.querySelector('#' + listID).innerHTML += `<li>${item}</li>`);
|
||||||
// arrayToHtmlList(['item 1', 'item 2'],'myListID')
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
arrayToHtmlList(['item 1', 'item 2'],'myListID')
|
||||||
```
|
```
|
||||||
|
|||||||
@ -7,5 +7,8 @@ Use `scrollY`, `scrollHeight` and `clientHeight` to determine if the bottom of t
|
|||||||
```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
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
bottomVisible() // true
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,9 +6,10 @@ Use a closure to call a stored key with stored arguments.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const call = (key, ...args) => context => context[ key ](...args);
|
const call = (key, ...args) => context => context[ key ](...args);
|
||||||
/*
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
Promise.resolve( [ 1, 2, 3 ] ).then( call('map', x => 2 * x ) ).then( console.log ) //[ 2, 4, 6 ]
|
Promise.resolve( [ 1, 2, 3 ] ).then( call('map', x => 2 * x ) ).then( console.log ) //[ 2, 4, 6 ]
|
||||||
const map = call.bind(null, 'map')
|
const map = call.bind(null, 'map')
|
||||||
Promise.resolve( [ 1, 2, 3 ] ).then( map( x => 2 * x ) ).then( console.log ) //[ 2, 4, 6 ]
|
Promise.resolve( [ 1, 2, 3 ] ).then( map( x => 2 * x ) ).then( console.log ) //[ 2, 4, 6 ]
|
||||||
*/
|
|
||||||
```
|
```
|
||||||
|
|||||||
@ -8,6 +8,9 @@ Omit the `lowerRest` parameter to keep the rest of the string intact, or set it
|
|||||||
```js
|
```js
|
||||||
const capitalize = ([first, ...rest], lowerRest = false) =>
|
const capitalize = ([first, ...rest], lowerRest = false) =>
|
||||||
first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join(''));
|
first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join(''));
|
||||||
// capitalize('myName') -> 'MyName'
|
```
|
||||||
// capitalize('myName', true) -> 'Myname'
|
|
||||||
|
```js
|
||||||
|
capitalize('fooBar') // 'FooBar'
|
||||||
|
capitalize('fooBar', true) // 'Foobar'
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Use `replace()` to match the first character of each word and `toUpperCase()` to
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
|
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
|
||||||
// capitalizeEveryWord('hello world!') -> 'Hello World!'
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
capitalizeEveryWord('hello world!') // 'Hello World!'
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,11 +6,12 @@ Loop through an array of functions containing asynchronous events, calling `next
|
|||||||
|
|
||||||
```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(); };
|
||||||
/*
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
chainAsync([
|
chainAsync([
|
||||||
next => { console.log('0 seconds'); setTimeout(next, 1000); },
|
next => { console.log('0 seconds'); setTimeout(next, 1000); },
|
||||||
next => { console.log('1 second'); setTimeout(next, 1000); },
|
next => { console.log('1 second'); setTimeout(next, 1000); },
|
||||||
next => { console.log('2 seconds'); }
|
next => { console.log('2 seconds'); }
|
||||||
])
|
])
|
||||||
*/
|
|
||||||
```
|
```
|
||||||
|
|||||||
@ -9,5 +9,8 @@ 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.from({length: Math.ceil(arr.length / size)}, (v, i) => arr.slice(i * size, i * size + size));
|
Array.from({length: Math.ceil(arr.length / size)}, (v, i) => arr.slice(i * size, i * size + size));
|
||||||
// chunk([1,2,3,4,5], 2) -> [[1,2],[3,4],[5]]
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
chunk([1,2,3,4,5], 2) // [[1,2],[3,4],[5]]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -1,13 +1,16 @@
|
|||||||
### clampNumber
|
### clampNumber
|
||||||
|
|
||||||
Clamps `num` within the inclusive range specified by the boundary values `a` and `b`
|
Clamps `num` within the inclusive range specified by the boundary values `a` and `b`.
|
||||||
|
|
||||||
If `num` falls within the range, return `num`.
|
If `num` falls within the range, return `num`.
|
||||||
Otherwise, return the nearest number in the range.
|
Otherwise, return the nearest number in the range.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const clampNumber = (num, a, b) => Math.max(Math.min(num, Math.max(a,b)),Math.min(a,b));
|
const clampNumber = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b));
|
||||||
// clampNumber(2, 3, 5) -> 3
|
```
|
||||||
// clampNumber(1, -1, -5) -> -1
|
|
||||||
// clampNumber(3, 2, 4) -> 3
|
```js
|
||||||
|
clampNumber(2, 3, 5) // 3
|
||||||
|
clampNumber(1, -1, -5) // -1
|
||||||
|
clampNumber(3, 2, 4) // 3
|
||||||
```
|
```
|
||||||
|
|||||||
@ -16,8 +16,9 @@ const cleanObj = (obj, keysToKeep = [], childIndicator) => {
|
|||||||
});
|
});
|
||||||
return obj;
|
return obj;
|
||||||
};
|
};
|
||||||
/*
|
```
|
||||||
const testObj = {a: 1, b: 2, children: {a: 1, b: 2}}
|
|
||||||
cleanObj(testObj, ["a"],"children") // { a: 1, children : { a: 1}}
|
```js
|
||||||
*/
|
const testObj = {a: 1, b: 2, children: {a: 1, b: 2}}
|
||||||
|
cleanObj(testObj, ["a"],"children") // { a: 1, children : { a: 1}}
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Use `Array.find()` to return the first non `null`/`undefined` argument.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_));
|
const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_));
|
||||||
// coalesce(null,undefined,"",NaN, "Waldo") -> ""
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
coalesce(null,undefined,"",NaN, "Waldo") // ""
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,6 +6,9 @@ Use `Array.find()` to return the first argument that returns `true` from the pro
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const coalesceFactory = valid => (...args) => args.find(valid);
|
const coalesceFactory = valid => (...args) => args.find(valid);
|
||||||
// const customCoalesce = coalesceFactory(_ => ![null, undefined, "", NaN].includes(_))
|
```
|
||||||
// customCoalesce(undefined, null, NaN, "", "Waldo") //-> "Waldo"
|
|
||||||
|
```js
|
||||||
|
const customCoalesce = coalesceFactory(_ => ![null, undefined, "", NaN].includes(_))
|
||||||
|
customCoalesce(undefined, null, NaN, "", "Waldo") // "Waldo"
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,6 +6,9 @@ If `n` is even, return `n/2`. Otherwise, return `3n+1`.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const collatz = n => (n % 2 == 0) ? (n / 2) : (3 * n + 1);
|
const collatz = n => (n % 2 == 0) ? (n / 2) : (3 * n + 1);
|
||||||
// collatz(8) --> 4
|
```
|
||||||
// collatz(5) --> 16
|
|
||||||
|
```js
|
||||||
|
collatz(8) // 4
|
||||||
|
collatz(5) // 16
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,11 +6,12 @@ Given a function, return a closure that collects all inputs into an array-accept
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const collectInto = fn => (...args) => fn(args);
|
const collectInto = fn => (...args) => fn(args);
|
||||||
/*
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
const Pall = collectInto( Promise.all.bind(Promise) )
|
const Pall = collectInto( Promise.all.bind(Promise) )
|
||||||
let p1 = Promise.resolve(1)
|
let p1 = Promise.resolve(1)
|
||||||
let p2 = Promise.resolve(2)
|
let p2 = Promise.resolve(2)
|
||||||
let p3 = new Promise((resolve) => setTimeout(resolve,2000,3))
|
let p3 = new Promise((resolve) => setTimeout(resolve,2000,3))
|
||||||
Pall(p1, p2, p3).then(console.log)
|
Pall(p1, p2, p3).then(console.log)
|
||||||
*/
|
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Use `Array.filter()` to filter out falsey values (`false`, `null`, `0`, `""`, `u
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const compact = arr => arr.filter(Boolean);
|
const compact = arr => arr.filter(Boolean);
|
||||||
// compact([0, 1, false, 2, '', 3, 'a', 'e'*23, NaN, 's', 34]) -> [ 1, 2, 3, 'a', 's', 34 ]
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
compact([0, 1, false, 2, '', 3, 'a', 'e'*23, NaN, 's', 34]) // [ 1, 2, 3, 'a', 's', 34 ]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -7,10 +7,11 @@ The last (rightmost) function can accept one or more arguments; the remaining fu
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)));
|
const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)));
|
||||||
/*
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
const add5 = x => x + 5
|
const add5 = x => x + 5
|
||||||
const multiply = (x, y) => x * y
|
const multiply = (x, y) => x * y
|
||||||
const multiplyAndAdd5 = compose(add5, multiply)
|
const multiplyAndAdd5 = compose(add5, multiply)
|
||||||
multiplyAndAdd5(5, 2) -> 15
|
multiplyAndAdd5(5, 2) // 15
|
||||||
*/
|
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Use `Array.reduce()` to increment a counter each time you encounter the specific
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const countOccurrences = (arr, value) => arr.reduce((a, v) => v === value ? a + 1 : a + 0, 0);
|
const countOccurrences = (arr, value) => arr.reduce((a, v) => v === value ? a + 1 : a + 0, 0);
|
||||||
// countOccurrences([1,1,2,1,2,3], 1) -> 3
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
countOccurrences([1,1,2,1,2,3], 1) // 3
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,6 +6,9 @@ Use a regular expression to count the number of vowels `(A, E, I, O, U)` in a `s
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const countVowels = str => (str.match(/[aeiou]/ig) || []).length;
|
const countVowels = str => (str.match(/[aeiou]/ig) || []).length;
|
||||||
// countVowels('foobar') -> 3
|
```
|
||||||
// countVowels('gym') -> 0
|
|
||||||
|
```js
|
||||||
|
countVowels('foobar') // 3
|
||||||
|
countVowels('gym') // 0
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Use `window.location.href` to get current URL.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const currentURL = () => window.location.href;
|
const currentURL = () => window.location.href;
|
||||||
// currentUrl() -> 'https://google.com'
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
currentUrl() // 'https://google.com'
|
||||||
```
|
```
|
||||||
|
|||||||
@ -12,6 +12,9 @@ const curry = (fn, arity = fn.length, ...args) =>
|
|||||||
arity <= args.length
|
arity <= args.length
|
||||||
? fn(...args)
|
? fn(...args)
|
||||||
: curry.bind(null, fn, arity, ...args);
|
: curry.bind(null, fn, arity, ...args);
|
||||||
// curry(Math.pow)(2)(10) -> 1024
|
```
|
||||||
// curry(Math.min, 3)(10)(50)(2) -> 2
|
|
||||||
|
```js
|
||||||
|
curry(Math.pow)(2)(10) // 1024
|
||||||
|
curry(Math.min, 3)(10)(50)(2) // 2
|
||||||
```
|
```
|
||||||
|
|||||||
@ -8,5 +8,8 @@ Recursively flatten each element that is an array.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const deepFlatten = arr => [].concat(...arr.map(v => Array.isArray(v) ? deepFlatten(v) : v));
|
const deepFlatten = arr => [].concat(...arr.map(v => Array.isArray(v) ? deepFlatten(v) : v));
|
||||||
// deepFlatten([1,[2],[[3],4],5]) -> [1,2,3,4,5]
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
deepFlatten([1,[2],[[3],4],5]) // [1,2,3,4,5]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,6 +6,9 @@ Use a regular expression to test the `navigator.userAgent` property to figure ou
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const detectDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? 'Mobile' : 'Desktop';
|
const detectDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? 'Mobile' : 'Desktop';
|
||||||
// detectDeviceType() -> "Mobile"
|
```
|
||||||
// detectDeviceType() -> "Desktop"
|
|
||||||
|
```js
|
||||||
|
detectDeviceType() // "Mobile"
|
||||||
|
detectDeviceType() // "Desktop"
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values no
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const difference = (a, b) => { const s = new Set(b); return a.filter(x => !s.has(x)); };
|
const difference = (a, b) => { const s = new Set(b); return a.filter(x => !s.has(x)); };
|
||||||
// difference([1,2,3], [1,2,4]) -> [3]
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
difference([1,2,3], [1,2,4]) // [3]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Use `Array.filter()` and `Array.find()` to find the appropriate values.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const differenceWith = (arr, val, comp) => arr.filter(a => !val.find(b => comp(a, b)));
|
const differenceWith = (arr, val, comp) => arr.filter(a => !val.find(b => comp(a, b)));
|
||||||
// differenceWith([1, 1.2, 1.5, 3], [1.9, 3], (a,b) => Math.round(a) == Math.round(b)) -> [1, 1.2]
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
differenceWith([1, 1.2, 1.5, 3], [1.9, 3], (a,b) => Math.round(a) == Math.round(b)) // [1, 1.2]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -7,5 +7,8 @@ Use `Array.map()` and `parseInt()` to transform each value to an integer.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const digitize = n => [...'' + n].map(i => parseInt(i));
|
const digitize = n => [...'' + n].map(i => parseInt(i));
|
||||||
// digitize(2334) -> [2, 3, 3, 4]
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
differenceWith([1, 1.2, 1.5, 3], [1.9, 3], (a,b) => Math.round(a) == Math.round(b)) // [1, 1.2]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Use `Math.hypot()` to calculate the Euclidean distance between two points.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
|
const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
|
||||||
// distance(1,1, 2,3) -> 2.23606797749979
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
distance(1,1, 2,3) // 2.23606797749979
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Use ES6 `Set` and the `...rest` operator to discard all duplicated values.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const distinctValuesOfArray = arr => [...new Set(arr)];
|
const distinctValuesOfArray = arr => [...new Set(arr)];
|
||||||
// distinctValuesOfArray([1,2,2,3,4,4,5]) -> [1,2,3,4,5]
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
distinctValuesOfArray([1,2,2,3,4,4,5]) // [1,2,3,4,5]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -10,5 +10,8 @@ const dropElements = (arr, func) => {
|
|||||||
while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);
|
while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);
|
||||||
return arr;
|
return arr;
|
||||||
};
|
};
|
||||||
// dropElements([1, 2, 3, 4], n => n >= 3) -> [3,4]
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
dropElements([1, 2, 3, 4], n => n >= 3) // [3,4]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,7 +6,10 @@ Use `Array.slice()` to slice the remove the specified number of elements from th
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const dropRight = (arr, n = 1) => arr.slice(0, -n);
|
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) -> []
|
```js
|
||||||
|
dropRight([1,2,3]) // [1,2]
|
||||||
|
dropRight([1,2,3], 2) // [1]
|
||||||
|
dropRight([1,2,3], 42) // []
|
||||||
```
|
```
|
||||||
|
|||||||
@ -16,7 +16,10 @@ const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
|
|||||||
((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
|
((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
|
||||||
: top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
|
: top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
|
||||||
};
|
};
|
||||||
// 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)
|
```js
|
||||||
|
// 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)
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Use `replace()` to escape special characters.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||||
// escapeRegExp('(test)') -> \\(test\\)
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
escapeRegExp('(test)') // \\(test\\)
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Use `Array.filter()` to create a new array that contains every nth element of a
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);
|
const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);
|
||||||
// everyNth([1,2,3,4,5,6], 2) -> [ 2, 4, 6 ]
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
everyNth([1,2,3,4,5,6], 2) // [ 2, 4, 6 ]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -7,6 +7,9 @@ Use `Array.map()`, `split()` and `Array.join()` to join the mapped array for con
|
|||||||
```js
|
```js
|
||||||
const extendHex = shortHex =>
|
const extendHex = shortHex =>
|
||||||
'#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split('').map(x => x + x).join('');
|
'#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split('').map(x => x + x).join('');
|
||||||
// extendHex('#03f') -> '#0033ff'
|
```
|
||||||
// extendHex('05a') -> '#0055aa'
|
|
||||||
|
```js
|
||||||
|
extendHex('#03f') // '#0033ff'
|
||||||
|
extendHex('05a') // '#0055aa'
|
||||||
```
|
```
|
||||||
|
|||||||
@ -11,5 +11,8 @@ Throws an exception if `n` is a negative number.
|
|||||||
const factorial = n =>
|
const factorial = n =>
|
||||||
n < 0 ? (() => { throw new TypeError('Negative numbers are not allowed!'); })()
|
n < 0 ? (() => { throw new TypeError('Negative numbers are not allowed!'); })()
|
||||||
: n <= 1 ? 1 : n * factorial(n - 1);
|
: n <= 1 ? 1 : n * factorial(n - 1);
|
||||||
// factorial(6) -> 720
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
factorial(6) // 720
|
||||||
```
|
```
|
||||||
|
|||||||
@ -8,5 +8,8 @@ Use `Array.reduce()` to add values into the array, using the sum of the last two
|
|||||||
```js
|
```js
|
||||||
const fibonacci = n =>
|
const fibonacci = n =>
|
||||||
Array.from({ length: n}).reduce((acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), []);
|
Array.from({ length: n}).reduce((acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), []);
|
||||||
// fibonacci(5) -> [0,1,1,2,3]
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
fibonacci(6) // 720
|
||||||
```
|
```
|
||||||
|
|||||||
@ -7,5 +7,8 @@ Use a mathematical formula to calculate the number of fibonacci numbers until `n
|
|||||||
```js
|
```js
|
||||||
const fibonacciCountUntilNum = num =>
|
const fibonacciCountUntilNum = num =>
|
||||||
Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
|
Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
|
||||||
// fibonacciCountUntilNum(10) -> 7
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
fibonacciCountUntilNum(10) // 7
|
||||||
```
|
```
|
||||||
|
|||||||
@ -11,5 +11,8 @@ const fibonacciUntilNum = num => {
|
|||||||
let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
|
let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
|
||||||
return Array.from({ length: n}).reduce((acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), []);
|
return Array.from({ length: n}).reduce((acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), []);
|
||||||
};
|
};
|
||||||
// fibonacciUntilNum(15) -> [0,1,1,2,3,5,8,13]
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
fibonacciCountUntilNum(10) // 7
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Use `Array.filter()` for an array containing only the unique values.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));
|
const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));
|
||||||
// filterNonUnique([1,2,2,3,4,4,5]) -> [1,3,5]
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
filterNonUnique([1,2,2,3,4,4,5]) // [1,3,5]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Use a new array and concatenate it with the spread input array causing a shallow
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const flatten = arr => [ ].concat(...arr);
|
const flatten = arr => [ ].concat(...arr);
|
||||||
// flatten([1,[2],3,4]) -> [1,2,3,4]
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
flatten([1,[2],3,4]) // [1,2,3,4]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -11,5 +11,8 @@ Omit the second element, `depth` to flatten only to a depth of `1` (single flatt
|
|||||||
const flattenDepth = (arr, depth = 1) =>
|
const flattenDepth = (arr, depth = 1) =>
|
||||||
depth != 1 ? arr.reduce((a, v) => a.concat(Array.isArray(v) ? flattenDepth(v, depth - 1) : v), [])
|
depth != 1 ? arr.reduce((a, v) => a.concat(Array.isArray(v) ? flattenDepth(v, depth - 1) : v), [])
|
||||||
: arr.reduce((a, v) => a.concat(v), []);
|
: arr.reduce((a, v) => a.concat(v), []);
|
||||||
// flattenDepth([1,[2],[[[3],4],5]], 2) -> [1,2,[3],4,5]
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
flattenDepth([1,[2],3,4]) // [1,2,3,4]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,7 +6,9 @@ Return a closure that takes variadic inputs, and splices the last argument to ma
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const flip = fn => (...args) => fn(args.pop(), ...args);
|
const flip = fn => (...args) => fn(args.pop(), ...args);
|
||||||
/*
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
let a = {name: 'John Smith'}
|
let a = {name: 'John Smith'}
|
||||||
let b = {}
|
let b = {}
|
||||||
const mergeFrom = flip(Object.assign)
|
const mergeFrom = flip(Object.assign)
|
||||||
@ -14,5 +16,4 @@ let mergePerson = mergeFrom.bind(null, a)
|
|||||||
mergePerson(b) // == b
|
mergePerson(b) // == b
|
||||||
b = {}
|
b = {}
|
||||||
Object.assign(b, a) // == b
|
Object.assign(b, a) // == b
|
||||||
*/
|
|
||||||
```
|
```
|
||||||
|
|||||||
@ -9,7 +9,10 @@ Omit the second argument to use a default separator of `_`.
|
|||||||
const fromCamelCase = (str, separator = '_') =>
|
const fromCamelCase = (str, separator = '_') =>
|
||||||
str.replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2')
|
str.replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2')
|
||||||
.replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2').toLowerCase();
|
.replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2').toLowerCase();
|
||||||
// fromCamelCase('someDatabaseFieldName', ' ') -> 'some database field name'
|
```
|
||||||
// fromCamelCase('someLabelThatNeedsToBeCamelized', '-') -> 'some-label-that-needs-to-be-camelized'
|
|
||||||
// fromCamelCase('someJavascriptProperty', '_') -> 'some_javascript_property'
|
```js
|
||||||
|
fromCamelCase('someDatabaseFieldName', ' ') // 'some database field name'
|
||||||
|
fromCamelCase('someLabelThatNeedsToBeCamelized', '-') // 'some-label-that-needs-to-be-camelized'
|
||||||
|
fromCamelCase('someJavascriptProperty', '_') // 'some_javascript_property'
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Use `console.debug()` and the `name` property of the passed method to log the me
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const functionName = fn => (console.debug(fn.name), fn);
|
const functionName = fn => (console.debug(fn.name), fn);
|
||||||
// functionName(Math.max) -> max (logged in debug channel of console)
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
functionName(Math.max) // max (logged in debug channel of console)
|
||||||
```
|
```
|
||||||
|
|||||||
@ -8,5 +8,8 @@ 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
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
gcd (8, 36) // 4
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Calculate the difference (in days) between two `Date` objects.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24);
|
const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24);
|
||||||
// getDaysDiffBetweenDates(new Date("2017-12-13"), new Date("2017-12-22")) -> 9
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
getDaysDiffBetweenDates(new Date("2017-12-13"), new Date("2017-12-22")) // 9
|
||||||
```
|
```
|
||||||
|
|||||||
@ -9,5 +9,8 @@ You can omit `el` to use a default value of `window`.
|
|||||||
const getScrollPosition = (el = window) =>
|
const getScrollPosition = (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});
|
||||||
// getScrollPosition() -> {x: 0, y: 200}
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
getScrollPosition() // {x: 0, y: 200}
|
||||||
```
|
```
|
||||||
|
|||||||
@ -7,5 +7,8 @@ Returns lowercased 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"
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
getType(new Set([1,2,3])) // "set"
|
||||||
```
|
```
|
||||||
|
|||||||
@ -10,5 +10,8 @@ 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'}
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
getURLParameters('http://url.com/page?name=Adam&surname=Smith') // {name: 'Adam', surname: 'Smith'}
|
||||||
```
|
```
|
||||||
|
|||||||
@ -9,6 +9,9 @@ Use `Array.reduce()` to create an object, where the keys are produced from the m
|
|||||||
const groupBy = (arr, func) =>
|
const groupBy = (arr, func) =>
|
||||||
arr.map(typeof func === 'function' ? func : val => val[func])
|
arr.map(typeof func === 'function' ? func : val => val[func])
|
||||||
.reduce((acc, val, i) => { acc[val] = (acc[val] || []).concat(arr[i]); return acc; }, {});
|
.reduce((acc, val, i) => { acc[val] = (acc[val] || []).concat(arr[i]); return acc; }, {});
|
||||||
// groupBy([6.1, 4.2, 6.3], Math.floor) -> {4: [4.2], 6: [6.1, 6.3]}
|
```
|
||||||
// groupBy(['one', 'two', 'three'], 'length') -> {3: ['one', 'two'], 5: ['three']}
|
|
||||||
|
```js
|
||||||
|
groupBy([6.1, 4.2, 6.3], Math.floor) // {4: [4.2], 6: [6.1, 6.3]}
|
||||||
|
groupBy(['one', 'two', 'three'], 'length') // {3: ['one', 'two'], 5: ['three']}
|
||||||
```
|
```
|
||||||
|
|||||||
@ -8,5 +8,8 @@ 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
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
hammingDistance(2,3) // 1
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Use `arr[0]` to return the first element of the passed array.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const head = arr => arr[0];
|
const head = arr => arr[0];
|
||||||
// head([1,2,3]) -> 1
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
head([1,2,3]) // 1
|
||||||
```
|
```
|
||||||
|
|||||||
@ -16,7 +16,10 @@ const hexToRGB = hex => {
|
|||||||
((h & (alpha ? 0x0000ff00 : 0x0000ff)) >>> (alpha ? 8 : 0)) +
|
((h & (alpha ? 0x0000ff00 : 0x0000ff)) >>> (alpha ? 8 : 0)) +
|
||||||
(alpha ? `, ${(h & 0x000000ff)}` : '') + ')';
|
(alpha ? `, ${(h & 0x000000ff)}` : '') + ')';
|
||||||
};
|
};
|
||||||
// hexToRGB('#27ae60ff') -> 'rgba(39, 174, 96, 255)'
|
```
|
||||||
// hexToRGB('27ae60') -> 'rgb(39, 174, 96)'
|
|
||||||
// hexToRGB('#fff') -> 'rgb(255, 255, 255)'
|
```js
|
||||||
|
hexToRGB('#27ae60ff') // 'rgba(39, 174, 96, 255)'
|
||||||
|
hexToRGB('27ae60') // 'rgb(39, 174, 96)'
|
||||||
|
hexToRGB('#fff') // 'rgb(255, 255, 255)'
|
||||||
```
|
```
|
||||||
|
|||||||
@ -10,8 +10,11 @@ const inRange = (n, start, end = null) => {
|
|||||||
if (end && start > end) end = [start, start = end][0];
|
if (end && start > end) end = [start, start = end][0];
|
||||||
return (end == null) ? (n >= 0 && n < start) : (n >= start && n < end);
|
return (end == null) ? (n >= 0 && n < start) : (n >= start && n < end);
|
||||||
};
|
};
|
||||||
// inRange(3, 2, 5) -> true
|
```
|
||||||
// inRange(3, 4) -> true
|
|
||||||
// inRange(2, 3, 5) -> false
|
```js
|
||||||
// inrange(3, 2) -> false
|
inRange(3, 2, 5) // true
|
||||||
|
inRange(3, 4) // true
|
||||||
|
inRange(2, 3, 5) // false
|
||||||
|
inrange(3, 2) // false
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Use `arr.slice(0,-1)` to return all but the last element of the array.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const initial = arr => arr.slice(0, -1);
|
const initial = arr => arr.slice(0, -1);
|
||||||
// initial([1,2,3]) -> [1,2]
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
initial([1,2,3]) // [1,2]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Use `Array.map()` to generate h rows where each is a new array of size w initial
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const initialize2DArray = (w, h, val = null) => Array(h).fill().map(() => Array(w).fill(val));
|
const initialize2DArray = (w, h, val = null) => Array(h).fill().map(() => Array(w).fill(val));
|
||||||
// initializeArrayWithRange(2, 2, 0) -> [[0,0], [0,0]]
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
initialize2DArray(2, 2, 0) // [[0,0], [0,0]]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -8,6 +8,9 @@ You can omit `start` to use a default value of `0`.
|
|||||||
```js
|
```js
|
||||||
const initializeArrayWithRange = (end, start = 0) =>
|
const initializeArrayWithRange = (end, start = 0) =>
|
||||||
Array.from({ length: (end + 1) - start }).map((v, i) => i + start);
|
Array.from({ length: (end + 1) - start }).map((v, i) => i + start);
|
||||||
// initializeArrayWithRange(5) -> [0,1,2,3,4,5]
|
```
|
||||||
// initializeArrayWithRange(7, 3) -> [3,4,5,6,7]
|
|
||||||
|
```js
|
||||||
|
initializeArrayWithRange(5) // [0,1,2,3,4,5]
|
||||||
|
initializeArrayWithRange(7, 3) // [3,4,5,6,7]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -7,5 +7,8 @@ You can omit `value` to use a default value of `0`.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const initializeArrayWithValues = (n, value = 0) => Array(n).fill(value);
|
const initializeArrayWithValues = (n, value = 0) => Array(n).fill(value);
|
||||||
// initializeArrayWithValues(5, 2) -> [2,2,2,2,2]
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
initializeArrayWithValues(5, 2) // [2,2,2,2,2]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values co
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const intersection = (a, b) => { const s = new Set(b); return a.filter(x => s.has(x)); };
|
const intersection = (a, b) => { const s = new Set(b); return a.filter(x => s.has(x)); };
|
||||||
// intersection([1,2,3], [4,3,2]) -> [2,3]
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
intersection([1,2,3], [4,3,2]) // [2,3]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -7,7 +7,10 @@ Convert the given number into an array of digits. Use `Math.pow()` to get the ap
|
|||||||
```js
|
```js
|
||||||
const isArmstrongNumber = digits =>
|
const isArmstrongNumber = digits =>
|
||||||
(arr => arr.reduce((a, d) => a + Math.pow(parseInt(d), arr.length), 0) == digits)((digits + '').split(''));
|
(arr => arr.reduce((a, d) => a + Math.pow(parseInt(d), arr.length), 0) == digits)((digits + '').split(''));
|
||||||
// isArmstrongNumber(1634) -> true
|
```
|
||||||
// isArmstrongNumber(371) -> true
|
|
||||||
// isArmstrongNumber(56) -> false
|
```js
|
||||||
|
isArmstrongNumber(1634) // true
|
||||||
|
isArmstrongNumber(371) // true
|
||||||
|
isArmstrongNumber(56) // false
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,6 +6,9 @@ Use `Array.isArray()` to check if a value is classified as an array.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const isArray = val => !!val && Array.isArray(val);
|
const isArray = val => !!val && Array.isArray(val);
|
||||||
// isArray(null) -> false
|
```
|
||||||
// isArray([1]) -> true
|
|
||||||
|
```js
|
||||||
|
isArray(null) // false
|
||||||
|
isArray([1]) // true
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,6 +6,9 @@ Use `typeof` to check if a value is classified as a boolean primitive.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const isBoolean = val => typeof val === 'boolean';
|
const isBoolean = val => typeof val === 'boolean';
|
||||||
// isBoolean(null) -> false
|
```
|
||||||
// isBoolean(false) -> true
|
|
||||||
|
```js
|
||||||
|
isBoolean(null) // false
|
||||||
|
isBoolean(false) // true
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Use the modulo operator (`%`) to check if the remainder is equal to `0`.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const isDivisible = (dividend, divisor) => dividend % divisor === 0;
|
const isDivisible = (dividend, divisor) => dividend % divisor === 0;
|
||||||
// isDivisible(6,3) -> true
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
isDivisible(6,3) // true
|
||||||
```
|
```
|
||||||
|
|||||||
@ -7,5 +7,8 @@ Returns `true` if the number is even, `false` if the number is odd.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const isEven = num => num % 2 === 0;
|
const isEven = num => num % 2 === 0;
|
||||||
// isEven(3) -> false
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
isEven(3) // false
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,6 +6,9 @@ Use `typeof` to check if a value is classified as a function primitive.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const isFunction = val => val && typeof val === 'function';
|
const isFunction = val => val && typeof val === 'function';
|
||||||
// isFunction('x') -> false
|
```
|
||||||
// isFunction(x => x) -> true
|
|
||||||
|
```js
|
||||||
|
isFunction('x') // false
|
||||||
|
isFunction(x => x) // true
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,6 +6,9 @@ Use `typeof` to check if a value is classified as a number primitive.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const isNumber = val => typeof val === 'number';
|
const isNumber = val => typeof val === 'number';
|
||||||
// isNumber('1') -> false
|
```
|
||||||
// isNumber(1) -> true
|
|
||||||
|
```js
|
||||||
|
isNumber('1') // false
|
||||||
|
isNumber(1) // true
|
||||||
```
|
```
|
||||||
@ -11,6 +11,9 @@ const isPrime = num => {
|
|||||||
for (var i = 2; i * i <= boundary; i++) if (num % i == 0) return false;
|
for (var i = 2; i * i <= boundary; i++) if (num % i == 0) return false;
|
||||||
return num >= 2;
|
return num >= 2;
|
||||||
};
|
};
|
||||||
// isPrime(11) -> true
|
```
|
||||||
// isPrime(12) -> false
|
|
||||||
|
```js
|
||||||
|
isPrime(11) // true
|
||||||
|
isPrime(12) // false
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,6 +6,9 @@ Use `typeof` to check if a value is classified as a string primitive.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const isString = val => typeof val === 'string';
|
const isString = val => typeof val === 'string';
|
||||||
// isString(10) -> false
|
```
|
||||||
// isString('10') -> true
|
|
||||||
|
```js
|
||||||
|
isString(10) // false
|
||||||
|
isString('10') // true
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,6 +6,9 @@ Use `typeof` to check if a value is classified as a symbol primitive.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const isSymbol = val => typeof val === 'symbol';
|
const isSymbol = val => typeof val === 'symbol';
|
||||||
// isSymbol('x') -> false
|
```
|
||||||
// isSymbol(Symbol('x')) -> true
|
|
||||||
|
```js
|
||||||
|
isSymbol('x') // false
|
||||||
|
isSymbol(Symbol('x')) // true
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Use `arr.length - 1` to compute the index of the last element of the given array
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const last = arr => arr[arr.length - 1];
|
const last = arr => arr[arr.length - 1];
|
||||||
// last([1,2,3]) -> 3
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
last([1,2,3]) // 3
|
||||||
```
|
```
|
||||||
|
|||||||
@ -10,5 +10,8 @@ const lcm = (x, y) => {
|
|||||||
const gcd = (x, y) => !y ? x : gcd(y, x % y);
|
const gcd = (x, y) => !y ? x : gcd(y, x % y);
|
||||||
return Math.abs(x * y) / (gcd(x, y));
|
return Math.abs(x * y) / (gcd(x, y));
|
||||||
};
|
};
|
||||||
// lcm(12,7) -> 84
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
lcm(12,7) // 84
|
||||||
```
|
```
|
||||||
|
|||||||
@ -7,8 +7,9 @@ Use an anonymous inner function scope to declare an undefined memory space, usin
|
|||||||
```js
|
```js
|
||||||
const mapObject = (arr, fn) =>
|
const mapObject = (arr, fn) =>
|
||||||
(a => (a = [arr, arr.map(fn)], a[0].reduce((acc, val, ind) => (acc[val] = a[1][ind], acc), {})))();
|
(a => (a = [arr, arr.map(fn)], a[0].reduce((acc, val, ind) => (acc[val] = a[1][ind], acc), {})))();
|
||||||
/*
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
const squareIt = arr => mapObject(arr, a => a*a)
|
const squareIt = arr => mapObject(arr, a => a*a)
|
||||||
squareIt([1,2,3]) // { 1: 1, 2: 4, 3: 9 }
|
squareIt([1,2,3]) // { 1: 1, 2: 4, 3: 9 }
|
||||||
*/
|
|
||||||
```
|
```
|
||||||
|
|||||||
@ -10,6 +10,9 @@ 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([0,10,-2,7]) -> 3.5
|
|
||||||
|
```js
|
||||||
|
median([5,6,50,1,-5]) // 5
|
||||||
|
median([0,10,-2,7]) // 3.5
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,6 +6,9 @@ Take a predicate function and apply `not` to it with its arguments.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const negate = func => (...args) => !func(...args);
|
const negate = func => (...args) => !func(...args);
|
||||||
// filter([1, 2, 3, 4, 5, 6], negate(isEven)) -> [1, 3, 5]
|
```
|
||||||
// negate(isOdd)(1) -> false
|
|
||||||
|
```js
|
||||||
|
filter([1, 2, 3, 4, 5, 6], negate(isEven)) // [1, 3, 5]
|
||||||
|
negate(isOdd)(1) // false
|
||||||
```
|
```
|
||||||
|
|||||||
@ -8,6 +8,9 @@ Omit the second argument, `n`, to get the first element of the array.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const nthElement = (arr, n = 0) => (n > 0 ? arr.slice(n, n + 1) : arr.slice(n))[0];
|
const nthElement = (arr, n = 0) => (n > 0 ? arr.slice(n, n + 1) : arr.slice(n))[0];
|
||||||
// nthElement(['a','b','c'],1) -> 'b'
|
```
|
||||||
// nthElement(['a','b','b'],-3) -> 'a'
|
|
||||||
|
```js
|
||||||
|
nthElement(['a','b','c'],1) // 'b'
|
||||||
|
nthElement(['a','b','b'],-3) // 'a'
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ 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}
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
objectFromPairs([['a',1],['b',2]]) // {a: 1, b: 2}
|
||||||
```
|
```
|
||||||
|
|||||||
@ -6,5 +6,8 @@ Use `Object.keys()` and `Array.map()` to iterate over the object's keys and prod
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]);
|
const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]);
|
||||||
// objectToPairs({a: 1, b: 2}) -> [['a',1],['b',2]])
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
objectToPairs({a: 1, b: 2}) // [['a',1],['b',2]])
|
||||||
```
|
```
|
||||||
|
|||||||
@ -16,10 +16,11 @@ const orderBy = (arr, props, orders) =>
|
|||||||
return acc;
|
return acc;
|
||||||
}, 0)
|
}, 0)
|
||||||
);
|
);
|
||||||
/*
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
const users = [{ 'name': 'fred', 'age': 48 },{ 'name': 'barney', 'age': 36 },
|
const users = [{ 'name': 'fred', 'age': 48 },{ 'name': 'barney', 'age': 36 },
|
||||||
{ 'name': 'fred', 'age': 40 },{ 'name': 'barney', 'age': 34 }];
|
{ 'name': 'fred', 'age': 40 },{ 'name': 'barney', 'age': 34 }];
|
||||||
orderby(users, ['name', 'age'], ['asc', 'desc']) -> [{name: 'barney', age: 36}, {name: 'barney', age: 34}, {name: 'fred', age: 48}, {name: 'fred', age: 40}]
|
orderby(users, ['name', 'age'], ['asc', 'desc']) // [{name: 'barney', age: 36}, {name: 'barney', age: 34}, {name: 'fred', age: 48}, {name: 'fred', age: 40}]
|
||||||
orderby(users, ['name', 'age']) -> [{name: 'barney', age: 34}, {name: 'barney', age: 36}, {name: 'fred', age: 40}, {name: 'fred', age: 48}]
|
orderby(users, ['name', 'age']) // [{name: 'barney', age: 34}, {name: 'barney', age: 36}, {name: 'fred', age: 40}, {name: 'fred', age: 48}]
|
||||||
*/
|
|
||||||
```
|
```
|
||||||
|
|||||||
@ -7,8 +7,11 @@ Then, `split('')` into individual characters, `reverse()`, `join('')` and compar
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const palindrome = str => {
|
const palindrome = str => {
|
||||||
const s = str.toLowerCase().replace(/[\W_]/g,'');
|
const s = str.toLowerCase().replace(/[\W_]/g, '');
|
||||||
return s === s.split('').reverse().join('');
|
return s === s.split('').reverse().join('');
|
||||||
}
|
};
|
||||||
// palindrome('taco cat') -> true
|
```
|
||||||
```
|
|
||||||
|
```js
|
||||||
|
palindrome('taco cat') // true
|
||||||
|
```
|
||||||
|
|||||||
@ -6,6 +6,9 @@ Use `Array.reduce()` to calculate how many numbers are below the value and how m
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const percentile = (arr, val) =>
|
const percentile = (arr, val) =>
|
||||||
100 * arr.reduce((acc,v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), 0) / arr.length;
|
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
|
```
|
||||||
```
|
|
||||||
|
```js
|
||||||
|
percentile([1,2,3,4,5,6,7,8,9,10], 6) // 55
|
||||||
|
```
|
||||||
|
|||||||
@ -7,5 +7,8 @@ Use `Array.reduce()` to convert the filtered/picked keys back to an object with
|
|||||||
```js
|
```js
|
||||||
const pick = (obj, arr) =>
|
const pick = (obj, arr) =>
|
||||||
arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {});
|
arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {});
|
||||||
// pick({ 'a': 1, 'b': '2', 'c': 3 }, ['a', 'c']) -> { 'a': 1, 'c': 3 }
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
pick({ 'a': 1, 'b': '2', 'c': 3 }, ['a', 'c']) // { 'a': 1, 'c': 3 }
|
||||||
```
|
```
|
||||||
|
|||||||
@ -7,10 +7,11 @@ The first (leftmost) function can accept one or more arguments; the remaining fu
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));
|
const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));
|
||||||
/*
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
const add5 = x => x + 5
|
const add5 = x => x + 5
|
||||||
const multiply = (x, y) => x * y
|
const multiply = (x, y) => x * y
|
||||||
const multiplyAndAdd5 = pipeFunctions(multiply, add5)
|
const multiplyAndAdd5 = pipeFunctions(multiply, add5)
|
||||||
multiplyAndAdd5(5, 2) -> 15
|
multiplyAndAdd5(5, 2) // 15
|
||||||
*/
|
|
||||||
```
|
```
|
||||||
|
|||||||
@ -7,5 +7,8 @@ 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]]
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
powerset([1,2]) // [[], [1], [2], [2,1]]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -12,5 +12,8 @@ const primes = num => {
|
|||||||
numsTillSqroot.forEach(x => arr = arr.filter(y => ((y % x) !== 0) || (y == x)));
|
numsTillSqroot.forEach(x => arr = arr.filter(y => ((y % x) !== 0) || (y == x)));
|
||||||
return arr;
|
return arr;
|
||||||
};
|
};
|
||||||
// primes(10) -> [2,3,5,7]
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
primes(10) // [2,3,5,7]
|
||||||
```
|
```
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user