Merge branch 'master' of https://github.com/Chalarangelo/30-seconds-of-code into patch-1
This commit is contained in:
42
README.md
42
README.md
@ -238,7 +238,7 @@ Use ES6 `Set` and the `...rest` operator to discard all duplicated values.
|
||||
|
||||
```js
|
||||
const distinctValuesOfArray = arr => [...new Set(arr)];
|
||||
// unique([1,2,2,3,4,4,5]) -> [1,2,3,4,5]
|
||||
// distinctValuesOfArray([1,2,2,3,4,4,5]) -> [1,2,3,4,5]
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
@ -268,7 +268,7 @@ Use `Array.filter()` to create a new array that contains every nth element of a
|
||||
|
||||
```js
|
||||
const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === 0);
|
||||
// everynth([1,2,3,4,5,6], 2) -> [ 1, 3, 5 ]
|
||||
// everyNth([1,2,3,4,5,6], 2) -> [ 1, 3, 5 ]
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
@ -370,7 +370,7 @@ You can omit `start` to use a default value of `0`.
|
||||
```js
|
||||
const initializeArrayWithRange = (end, start = 0) =>
|
||||
Array.from({ length: end - start }).map((v, i) => i + start);
|
||||
// initializeArrayRange(5) -> [0,1,2,3,4]
|
||||
// initializeArrayWithRange(5) -> [0,1,2,3,4]
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
@ -384,7 +384,7 @@ You can omit `value` to use a default value of `0`.
|
||||
|
||||
```js
|
||||
const initializeArrayWithValues = (n, value = 0) => Array(n).fill(value);
|
||||
// initializeArray(5, 2) -> [2,2,2,2,2]
|
||||
// initializeArrayWithValues(5, 2) -> [2,2,2,2,2]
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
@ -690,7 +690,7 @@ You can omit `el` to use a default value of `window`.
|
||||
const getScrollPosition = (el = window) =>
|
||||
({x: (el.pageXOffset !== undefined) ? el.pageXOffset : el.scrollLeft,
|
||||
y: (el.pageYOffset !== undefined) ? el.pageYOffset : el.scrollTop});
|
||||
// getScrollPos() -> {x: 0, y: 200}
|
||||
// getScrollPosition() -> {x: 0, y: 200}
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
@ -707,7 +707,7 @@ 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'}
|
||||
// getURLParameters('http://url.com/page?name=Adam&surname=Smith') -> {name: 'Adam', surname: 'Smith'}
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
@ -772,7 +772,7 @@ const JSONToDate = arr => {
|
||||
const dt = new Date(parseInt(arr.toString().substr(6)));
|
||||
return `${ dt.getDate() }/${ dt.getMonth() + 1 }/${ dt.getFullYear() }`
|
||||
};
|
||||
// jsonToDate(/Date(1489525200000)/) -> "14/3/2017"
|
||||
// JSONToDate(/Date(1489525200000)/) -> "14/3/2017"
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
@ -876,7 +876,7 @@ const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)
|
||||
/*
|
||||
const add5 = x => x + 5
|
||||
const multiply = (x, y) => x * y
|
||||
const multiplyAndAdd5 = pipe(multiply, add5)
|
||||
const multiplyAndAdd5 = pipeFunctions(multiply, add5)
|
||||
multiplyAndAdd5(5, 2) -> 15
|
||||
*/
|
||||
```
|
||||
@ -914,7 +914,7 @@ Use `Array.reduce()` to create a promise chain, where each promise returns the n
|
||||
```js
|
||||
const runPromisesInSeries = 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
|
||||
// runPromisesInSeries([() => delay(1000), () => delay(2000)]) -> executes each promise sequentially, taking a total of 3 seconds to complete
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
@ -947,7 +947,7 @@ Use `Array.reduce()` to add each value to an accumulator, initialized with a val
|
||||
|
||||
```js
|
||||
const arrayAverage = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length;
|
||||
// average([1,2,3]) -> 2
|
||||
// arrayAverage([1,2,3]) -> 2
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
@ -960,7 +960,7 @@ Use `Array.reduce()` to add each value to an accumulator, initialized with a val
|
||||
|
||||
```js
|
||||
const arraySum = arr => arr.reduce((acc, val) => acc + val, 0);
|
||||
// sum([1,2,3,4]) -> 10
|
||||
// arraySum([1,2,3,4]) -> 10
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
@ -1197,7 +1197,7 @@ Use `Math.random()` to generate a random value, map it to the desired range usin
|
||||
|
||||
```js
|
||||
const randomNumberInRange = (min, max) => Math.random() * (max - min) + min;
|
||||
// randomInRange(2,10) -> 6.0211363285087005
|
||||
// randomNumberInRange(2,10) -> 6.0211363285087005
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
@ -1254,7 +1254,7 @@ const speechSynthesis = message => {
|
||||
msg.voice = window.speechSynthesis.getVoices()[0];
|
||||
window.speechSynthesis.speak(msg);
|
||||
};
|
||||
// speak('Hello, World') -> plays the message
|
||||
// speechSynthesis('Hello, World') -> plays the message
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
@ -1269,7 +1269,7 @@ Use `fs.writeFile()`, template literals and `JSON.stringify()` to write a `json`
|
||||
```js
|
||||
const fs = require('fs');
|
||||
const JSONToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2))
|
||||
// jsonToFile({test: "is passed"}, 'testJsonFile') -> writes the object to 'testJsonFile.json'
|
||||
// JSONToFile({test: "is passed"}, 'testJsonFile') -> writes the object to 'testJsonFile.json'
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
@ -1291,7 +1291,7 @@ const readFileLines = filename => fs.readFileSync(filename).toString('UTF8').spl
|
||||
line2
|
||||
line3
|
||||
___________________________
|
||||
let arr = readFileToArray('test.txt')
|
||||
let arr = readFileLines('test.txt')
|
||||
console.log(arr) // -> ['line1', 'line2', 'line3']
|
||||
*/
|
||||
```
|
||||
@ -1317,7 +1317,7 @@ const cleanObj = (obj, keysToKeep = [], childIndicator) => {
|
||||
})
|
||||
}
|
||||
/*
|
||||
testObj = {a: 1, b: 2, children: {a: 1, b: 2}}
|
||||
const testObj = {a: 1, b: 2, children: {a: 1, b: 2}}
|
||||
cleanObj(testObj, ["a"],"children")
|
||||
console.log(testObj)// { a: 1, children : { a: 1}}
|
||||
*/
|
||||
@ -1504,7 +1504,7 @@ Return the string truncated to the desired length, with `...` appended to the en
|
||||
```js
|
||||
const truncateString = (str, num) =>
|
||||
str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str;
|
||||
// truncate('boomerang', 7) -> 'boom...'
|
||||
// truncateString('boomerang', 7) -> 'boom...'
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
@ -1519,8 +1519,8 @@ Use `Array.map()`, `split()` and `Array.join()` to join the mapped array for con
|
||||
```js
|
||||
const extendHex = shortHex =>
|
||||
'#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split('').map(x => x+x).join('')
|
||||
// convertHex('#03f') -> '#0033ff'
|
||||
// convertHex('05a') -> '#0055aa'
|
||||
// extendHex('#03f') -> '#0033ff'
|
||||
// extendHex('05a') -> '#0055aa'
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
@ -1651,7 +1651,7 @@ Convert given RGB parameters to hexadecimal string using bitwise left-shift oper
|
||||
|
||||
```js
|
||||
const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
|
||||
// rgbToHex(255, 165, 1) -> 'ffa501'
|
||||
// RGBToHex(255, 165, 1) -> 'ffa501'
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
@ -1704,7 +1704,7 @@ const UUIDGenerator = () =>
|
||||
([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'
|
||||
// UUIDGenerator() -> '7982fcfe-5721-4632-bede-6000885be57d'
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
|
||||
@ -23,7 +23,7 @@
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<h1 class="logo" style="margin-top: -1rem; text-align:center;"><img src="favicon.png" style="height: 4rem;"/><span style="position:relative; top: -1rem;"> 30 seconds of code</span></h1>
|
||||
<h1 class="logo" style="margin-top: -1rem; text-align:center;"><a style="text-decoration:none;color:black" href="https://github.com/Chalarangelo/30-seconds-of-code"><img src="favicon.png" style="height: 4rem;"/><span style="position:relative; top: -1rem;"> 30 seconds of code</span></a></h1>
|
||||
<label for="doc-drawer-checkbox" class="button drawer-toggle" style="position: absolute; right: 0; top: 0;"></label>
|
||||
</header>
|
||||
<div class="row" style="height: calc(100vh - 3.5625rem);overflow: hidden;">
|
||||
@ -207,7 +207,7 @@ Recursively flatten each element that is an array.</p>
|
||||
<p>Returns all the distinct values of an array.</p>
|
||||
<p>Use ES6 <code>Set</code> and the <code>...rest</code> operator to discard all duplicated values.</p>
|
||||
<pre><code class="language-js">const distinctValuesOfArray = arr => [...new Set(arr)];
|
||||
// unique([1,2,2,3,4,4,5]) -> [1,2,3,4,5]
|
||||
// distinctValuesOfArray([1,2,2,3,4,4,5]) -> [1,2,3,4,5]
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="dropelements">dropElements</h3></div><div class="section double-padded">
|
||||
<p>Removes elements in an array until the passed function returns <code>true</code>. Returns the remaining elements in the array.</p>
|
||||
@ -223,7 +223,7 @@ Returns the remaining elements.</p>
|
||||
<p>Returns every nth element in an array.</p>
|
||||
<p>Use <code>Array.filter()</code> to create a new array that contains every nth element of a given array.</p>
|
||||
<pre><code class="language-js">const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === 0);
|
||||
// everynth([1,2,3,4,5,6], 2) -> [ 1, 3, 5 ]
|
||||
// everyNth([1,2,3,4,5,6], 2) -> [ 1, 3, 5 ]
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="filternonunique">filterNonUnique</h3></div><div class="section double-padded">
|
||||
<p>Filters out the non-unique values in an array.</p>
|
||||
@ -276,14 +276,14 @@ Use <code>Array.reduce()</code> to create an object, where the keys are produced
|
||||
You can omit <code>start</code> to use a default value of <code>0</code>.</p>
|
||||
<pre><code class="language-js">const initializeArrayWithRange = (end, start = 0) =>
|
||||
Array.from({ length: end - start }).map((v, i) => i + start);
|
||||
// initializeArrayRange(5) -> [0,1,2,3,4]
|
||||
// initializeArrayWithRange(5) -> [0,1,2,3,4]
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="initializearraywithvalues">initializeArrayWithValues</h3></div><div class="section double-padded">
|
||||
<p>Initializes and fills an array with the specified values.</p>
|
||||
<p>Use <code>Array(n)</code> to create an array of the desired length, <code>fill(v)</code> to fill it with the desired values.
|
||||
You can omit <code>value</code> to use a default value of <code>0</code>.</p>
|
||||
<pre><code class="language-js">const initializeArrayWithValues = (n, value = 0) => Array(n).fill(value);
|
||||
// initializeArray(5, 2) -> [2,2,2,2,2]
|
||||
// initializeArrayWithValues(5, 2) -> [2,2,2,2,2]
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="intersection">intersection</h3></div><div class="section double-padded">
|
||||
<p>Returns a list of elements that exist in both arrays.</p>
|
||||
@ -449,7 +449,7 @@ You can omit <code>el</code> to use a default value of <code>window</code>.</p>
|
||||
<pre><code class="language-js">const getScrollPosition = (el = window) =>
|
||||
({x: (el.pageXOffset !== undefined) ? el.pageXOffset : el.scrollLeft,
|
||||
y: (el.pageYOffset !== undefined) ? el.pageYOffset : el.scrollTop});
|
||||
// getScrollPos() -> {x: 0, y: 200}
|
||||
// getScrollPosition() -> {x: 0, y: 200}
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="geturlparameters">getURLParameters</h3></div><div class="section double-padded">
|
||||
<p>Returns an object containing the parameters of the current URL.</p>
|
||||
@ -459,7 +459,7 @@ Pass <code>location.search</code> as the argument to apply to the current <code>
|
||||
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'}
|
||||
// getURLParameters('http://url.com/page?name=Adam&surname=Smith') -> {name: 'Adam', surname: 'Smith'}
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="redirect">redirect</h3></div><div class="section double-padded">
|
||||
<p>Redirects to a specified URL.</p>
|
||||
@ -496,7 +496,7 @@ Scroll by a fraction of the distance from top. Use <code>window.requestAnimation
|
||||
const dt = new Date(parseInt(arr.toString().substr(6)));
|
||||
return `${ dt.getDate() }/${ dt.getMonth() + 1 }/${ dt.getFullYear() }`
|
||||
};
|
||||
// jsonToDate(/Date(1489525200000)/) -> "14/3/2017"
|
||||
// JSONToDate(/Date(1489525200000)/) -> "14/3/2017"
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="toenglishdate">toEnglishDate</h3></div><div class="section double-padded">
|
||||
<p>Converts a date from American format to English format.</p>
|
||||
@ -558,7 +558,7 @@ The first (leftmost) function can accept one or more arguments; the remaining fu
|
||||
/*
|
||||
const add5 = x => x + 5
|
||||
const multiply = (x, y) => x * y
|
||||
const multiplyAndAdd5 = pipe(multiply, add5)
|
||||
const multiplyAndAdd5 = pipeFunctions(multiply, add5)
|
||||
multiplyAndAdd5(5, 2) -> 15
|
||||
*/
|
||||
</code></pre>
|
||||
@ -581,7 +581,7 @@ Use the <code>...rest</code> operator to pass in all the parameters.</p>
|
||||
<p>Use <code>Array.reduce()</code> to create a promise chain, where each promise returns the next promise when resolved.</p>
|
||||
<pre><code class="language-js">const runPromisesInSeries = 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
|
||||
// runPromisesInSeries([() => delay(1000), () => delay(2000)]) -> executes each promise sequentially, taking a total of 3 seconds to complete
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="sleep">sleep</h3></div><div class="section double-padded">
|
||||
<p>Delays the execution of an asynchronous function.</p>
|
||||
@ -600,13 +600,13 @@ async function sleepyWork() {
|
||||
<p>Returns the average of an array of numbers.</p>
|
||||
<p>Use <code>Array.reduce()</code> to add each value to an accumulator, initialized with a value of <code>0</code>, divide by the <code>length</code> of the array.</p>
|
||||
<pre><code class="language-js">const arrayAverage = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length;
|
||||
// average([1,2,3]) -> 2
|
||||
// arrayAverage([1,2,3]) -> 2
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="arraysum">arraySum</h3></div><div class="section double-padded">
|
||||
<p>Returns the sum of an array of numbers.</p>
|
||||
<p>Use <code>Array.reduce()</code> to add each value to an accumulator, initialized with a value of <code>0</code>.</p>
|
||||
<pre><code class="language-js">const arraySum = arr => arr.reduce((acc, val) => acc + val, 0);
|
||||
// sum([1,2,3,4]) -> 10
|
||||
// arraySum([1,2,3,4]) -> 10
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="collatz">collatz</h3></div><div class="section double-padded">
|
||||
<p>Applies the Collatz algorithm.</p>
|
||||
@ -731,7 +731,7 @@ Then, <code>split('')</code> into individual characters, <code>reverse()</code>,
|
||||
<p>Returns a random number in the specified range.</p>
|
||||
<p>Use <code>Math.random()</code> to generate a random value, map it to the desired range using multiplication.</p>
|
||||
<pre><code class="language-js">const randomNumberInRange = (min, max) => Math.random() * (max - min) + min;
|
||||
// randomInRange(2,10) -> 6.0211363285087005
|
||||
// randomNumberInRange(2,10) -> 6.0211363285087005
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="round">round</h3></div><div class="section double-padded">
|
||||
<p>Rounds a number to a specified amount of digits.</p>
|
||||
@ -766,7 +766,7 @@ Use <code>window.speechSynthesis.speak()</code> to play the message.</p>
|
||||
msg.voice = window.speechSynthesis.getVoices()[0];
|
||||
window.speechSynthesis.speak(msg);
|
||||
};
|
||||
// speak('Hello, World') -> plays the message
|
||||
// speechSynthesis('Hello, World') -> plays the message
|
||||
</code></pre>
|
||||
</div></div><br/><h2 style="text-align:center;">Node</h2>
|
||||
<div class="card fluid"><div class="section double-padded"><h3 id="jsontofile">JSONToFile</h3></div><div class="section double-padded">
|
||||
@ -774,7 +774,7 @@ Use <code>window.speechSynthesis.speak()</code> to play the message.</p>
|
||||
<p>Use <code>fs.writeFile()</code>, template literals and <code>JSON.stringify()</code> to write a <code>json</code> object to a <code>.json</code> file.</p>
|
||||
<pre><code class="language-js">const fs = require('fs');
|
||||
const JSONToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2))
|
||||
// jsonToFile({test: "is passed"}, 'testJsonFile') -> writes the object to 'testJsonFile.json'
|
||||
// JSONToFile({test: "is passed"}, 'testJsonFile') -> writes the object to 'testJsonFile.json'
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="readfilelines">readFileLines</h3></div><div class="section double-padded">
|
||||
<p>Returns an array of lines from the specified file.</p>
|
||||
@ -789,7 +789,7 @@ contents of test.txt :
|
||||
line2
|
||||
line3
|
||||
___________________________
|
||||
let arr = readFileToArray('test.txt')
|
||||
let arr = readFileLines('test.txt')
|
||||
console.log(arr) // -> ['line1', 'line2', 'line3']
|
||||
*/
|
||||
</code></pre>
|
||||
@ -808,7 +808,7 @@ also if you give it a special key(<code>childIndicator</code>) it will search de
|
||||
})
|
||||
}
|
||||
/*
|
||||
testObj = {a: 1, b: 2, children: {a: 1, b: 2}}
|
||||
const testObj = {a: 1, b: 2, children: {a: 1, b: 2}}
|
||||
cleanObj(testObj, ["a"],"children")
|
||||
console.log(testObj)// { a: 1, children : { a: 1}}
|
||||
*/
|
||||
@ -911,7 +911,7 @@ Combine characters to get a string using <code>join('')</code>.</p>
|
||||
Return the string truncated to the desired length, with <code>...</code> appended to the end or the original string.</p>
|
||||
<pre><code class="language-js">const truncateString = (str, num) =>
|
||||
str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str;
|
||||
// truncate('boomerang', 7) -> 'boom...'
|
||||
// truncateString('boomerang', 7) -> 'boom...'
|
||||
</code></pre>
|
||||
</div></div><br/><h2 style="text-align:center;">Utility</h2>
|
||||
<div class="card fluid"><div class="section double-padded"><h3 id="extendhex">extendHex</h3></div><div class="section double-padded">
|
||||
@ -920,8 +920,8 @@ Return the string truncated to the desired length, with <code>...</code> appende
|
||||
<code>Array.slice()</code> is used to remove <code>#</code> from string start since it's added once.</p>
|
||||
<pre><code class="language-js">const extendHex = shortHex =>
|
||||
'#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split('').map(x => x+x).join('')
|
||||
// convertHex('#03f') -> '#0033ff'
|
||||
// convertHex('05a') -> '#0055aa'
|
||||
// extendHex('#03f') -> '#0033ff'
|
||||
// extendHex('05a') -> '#0055aa'
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="gettype">getType</h3></div><div class="section double-padded">
|
||||
<p>Returns the native type of a value.</p>
|
||||
@ -934,12 +934,12 @@ Return the string truncated to the desired length, with <code>...</code> appende
|
||||
<p>Converts a colorcode to a <code>rgb()</code> string.</p>
|
||||
<p>Use bitwise right-shift operator and mask bits with <code>&</code> (and) operator to convert a hexadecimal color code (prefixed with <code>#</code>) to a string with the RGB values. In case it's a 3-digit-colorcode, do the same with the 6-digit-colorcode extended by the extendHex() function (ref. <code>extendHex</code> snippet)</p>
|
||||
<pre><code class="language-js">const hexToRgb = hex => {
|
||||
const extendHex = shortHex =>
|
||||
const extendHex = shortHex =>
|
||||
'#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split('').map(x => x+x).join('');
|
||||
return hex.slice(1).length==3 ?
|
||||
return hex.slice(1).length==3 ?
|
||||
`rgb(${parseInt(extendHex(hex).slice(1), 16) >> 16}, ${(parseInt(extendHex(hex).slice(1), 16) & 0x00ff00) >> 8}, ${parseInt(extendHex(hex).slice(1), 16) & 0x0000ff})`:
|
||||
`rgb(${parseInt(hex.slice(1), 16) >> 16}, ${(parseInt(hex.slice(1), 16) & 0x00ff00) >> 8}, ${parseInt(hex.slice(1), 16) & 0x0000ff})`;
|
||||
}
|
||||
}
|
||||
// hexToRgb('#27ae60') -> 'rgb(39, 174, 96)'
|
||||
// hexToRgb('#acd') -> 'rgb(170, 204, 221)'
|
||||
</code></pre>
|
||||
@ -989,7 +989,7 @@ Return the string truncated to the desired length, with <code>...</code> appende
|
||||
<p>Converts the values of RGB components to a colorcode.</p>
|
||||
<p>Convert given RGB parameters to hexadecimal string using bitwise left-shift operator (<code><<</code>) and <code>toString(16)</code>, then <code>padStart(6,'0')</code> to get a 6-digit hexadecimal value.</p>
|
||||
<pre><code class="language-js">const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
|
||||
// rgbToHex(255, 165, 1) -> 'ffa501'
|
||||
// RGBToHex(255, 165, 1) -> 'ffa501'
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="timetaken">timeTaken</h3></div><div class="section double-padded">
|
||||
<p>Measures the time taken by a function to execute.</p>
|
||||
@ -1021,7 +1021,7 @@ If digit is found in teens pattern, use teens ordinal.</p>
|
||||
([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'
|
||||
// UUIDGenerator() -> '7982fcfe-5721-4632-bede-6000885be57d'
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="validateemail">validateEmail</h3></div><div class="section double-padded">
|
||||
<p>Returns <code>true</code> if the given string is a valid email, <code>false</code> otherwise.</p>
|
||||
@ -1042,7 +1042,8 @@ Use <code>Number()</code> to check if the coercion holds.</p>
|
||||
</div></div><br/>
|
||||
<footer><p><strong>30 seconds of code</strong> is licensed under the <a href="https://github.com/Chalarangelo/30-seconds-of-code/blob/master/LICENSE">CC0-1.0</a> license.<br/>Icons made by <a href="https://www.flaticon.com/authors/smashicons">Smashicons</a> from <a href="https://www.flaticon.com/">www.flaticon.com</a> is licensed by <a href="http://creativecommons.org/licenses/by/3.0/">CC 3.0 BY</a>.</p></footer>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
<script src="prism.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
@ -9,5 +9,5 @@ const JSONToDate = arr => {
|
||||
const dt = new Date(parseInt(arr.toString().substr(6)));
|
||||
return `${ dt.getDate() }/${ dt.getMonth() + 1 }/${ dt.getFullYear() }`
|
||||
};
|
||||
// jsonToDate(/Date(1489525200000)/) -> "14/3/2017"
|
||||
// JSONToDate(/Date(1489525200000)/) -> "14/3/2017"
|
||||
```
|
||||
|
||||
@ -7,5 +7,5 @@ Use `fs.writeFile()`, template literals and `JSON.stringify()` to write a `json`
|
||||
```js
|
||||
const fs = require('fs');
|
||||
const JSONToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2))
|
||||
// jsonToFile({test: "is passed"}, 'testJsonFile') -> writes the object to 'testJsonFile.json'
|
||||
// JSONToFile({test: "is passed"}, 'testJsonFile') -> writes the object to 'testJsonFile.json'
|
||||
```
|
||||
|
||||
@ -6,5 +6,5 @@ Convert given RGB parameters to hexadecimal string using bitwise left-shift oper
|
||||
|
||||
```js
|
||||
const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
|
||||
// rgbToHex(255, 165, 1) -> 'ffa501'
|
||||
// RGBToHex(255, 165, 1) -> 'ffa501'
|
||||
```
|
||||
|
||||
@ -9,5 +9,5 @@ const UUIDGenerator = () =>
|
||||
([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'
|
||||
// UUIDGenerator() -> '7982fcfe-5721-4632-bede-6000885be57d'
|
||||
```
|
||||
|
||||
@ -6,5 +6,5 @@ Use `Array.reduce()` to add each value to an accumulator, initialized with a val
|
||||
|
||||
```js
|
||||
const arrayAverage = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length;
|
||||
// average([1,2,3]) -> 2
|
||||
// arrayAverage([1,2,3]) -> 2
|
||||
```
|
||||
|
||||
@ -6,5 +6,5 @@ Use `Array.reduce()` to add each value to an accumulator, initialized with a val
|
||||
|
||||
```js
|
||||
const arraySum = arr => arr.reduce((acc, val) => acc + val, 0);
|
||||
// sum([1,2,3,4]) -> 10
|
||||
// arraySum([1,2,3,4]) -> 10
|
||||
```
|
||||
|
||||
@ -16,7 +16,7 @@ const cleanObj = (obj, keysToKeep = [], childIndicator) => {
|
||||
})
|
||||
}
|
||||
/*
|
||||
testObj = {a: 1, b: 2, children: {a: 1, b: 2}}
|
||||
const testObj = {a: 1, b: 2, children: {a: 1, b: 2}}
|
||||
cleanObj(testObj, ["a"],"children")
|
||||
console.log(testObj)// { a: 1, children : { a: 1}}
|
||||
*/
|
||||
|
||||
@ -6,5 +6,5 @@ Use ES6 `Set` and the `...rest` operator to discard all duplicated values.
|
||||
|
||||
```js
|
||||
const distinctValuesOfArray = arr => [...new Set(arr)];
|
||||
// unique([1,2,2,3,4,4,5]) -> [1,2,3,4,5]
|
||||
// distinctValuesOfArray([1,2,2,3,4,4,5]) -> [1,2,3,4,5]
|
||||
```
|
||||
|
||||
@ -6,5 +6,5 @@ Use `Array.filter()` to create a new array that contains every nth element of a
|
||||
|
||||
```js
|
||||
const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === 0);
|
||||
// everynth([1,2,3,4,5,6], 2) -> [ 1, 3, 5 ]
|
||||
// everyNth([1,2,3,4,5,6], 2) -> [ 1, 3, 5 ]
|
||||
```
|
||||
|
||||
@ -7,6 +7,6 @@ Use `Array.map()`, `split()` and `Array.join()` to join the mapped array for con
|
||||
```js
|
||||
const extendHex = shortHex =>
|
||||
'#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split('').map(x => x+x).join('')
|
||||
// convertHex('#03f') -> '#0033ff'
|
||||
// convertHex('05a') -> '#0055aa'
|
||||
// extendHex('#03f') -> '#0033ff'
|
||||
// extendHex('05a') -> '#0055aa'
|
||||
```
|
||||
|
||||
@ -9,5 +9,5 @@ You can omit `el` to use a default value of `window`.
|
||||
const getScrollPosition = (el = window) =>
|
||||
({x: (el.pageXOffset !== undefined) ? el.pageXOffset : el.scrollLeft,
|
||||
y: (el.pageYOffset !== undefined) ? el.pageYOffset : el.scrollTop});
|
||||
// getScrollPos() -> {x: 0, y: 200}
|
||||
// getScrollPosition() -> {x: 0, y: 200}
|
||||
```
|
||||
|
||||
@ -10,5 +10,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'}
|
||||
// getURLParameters('http://url.com/page?name=Adam&surname=Smith') -> {name: 'Adam', surname: 'Smith'}
|
||||
```
|
||||
|
||||
@ -8,5 +8,5 @@ You can omit `start` to use a default value of `0`.
|
||||
```js
|
||||
const initializeArrayWithRange = (end, start = 0) =>
|
||||
Array.from({ length: end - start }).map((v, i) => i + start);
|
||||
// initializeArrayRange(5) -> [0,1,2,3,4]
|
||||
// initializeArrayWithRange(5) -> [0,1,2,3,4]
|
||||
```
|
||||
|
||||
@ -7,5 +7,5 @@ You can omit `value` to use a default value of `0`.
|
||||
|
||||
```js
|
||||
const initializeArrayWithValues = (n, value = 0) => Array(n).fill(value);
|
||||
// initializeArray(5, 2) -> [2,2,2,2,2]
|
||||
// initializeArrayWithValues(5, 2) -> [2,2,2,2,2]
|
||||
```
|
||||
|
||||
@ -10,7 +10,7 @@ const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)
|
||||
/*
|
||||
const add5 = x => x + 5
|
||||
const multiply = (x, y) => x * y
|
||||
const multiplyAndAdd5 = pipe(multiply, add5)
|
||||
const multiplyAndAdd5 = pipeFunctions(multiply, add5)
|
||||
multiplyAndAdd5(5, 2) -> 15
|
||||
*/
|
||||
```
|
||||
|
||||
@ -6,5 +6,5 @@ Use `Math.random()` to generate a random value, map it to the desired range usin
|
||||
|
||||
```js
|
||||
const randomNumberInRange = (min, max) => Math.random() * (max - min) + min;
|
||||
// randomInRange(2,10) -> 6.0211363285087005
|
||||
// randomNumberInRange(2,10) -> 6.0211363285087005
|
||||
```
|
||||
|
||||
@ -15,7 +15,7 @@ const readFileLines = filename => fs.readFileSync(filename).toString('UTF8').spl
|
||||
line2
|
||||
line3
|
||||
___________________________
|
||||
let arr = readFileToArray('test.txt')
|
||||
let arr = readFileLines('test.txt')
|
||||
console.log(arr) // -> ['line1', 'line2', 'line3']
|
||||
*/
|
||||
```
|
||||
|
||||
@ -7,5 +7,5 @@ Use `Array.reduce()` to create a promise chain, where each promise returns the n
|
||||
```js
|
||||
const runPromisesInSeries = 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
|
||||
// runPromisesInSeries([() => delay(1000), () => delay(2000)]) -> executes each promise sequentially, taking a total of 3 seconds to complete
|
||||
```
|
||||
|
||||
@ -13,5 +13,5 @@ const speechSynthesis = message => {
|
||||
msg.voice = window.speechSynthesis.getVoices()[0];
|
||||
window.speechSynthesis.speak(msg);
|
||||
};
|
||||
// speak('Hello, World') -> plays the message
|
||||
// speechSynthesis('Hello, World') -> plays the message
|
||||
```
|
||||
|
||||
@ -8,5 +8,5 @@ Return the string truncated to the desired length, with `...` appended to the en
|
||||
```js
|
||||
const truncateString = (str, num) =>
|
||||
str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str;
|
||||
// truncate('boomerang', 7) -> 'boom...'
|
||||
// truncateString('boomerang', 7) -> 'boom...'
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user