Merge branch 'master' of https://github.com/Chalarangelo/30-seconds-of-code
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@ -3,3 +3,4 @@ currentSnippet\.js
|
||||
*.md.temp.js
|
||||
.idea
|
||||
test.sh
|
||||
dist/
|
||||
|
||||
126
README.md
126
README.md
@ -69,6 +69,7 @@
|
||||
* [`arrayToHtmlList`](#arraytohtmllist)
|
||||
* [`bottomVisible`](#bottomvisible)
|
||||
* [`currentURL`](#currenturl)
|
||||
* [`detectDeviceType`](#detectdevicetype)
|
||||
* [`elementIsVisibleInViewport`](#elementisvisibleinviewport)
|
||||
* [`getScrollPosition`](#getscrollposition)
|
||||
* [`getURLParameters`](#geturlparameters)
|
||||
@ -90,6 +91,9 @@
|
||||
* [`runPromisesInSeries`](#runpromisesinseries)
|
||||
* [`sleep`](#sleep)
|
||||
|
||||
### Logic
|
||||
* [`negate`](#negate)
|
||||
|
||||
### Math
|
||||
* [`arrayAverage`](#arrayaverage)
|
||||
* [`arraySum`](#arraysum)
|
||||
@ -142,9 +146,12 @@
|
||||
* [`countVowels`](#countvowels)
|
||||
* [`escapeRegExp`](#escaperegexp)
|
||||
* [`fromCamelCase`](#fromcamelcase)
|
||||
* [`repeatString`](#repeatstring)
|
||||
* [`reverseString`](#reversestring)
|
||||
* [`sortCharactersInString`](#sortcharactersinstring)
|
||||
* [`toCamelCase`](#tocamelcase)
|
||||
* [`toKebabCase`](#tokebabcase)
|
||||
* [`toSnakeCase`](#tosnakecase)
|
||||
* [`truncateString`](#truncatestring)
|
||||
* [`words`](#words)
|
||||
|
||||
@ -160,6 +167,7 @@
|
||||
* [`isNumber`](#isnumber)
|
||||
* [`isString`](#isstring)
|
||||
* [`isSymbol`](#issymbol)
|
||||
* [`randomHexColorCode`](#randomhexcolorcode)
|
||||
* [`RGBToHex`](#rgbtohex)
|
||||
* [`timeTaken`](#timetaken)
|
||||
* [`toDecimalMark`](#todecimalmark)
|
||||
@ -442,12 +450,12 @@ const dropElements = (arr, func) => {
|
||||
|
||||
### dropRight
|
||||
|
||||
Returns a new array with `n` elements removed from the right
|
||||
Returns a new array with `n` elements removed from the right.
|
||||
|
||||
Check if `n` is shorter than the given array and use `Array.slice()` to slice it accordingly or return an empty array.
|
||||
Use `Array.slice()` to slice the remove the specified number of elements from the right.
|
||||
|
||||
```js
|
||||
const dropRight = (arr, n = 1) => n < arr.length ? arr.slice(0, arr.length - 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) -> []
|
||||
@ -973,6 +981,20 @@ const currentURL = () => window.location.href;
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
|
||||
### detectDeviceType
|
||||
|
||||
Detects wether the website is being opened in a mobile device or a desktop/laptop.
|
||||
|
||||
Use a regular expression to test the `navigator.userAgent` property to figure out if the device is a mobile device or a desktop/laptop.
|
||||
|
||||
```js
|
||||
const detectDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? "Mobile" : "Desktop";
|
||||
// detectDeviceType() -> "Mobile"
|
||||
// detectDeviceType() -> "Desktop"
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
|
||||
### elementIsVisibleInViewport
|
||||
|
||||
Returns `true` if the element specified is visible in the viewport, `false` otherwise.
|
||||
@ -1247,6 +1269,21 @@ async function sleepyWork() {
|
||||
*/
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
## Logic
|
||||
|
||||
### negate
|
||||
|
||||
Negates a predicate function.
|
||||
|
||||
Take a predicate function and apply `not` to it with its arguments.
|
||||
|
||||
```js
|
||||
const negate = func => (...args) => !func(...args);
|
||||
// filter([1, 2, 3, 4, 5, 6], negate(isEven)) -> [1, 3, 5]
|
||||
// negate(isOdd)(1) -> false
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
## Math
|
||||
|
||||
@ -1957,6 +1994,22 @@ const fromCamelCase = (str, separator = '_') =>
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
|
||||
### repeatString
|
||||
|
||||
Repeats a string n times using `String.repeat()`
|
||||
|
||||
If no string is provided the default is `""` and the default number of times is 2.
|
||||
|
||||
```js
|
||||
const repeatString = (str="",num=2) => {
|
||||
return num >= 0 ? str.repeat(num) : str;
|
||||
}
|
||||
// repeatString("abc",3) -> 'abcabcabc'
|
||||
// repeatString("abc") -> 'abcabc'
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
|
||||
### reverseString
|
||||
|
||||
Reverses a string.
|
||||
@ -2002,6 +2055,52 @@ const toCamelCase = str =>
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
|
||||
### toKebabCase
|
||||
|
||||
Converts a string to [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
|
||||
Breaks the string into words.
|
||||
A word is defined as following:-
|
||||
-> Beginning with two or more capital letters, e.g. XML or FM
|
||||
-> Begin with a capital letter followed by lower case letters with optional trailing numbers, e.g. Hello or Http2
|
||||
-> Contain nothing but lower case letters with optional trailing numbers, e.g. hello or http2
|
||||
-> Individual upper letters, e.g T.M.N.T
|
||||
-> Groups of numbers, e.g. 555-555-5555
|
||||
|
||||
For more detailed explanation of this Regex [Visit this Site](https://regex101.com/r/bMCgAB/1)
|
||||
|
||||
```js
|
||||
const toKebabCase = str => {
|
||||
let regex = rx = /[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g;
|
||||
return str.match(regex).map(x =>{
|
||||
return x.toLowerCase();
|
||||
}).join('-');
|
||||
}
|
||||
// toKebabCase("camelCase") -> 'camel-case'
|
||||
// toKebabCase("some text") -> 'some-text'
|
||||
// toKebabCase("some-mixed_string With spaces_underscores-and-hyphens") -> 'some-mixed-string-with-spaces-underscores-and-hyphens'
|
||||
// toKebabCase("AllThe-small Things") -> "all-the-small-things"
|
||||
// toKebabCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML') -> "i-am-listening-to-fm-while-loading-different-url-on-my-browser-and-also-editing-xml-and-html"
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
|
||||
### toSnakeCase
|
||||
|
||||
Converts a string to snakecase.
|
||||
|
||||
Use `replace()` to add underscores before capital letters, convert `toLowerCase()`, then `replace()` hyphens and spaces with underscores.
|
||||
|
||||
```js
|
||||
const toSnakeCase = str =>
|
||||
str.replace(/(\w)([A-Z])/g, '$1_$2').replace(/[\s-_]+/g, '_').toLowerCase();
|
||||
// toSnakeCase("camelCase") -> 'camel_case'
|
||||
// toSnakeCase("some text") -> 'some_text'
|
||||
// toSnakeCase("some-javascript-property") -> 'some_javascript_property'
|
||||
// toSnakeCase("some-mixed_string With spaces_underscores-and-hyphens") -> 'some_mixed_string_with_spaces_underscores_and_hyphens'
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
|
||||
### truncateString
|
||||
|
||||
Truncates a string up to a specified length.
|
||||
@ -2065,7 +2164,7 @@ const coalesceFactory = valid => (...args) => args.find(valid);
|
||||
Extends a 3-digit color code to a 6-digit color code.
|
||||
|
||||
Use `Array.map()`, `split()` and `Array.join()` to join the mapped array for converting a 3-digit RGB notated hexadecimal color-code to the 6-digit form.
|
||||
`Array.slice()` is used to remove `#` from string start since it's added once.
|
||||
`String.slice()` is used to remove `#` from string start since it's added once.
|
||||
```js
|
||||
const extendHex = shortHex =>
|
||||
'#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split('').map(x => x+x).join('')
|
||||
@ -2199,6 +2298,25 @@ const isSymbol = val => typeof val === 'symbol';
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
|
||||
### randomHexColorCode
|
||||
|
||||
Generates a random hexadecimal color code.
|
||||
|
||||
Use `Math.random` to generate a random number and limit that number to fall in between 0 and 16 using `Math.floor`. Use the generated random number as index to access a character from 0 to F. Append it to `color` till the length is not `7`.
|
||||
|
||||
```js
|
||||
const randomHexColorCode = () => {
|
||||
let color = '#';
|
||||
while(color.length < 7) color += '0123456789ABCDEF'[Math.floor(Math.random() * 16)];
|
||||
return color;
|
||||
}
|
||||
// randomHexColorCode() -> "#e34155"
|
||||
// randomHexColorCode() -> "#fd73a6"
|
||||
// randomHexColorCode() -> "#4144c6"
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
|
||||
### RGBToHex
|
||||
|
||||
Converts the values of RGB components to a color code.
|
||||
|
||||
1697
dist/flavor.css
vendored
1697
dist/flavor.css
vendored
File diff suppressed because it is too large
Load Diff
1
dist/flavor.min.css
vendored
1
dist/flavor.min.css
vendored
File diff suppressed because one or more lines are too long
110
docs/index.html
110
docs/index.html
@ -17,7 +17,7 @@
|
||||
</head>
|
||||
<script>
|
||||
const search = (node) => {
|
||||
// Hide non-query-matching snippets
|
||||
// Hide non-query-matching snippets
|
||||
Array.from(node.parentElement.parentElement.getElementsByTagName('a')).forEach(x => {
|
||||
x.style.display = x.getAttribute("href").toUpperCase().indexOf(node.value.toUpperCase()) + 1 ? '' : 'none'
|
||||
});
|
||||
@ -32,8 +32,30 @@
|
||||
element.style.display = (element.tagName == 'H3' && index + 1 == source.length ? 'none' : element.tagName == 'H3' && source[index + 1].tagName == 'H3' ? 'none' : '')
|
||||
})
|
||||
}
|
||||
function clipboard() {
|
||||
const snippets = document.querySelectorAll("pre");
|
||||
snippets.forEach(element => {
|
||||
const button = document.createElement("button");
|
||||
button.innerHTML = "Copy to clipboard";
|
||||
element.parentElement.appendChild(button);
|
||||
|
||||
button.addEventListener ("click", function() {
|
||||
//The following regex removes all the comments from the snippet
|
||||
const text = element.textContent.replace(/\/\*(.|[\r\n])*?\*\//g, '').replace(/\/\/.*/gm, '');
|
||||
// Apparently you can't copy a variable to clipboard so you need to create text input element,
|
||||
// give it a value, copy it and then remove it from DOM.
|
||||
const textArea = document.createElement("textarea");
|
||||
textArea.value = text.trim();
|
||||
document.body.appendChild(textArea);
|
||||
console.log(textArea.innerText);
|
||||
textArea.select();
|
||||
document.execCommand("Copy");
|
||||
document.body.removeChild(textArea);
|
||||
});
|
||||
});
|
||||
};
|
||||
</script>
|
||||
<body>
|
||||
<body onload="clipboard()">
|
||||
<a href="https://github.com/Chalarangelo/30-seconds-of-code" class="github-corner" aria-label="View source on Github"><svg width="90" height="90" viewBox="0 0 250 250" style="fill:#151513;color:#fff;position:absolute;top:0;border:0;right:0" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin:130px 106px" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
|
||||
<header style="height:5.5rem">
|
||||
<h1 class="logo" href="https://github.com/Chalarangelo/30-seconds-of-code"><img src="favicon.png" style="height:4rem"/><span id="title"> 30 seconds of code</span>
|
||||
@ -108,6 +130,7 @@
|
||||
</h3><a class="sublink-1" href="#arraytohtmllist">arrayToHtmlList</a>
|
||||
<a class="sublink-1" href="#bottomvisible">bottomVisible</a>
|
||||
<a class="sublink-1" href="#currenturl">currentURL</a>
|
||||
<a class="sublink-1" href="#detectdevicetype">detectDeviceType</a>
|
||||
<a class="sublink-1" href="#elementisvisibleinviewport">elementIsVisibleInViewport</a>
|
||||
<a class="sublink-1" href="#getscrollposition">getScrollPosition</a>
|
||||
<a class="sublink-1" href="#geturlparameters">getURLParameters</a>
|
||||
@ -129,6 +152,9 @@
|
||||
<a class="sublink-1" href="#runpromisesinseries">runPromisesInSeries</a>
|
||||
<a class="sublink-1" href="#sleep">sleep</a>
|
||||
|
||||
<h3>Logic
|
||||
</h3><a class="sublink-1" href="#negate">negate</a>
|
||||
|
||||
<h3>Math
|
||||
</h3><a class="sublink-1" href="#arrayaverage">arrayAverage</a>
|
||||
<a class="sublink-1" href="#arraysum">arraySum</a>
|
||||
@ -181,9 +207,12 @@
|
||||
<a class="sublink-1" href="#countvowels">countVowels</a>
|
||||
<a class="sublink-1" href="#escaperegexp">escapeRegExp</a>
|
||||
<a class="sublink-1" href="#fromcamelcase">fromCamelCase</a>
|
||||
<a class="sublink-1" href="#repeatstring">repeatString</a>
|
||||
<a class="sublink-1" href="#reversestring">reverseString</a>
|
||||
<a class="sublink-1" href="#sortcharactersinstring">sortCharactersInString</a>
|
||||
<a class="sublink-1" href="#tocamelcase">toCamelCase</a>
|
||||
<a class="sublink-1" href="#tokebabcase">toKebabCase</a>
|
||||
<a class="sublink-1" href="#tosnakecase">toSnakeCase</a>
|
||||
<a class="sublink-1" href="#truncatestring">truncateString</a>
|
||||
<a class="sublink-1" href="#words">words</a>
|
||||
|
||||
@ -199,6 +228,7 @@
|
||||
<a class="sublink-1" href="#isnumber">isNumber</a>
|
||||
<a class="sublink-1" href="#isstring">isString</a>
|
||||
<a class="sublink-1" href="#issymbol">isSymbol</a>
|
||||
<a class="sublink-1" href="#randomhexcolorcode">randomHexColorCode</a>
|
||||
<a class="sublink-1" href="#rgbtohex">RGBToHex</a>
|
||||
<a class="sublink-1" href="#timetaken">timeTaken</a>
|
||||
<a class="sublink-1" href="#todecimalmark">toDecimalMark</a>
|
||||
@ -359,9 +389,9 @@ Returns the remaining elements.</p>
|
||||
// dropElements([1, 2, 3, 4], n => n >= 3) -> [3,4]
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="dropright">dropRight</h3></div><div class="section double-padded">
|
||||
<p>Returns a new array with <code>n</code> elements removed from the right</p>
|
||||
<p>Check if <code>n</code> is shorter than the given array and use <code>Array.slice()</code> to slice it accordingly or return an empty array.</p>
|
||||
<pre><code class="language-js">const dropRight = (arr, n = 1) => n < arr.length ? arr.slice(0, arr.length - n) : []
|
||||
<p>Returns a new array with <code>n</code> elements removed from the right.</p>
|
||||
<p>Use <code>Array.slice()</code> to slice the remove the specified number of elements from the right.</p>
|
||||
<pre><code class="language-js">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) -> []
|
||||
@ -651,6 +681,13 @@ If lengths of the argument-arrays vary, <code>undefined</code> is used where no
|
||||
<pre><code class="language-js">const currentURL = () => window.location.href;
|
||||
// currentUrl() -> 'https://google.com'
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="detectdevicetype">detectDeviceType</h3></div><div class="section double-padded">
|
||||
<p>Detects wether the website is being opened in a mobile device or a desktop/laptop.</p>
|
||||
<p>Use a regular expression to test the <code>navigator.userAgent</code> property to figure out if the device is a mobile device or a desktop/laptop.</p>
|
||||
<pre><code class="language-js">const detectDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? "Mobile" : "Desktop";
|
||||
// detectDeviceType() -> "Mobile"
|
||||
// detectDeviceType() -> "Desktop"
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="elementisvisibleinviewport">elementIsVisibleInViewport</h3></div><div class="section double-padded">
|
||||
<p>Returns <code>true</code> if the element specified is visible in the viewport, <code>false</code> otherwise.</p>
|
||||
<p>Use <code>Element.getBoundingClientRect()</code> and the <code>window.inner(Width|Height)</code> values
|
||||
@ -815,6 +852,14 @@ async function sleepyWork() {
|
||||
}
|
||||
*/
|
||||
</code></pre>
|
||||
</div></div><br/><h2 style="text-align:center">Logic</h2>
|
||||
<div class="card fluid"><div class="section double-padded"><h3 id="negate">negate</h3></div><div class="section double-padded">
|
||||
<p>Negates a predicate function.</p>
|
||||
<p>Take a predicate function and apply <code>not</code> to it with its arguments.</p>
|
||||
<pre><code class="language-js">const negate = func => (...args) => !func(...args);
|
||||
// filter([1, 2, 3, 4, 5, 6], negate(isEven)) -> [1, 3, 5]
|
||||
// negate(isOdd)(1) -> false
|
||||
</code></pre>
|
||||
</div></div><br/><h2 style="text-align:center">Math</h2>
|
||||
<div class="card fluid"><div class="section double-padded"><h3 id="arrayaverage">arrayAverage</h3></div><div class="section double-padded">
|
||||
<p>Returns the average of an array of numbers.</p>
|
||||
@ -1221,6 +1266,15 @@ Omit the second argument to use a default separator of <code>_</code>.</p>
|
||||
// fromCamelCase('someLabelThatNeedsToBeCamelized', '-') -> 'some-label-that-needs-to-be-camelized'
|
||||
// fromCamelCase('someJavascriptProperty', '_') -> 'some_javascript_property'
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="repeatstring">repeatString</h3></div><div class="section double-padded">
|
||||
<p>Repeats a string n times using <code>String.repeat()</code></p>
|
||||
<p>If no string is provided the default is <code>""</code> and the default number of times is 2.</p>
|
||||
<pre><code class="language-js">const repeatString = (str="",num=2) => {
|
||||
return num >= 0 ? str.repeat(num) : str;
|
||||
}
|
||||
// repeatString("abc",3) -> 'abcabcabc'
|
||||
// repeatString("abc") -> 'abcabc'
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="reversestring">reverseString</h3></div><div class="section double-padded">
|
||||
<p>Reverses a string.</p>
|
||||
<p>Use <code>split('')</code> and <code>Array.reverse()</code> to reverse the order of the characters in the string.
|
||||
@ -1245,6 +1299,38 @@ Combine characters to get a string using <code>join('')</code>.</p>
|
||||
// toCamelCase("some-javascript-property") -> 'someJavascriptProperty'
|
||||
// toCamelCase("some-mixed_string with spaces_underscores-and-hyphens") -> 'someMixedStringWithSpacesUnderscoresAndHyphens'
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="tokebabcase">toKebabCase</h3></div><div class="section double-padded">
|
||||
<p>Converts a string to <a href="https://en.wikipedia.org/wiki/Letter_case#Special_case_styles">kebab case</a>.
|
||||
Breaks the string into words.
|
||||
A word is defined as following:-
|
||||
-> Beginning with two or more capital letters, e.g. XML or FM
|
||||
-> Begin with a capital letter followed by lower case letters with optional trailing numbers, e.g. Hello or Http2
|
||||
-> Contain nothing but lower case letters with optional trailing numbers, e.g. hello or http2
|
||||
-> Individual upper letters, e.g T.M.N.T
|
||||
-> Groups of numbers, e.g. 555-555-5555</p>
|
||||
<p>For more detailed explanation of this Regex <a href="https://regex101.com/r/bMCgAB/1">Visit this Site</a></p>
|
||||
<pre><code class="language-js">const toKebabCase = str => {
|
||||
let regex = rx = /[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g;
|
||||
return str.match(regex).map(x =>{
|
||||
return x.toLowerCase();
|
||||
}).join('-');
|
||||
}
|
||||
// toKebabCase("camelCase") -> 'camel-case'
|
||||
// toKebabCase("some text") -> 'some-text'
|
||||
// toKebabCase("some-mixed_string With spaces_underscores-and-hyphens") -> 'some-mixed-string-with-spaces-underscores-and-hyphens'
|
||||
// toKebabCase("AllThe-small Things") -> "all-the-small-things"
|
||||
// toKebabCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML') -> "i-am-listening-to-fm-while-loading-different-url-on-my-browser-and-also-editing-xml-and-html"
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="tosnakecase">toSnakeCase</h3></div><div class="section double-padded">
|
||||
<p>Converts a string to snakecase.</p>
|
||||
<p>Use <code>replace()</code> to add underscores before capital letters, convert <code>toLowerCase()</code>, then <code>replace()</code> hyphens and spaces with underscores.</p>
|
||||
<pre><code class="language-js">const toSnakeCase = str =>
|
||||
str.replace(/(\w)([A-Z])/g, '$1_$2').replace(/[\s-_]+/g, '_').toLowerCase();
|
||||
// toSnakeCase("camelCase") -> 'camel_case'
|
||||
// toSnakeCase("some text") -> 'some_text'
|
||||
// toSnakeCase("some-javascript-property") -> 'some_javascript_property'
|
||||
// toSnakeCase("some-mixed_string With spaces_underscores-and-hyphens") -> 'some_mixed_string_with_spaces_underscores_and_hyphens'
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="truncatestring">truncateString</h3></div><div class="section double-padded">
|
||||
<p>Truncates a string up to a specified length.</p>
|
||||
<p>Determine if the string's <code>length</code> is greater than <code>num</code>.
|
||||
@ -1278,7 +1364,7 @@ Omit the second argument to use the default regex.</p>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="extendhex">extendHex</h3></div><div class="section double-padded">
|
||||
<p>Extends a 3-digit color code to a 6-digit color code.</p>
|
||||
<p>Use <code>Array.map()</code>, <code>split()</code> and <code>Array.join()</code> to join the mapped array for converting a 3-digit RGB notated hexadecimal color-code to the 6-digit form.
|
||||
<code>Array.slice()</code> is used to remove <code>#</code> from string start since it's added once.</p>
|
||||
<code>String.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('')
|
||||
// extendHex('#03f') -> '#0033ff'
|
||||
@ -1352,6 +1438,18 @@ Omit the second argument to use the default regex.</p>
|
||||
// isSymbol('x') -> false
|
||||
// isSymbol(Symbol('x')) -> true
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="randomhexcolorcode">randomHexColorCode</h3></div><div class="section double-padded">
|
||||
<p>Generates a random hexadecimal color code.</p>
|
||||
<p>Use <code>Math.random</code> to generate a random number and limit that number to fall in between 0 and 16 using <code>Math.floor</code>. Use the generated random number as index to access a character from 0 to F. Append it to <code>color</code> till the length is not <code>7</code>.</p>
|
||||
<pre><code class="language-js">const randomHexColorCode = () => {
|
||||
let color = '#';
|
||||
while(color.length < 7) color += '0123456789ABCDEF'[Math.floor(Math.random() * 16)];
|
||||
return color;
|
||||
}
|
||||
// randomHexColorCode() -> "#e34155"
|
||||
// randomHexColorCode() -> "#fd73a6"
|
||||
// randomHexColorCode() -> "#4144c6"
|
||||
</code></pre>
|
||||
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="rgbtohex">RGBToHex</h3></div><div class="section double-padded">
|
||||
<p>Converts the values of RGB components to a color code.</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>
|
||||
|
||||
11
snippets/detectDeviceType.md
Normal file
11
snippets/detectDeviceType.md
Normal file
@ -0,0 +1,11 @@
|
||||
### detectDeviceType
|
||||
|
||||
Detects wether the website is being opened in a mobile device or a desktop/laptop.
|
||||
|
||||
Use a regular expression to test the `navigator.userAgent` property to figure out if the device is a mobile device or a desktop/laptop.
|
||||
|
||||
```js
|
||||
const detectDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? "Mobile" : "Desktop";
|
||||
// detectDeviceType() -> "Mobile"
|
||||
// detectDeviceType() -> "Desktop"
|
||||
```
|
||||
@ -1,11 +1,11 @@
|
||||
### dropRight
|
||||
|
||||
Returns a new array with `n` elements removed from the right
|
||||
Returns a new array with `n` elements removed from the right.
|
||||
|
||||
Check if `n` is shorter than the given array and use `Array.slice()` to slice it accordingly or return an empty array.
|
||||
Use `Array.slice()` to slice the remove the specified number of elements from the right.
|
||||
|
||||
```js
|
||||
const dropRight = (arr, n = 1) => n < arr.length ? arr.slice(0, arr.length - 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) -> []
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
Extends a 3-digit color code to a 6-digit color code.
|
||||
|
||||
Use `Array.map()`, `split()` and `Array.join()` to join the mapped array for converting a 3-digit RGB notated hexadecimal color-code to the 6-digit form.
|
||||
`Array.slice()` is used to remove `#` from string start since it's added once.
|
||||
`String.slice()` is used to remove `#` from string start since it's added once.
|
||||
```js
|
||||
const extendHex = shortHex =>
|
||||
'#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split('').map(x => x+x).join('')
|
||||
|
||||
11
snippets/negate.md
Normal file
11
snippets/negate.md
Normal file
@ -0,0 +1,11 @@
|
||||
### negate
|
||||
|
||||
Negates a predicate function.
|
||||
|
||||
Take a predicate function and apply `not` to it with its arguments.
|
||||
|
||||
```js
|
||||
const negate = func => (...args) => !func(...args);
|
||||
// filter([1, 2, 3, 4, 5, 6], negate(isEven)) -> [1, 3, 5]
|
||||
// negate(isOdd)(1) -> false
|
||||
```
|
||||
16
snippets/randomHexColorCode.md
Normal file
16
snippets/randomHexColorCode.md
Normal file
@ -0,0 +1,16 @@
|
||||
### randomHexColorCode
|
||||
|
||||
Generates a random hexadecimal color code.
|
||||
|
||||
Use `Math.random` to generate a random number and limit that number to fall in between 0 and 16 using `Math.floor`. Use the generated random number as index to access a character from 0 to F. Append it to `color` till the length is not `7`.
|
||||
|
||||
```js
|
||||
const randomHexColorCode = () => {
|
||||
let color = '#';
|
||||
while(color.length < 7) color += '0123456789ABCDEF'[Math.floor(Math.random() * 16)];
|
||||
return color;
|
||||
}
|
||||
// randomHexColorCode() -> "#e34155"
|
||||
// randomHexColorCode() -> "#fd73a6"
|
||||
// randomHexColorCode() -> "#4144c6"
|
||||
```
|
||||
13
snippets/repeatString.md
Normal file
13
snippets/repeatString.md
Normal file
@ -0,0 +1,13 @@
|
||||
### repeatString
|
||||
|
||||
Repeats a string n times using `String.repeat()`
|
||||
|
||||
If no string is provided the default is `""` and the default number of times is 2.
|
||||
|
||||
```js
|
||||
const repeatString = (str="",num=2) => {
|
||||
return num >= 0 ? str.repeat(num) : str;
|
||||
}
|
||||
// repeatString("abc",3) -> 'abcabcabc'
|
||||
// repeatString("abc") -> 'abcabc'
|
||||
```
|
||||
26
snippets/toKebabCase.md
Normal file
26
snippets/toKebabCase.md
Normal file
@ -0,0 +1,26 @@
|
||||
### toKebabCase
|
||||
|
||||
Converts a string to [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
|
||||
Breaks the string into words.
|
||||
A word is defined as following:-
|
||||
-> Beginning with two or more capital letters, e.g. XML or FM
|
||||
-> Begin with a capital letter followed by lower case letters with optional trailing numbers, e.g. Hello or Http2
|
||||
-> Contain nothing but lower case letters with optional trailing numbers, e.g. hello or http2
|
||||
-> Individual upper letters, e.g T.M.N.T
|
||||
-> Groups of numbers, e.g. 555-555-5555
|
||||
|
||||
For more detailed explanation of this Regex [Visit this Site](https://regex101.com/r/bMCgAB/1)
|
||||
|
||||
```js
|
||||
const toKebabCase = str => {
|
||||
let regex = rx = /[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g;
|
||||
return str.match(regex).map(x =>{
|
||||
return x.toLowerCase();
|
||||
}).join('-');
|
||||
}
|
||||
// toKebabCase("camelCase") -> 'camel-case'
|
||||
// toKebabCase("some text") -> 'some-text'
|
||||
// toKebabCase("some-mixed_string With spaces_underscores-and-hyphens") -> 'some-mixed-string-with-spaces-underscores-and-hyphens'
|
||||
// toKebabCase("AllThe-small Things") -> "all-the-small-things"
|
||||
// toKebabCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML') -> "i-am-listening-to-fm-while-loading-different-url-on-my-browser-and-also-editing-xml-and-html"
|
||||
```
|
||||
14
snippets/toSnakeCase.md
Normal file
14
snippets/toSnakeCase.md
Normal file
@ -0,0 +1,14 @@
|
||||
### toSnakeCase
|
||||
|
||||
Converts a string to snakecase.
|
||||
|
||||
Use `replace()` to add underscores before capital letters, convert `toLowerCase()`, then `replace()` hyphens and spaces with underscores.
|
||||
|
||||
```js
|
||||
const toSnakeCase = str =>
|
||||
str.replace(/(\w)([A-Z])/g, '$1_$2').replace(/[\s-_]+/g, '_').toLowerCase();
|
||||
// toSnakeCase("camelCase") -> 'camel_case'
|
||||
// toSnakeCase("some text") -> 'some_text'
|
||||
// toSnakeCase("some-javascript-property") -> 'some_javascript_property'
|
||||
// toSnakeCase("some-mixed_string With spaces_underscores-and-hyphens") -> 'some_mixed_string_with_spaces_underscores_and_hyphens'
|
||||
```
|
||||
@ -17,7 +17,7 @@
|
||||
</head>
|
||||
<script>
|
||||
const search = (node) => {
|
||||
// Hide non-query-matching snippets
|
||||
// Hide non-query-matching snippets
|
||||
Array.from(node.parentElement.parentElement.getElementsByTagName('a')).forEach(x => {
|
||||
x.style.display = x.getAttribute("href").toUpperCase().indexOf(node.value.toUpperCase()) + 1 ? '' : 'none'
|
||||
});
|
||||
@ -32,8 +32,30 @@
|
||||
element.style.display = (element.tagName == 'H3' && index + 1 == source.length ? 'none' : element.tagName == 'H3' && source[index + 1].tagName == 'H3' ? 'none' : '')
|
||||
})
|
||||
}
|
||||
function clipboard() {
|
||||
const snippets = document.querySelectorAll("pre");
|
||||
snippets.forEach(element => {
|
||||
const button = document.createElement("button");
|
||||
button.innerHTML = "Copy to clipboard";
|
||||
element.parentElement.appendChild(button);
|
||||
|
||||
button.addEventListener ("click", function() {
|
||||
//The following regex removes all the comments from the snippet
|
||||
const text = element.textContent.replace(/\/\*(.|[\r\n])*?\*\//g, '').replace(/\/\/.*/gm, '');
|
||||
// Apparently you can't copy a variable to clipboard so you need to create text input element,
|
||||
// give it a value, copy it and then remove it from DOM.
|
||||
const textArea = document.createElement("textarea");
|
||||
textArea.value = text.trim();
|
||||
document.body.appendChild(textArea);
|
||||
console.log(textArea.innerText);
|
||||
textArea.select();
|
||||
document.execCommand("Copy");
|
||||
document.body.removeChild(textArea);
|
||||
});
|
||||
});
|
||||
};
|
||||
</script>
|
||||
<body>
|
||||
<body onload="clipboard()">
|
||||
<a href="https://github.com/Chalarangelo/30-seconds-of-code" class="github-corner" aria-label="View source on Github"><svg width="90" height="90" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
|
||||
<header style="height: 5.5rem;">
|
||||
<h1 class="logo" href="https://github.com/Chalarangelo/30-seconds-of-code"><img src="favicon.png" style="height: 4rem;"/><span id="title"> 30 seconds of code</span>
|
||||
|
||||
@ -25,6 +25,7 @@ countVowels:string
|
||||
currentURL:browser
|
||||
curry:function
|
||||
deepFlatten:array
|
||||
detectDeviceType:browser
|
||||
difference:array
|
||||
differenceWith:array
|
||||
digitize:math
|
||||
@ -78,6 +79,7 @@ last:array
|
||||
lcm:math
|
||||
mapObject:array
|
||||
median:math
|
||||
negate:logic
|
||||
nthElement:array
|
||||
objectFromPairs:object
|
||||
objectToPairs:object
|
||||
@ -92,11 +94,13 @@ promisify:adapter
|
||||
pull:array
|
||||
pullAtIndex:array
|
||||
pullAtValue:array
|
||||
randomHexColorCode:utility
|
||||
randomIntegerInRange:math
|
||||
randomNumberInRange:math
|
||||
readFileLines:node
|
||||
redirect:browser
|
||||
remove:array
|
||||
repeatString:string
|
||||
reverseString:string
|
||||
RGBToHex:utility
|
||||
round:math
|
||||
@ -120,7 +124,9 @@ timeTaken:utility
|
||||
toCamelCase:string
|
||||
toDecimalMark:utility
|
||||
toEnglishDate:date
|
||||
toKebabCase:string
|
||||
toOrdinalSuffix:utility
|
||||
toSnakeCase:string
|
||||
truncateString:string
|
||||
truthCheckCollection:object
|
||||
union:array
|
||||
|
||||
Reference in New Issue
Block a user