Merge pull request #2 from Chalarangelo/master

hghj
This commit is contained in:
Rohit Tanwar
2017-12-26 15:57:12 +05:30
committed by GitHub
15 changed files with 208 additions and 135 deletions

View File

@ -11,7 +11,7 @@ script:
- npm run webber
after_success:
- chmod +x .travis/push.sh
- sudo .travis/push.sh
- .travis/push.sh
group: deprecated-2017Q4
env:
global:

View File

@ -1,5 +1,3 @@
#!/bin/sh
setup_git() {
git config --global user.email "travis@travis-ci.org"
git config --global user.name "Travis CI"
@ -7,6 +5,11 @@ setup_git() {
commit_website_files() {
git checkout master
if [[ $(( $TRAVIS_BUILD_NUMBER % 5 )) == 0 ]]; then
declare -i n=($TRAVIS_BUILD_NUMBER-270)/5
npm run linter
echo "Linting build: $n"
fi
git add *
git commit --message "Travis build: $TRAVIS_BUILD_NUMBER"
}

138
README.md
View File

@ -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)
@ -163,6 +167,7 @@
* [`isNumber`](#isnumber)
* [`isString`](#isstring)
* [`isSymbol`](#issymbol)
* [`randomHexColorCode`](#randomhexcolorcode)
* [`RGBToHex`](#rgbtohex)
* [`timeTaken`](#timetaken)
* [`toDecimalMark`](#todecimalmark)
@ -170,10 +175,6 @@
* [`UUIDGenerator`](#uuidgenerator)
* [`validateNumber`](#validatenumber)
### _Uncategorized_
* [`detectDeviceType`](#detectdevicetype)
* [`negate`](#negate)
## Adapter
### call
@ -224,7 +225,7 @@ const flip = fn => (...args) => fn(args.pop(), ...args)
let a = {name: 'John Smith'}
let b = {}
const mergeFrom = flip(Object.assign)
let mergePerson = mergeFrom.bind(a)
let mergePerson = mergeFrom.bind(null, a)
mergePerson(b) // == b
b = {}
Object.assign(b, a) // == b
@ -449,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) -> []
@ -980,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.
@ -1176,8 +1191,8 @@ multiplyAndAdd5(5, 2) -> 15
Curries a function.
Use recursion.
If the number of provided arguments (`args`) is sufficient, call the passed function `f`.
Otherwise, return a curried function `f` that expects the rest of the arguments.
If the number of provided arguments (`args`) is sufficient, call the passed function `fn`.
Otherwise, return a curried function `fn` that expects the rest of the arguments.
If you want to curry a function that accepts a variable number of arguments (a variadic function, e.g. `Math.min()`), you can optionally pass the number of arguments to the second parameter `arity`.
```js
@ -1254,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
@ -2012,11 +2042,16 @@ const sortCharactersInString = str =>
Converts a string to camelcase.
Use `replace()` to remove underscores, hyphens, and spaces and convert words to camelcase.
Break the string into words and combine them capitalizing the first letter of each word.
For more detailed explanation of this Regex, [visit this Site](https://regex101.com/r/bMCgAB/1).
```js
const toCamelCase = str =>
str.replace(/^([A-Z])|[\s-_]+(\w)/g, (match, p1, p2, offset) => p2 ? p2.toUpperCase() : p1.toLowerCase());
const toCamelCase = str => {
let s = str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map(x => x.slice(0,1).toUpperCase() + x.slice(1).toLowerCase())
.join('');
return s.slice(0,1).toLowerCase() + s.slice(1)
}
// toCamelCase("some_database_field_name") -> 'someDatabaseFieldName'
// toCamelCase("Some label that needs to be camelized") -> 'someLabelThatNeedsToBeCamelized'
// toCamelCase("some-javascript-property") -> 'someJavascriptProperty'
@ -2027,36 +2062,43 @@ const toCamelCase = str =>
### toKebabCase
Converts a string to [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
Use `replace()` to add spaces before capital letters, convert `toLowerCase()`, then `replace()` underscores and spaces with hyphens.
Also check if a string starts with a hyphen and remove it if yes.
Converts a string to kebab case.
Break the string into words and combine them using `-` as a separator.
For more detailed explanation of this Regex, [visit this Site](https://regex101.com/r/bMCgAB/1).
```js
const toKebabCase = str => {
str = str.replace(/([A-Z])/g," $1").toLowerCase().replace(/_/g,' ').replace(/-/g,' ').replace(/\s\s+/g, ' ').replace(/\s/g,'-');
return str.startsWith('-') ? str.slice(1,str.length) : str;
}
const toKebabCase = str =>
str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map(x => 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.
Converts a string to snake case.
Use `replace()` to add underscores before capital letters, convert `toLowerCase()`, then `replace()` hyphens and spaces with underscores.
Break the string into words and combine them using `_` as a separator.
For more detailed explanation of this Regex, [visit this Site](https://regex101.com/r/bMCgAB/1).
```js
const toSnakeCase = str =>
str.replace(/(\w)([A-Z])/g, '$1_$2').replace(/[\s-_]+/g, '_').toLowerCase();
const toSnakeCase = str =>{
str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map(x => x.toLowerCase())
.join('_');
// 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'
// toKebabCase("AllThe-small Things") -> "all_the_smal_things"
// toKebabCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML') -> "i_am_listening_to_fm_while_loading_different_url_on_my_browser_and_also_editing_some_xml_and_html"
```
[⬆ back to top](#table-of-contents)
@ -2258,6 +2300,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 24-bit(6x4bits) hexadecimal number. Use bit shifting and then convert it to an hexadecimal String using `toString(16)`.
```js
const randomHexColor = () => {
let n = (Math.random()*0xfffff|0).toString(16);
return '#' + (n.length !== 6
? (Math.random()*0xf|0).toString(16) + n : n);
}
// randomHexColorCode() -> "#e34155"
// randomHexColorCode() -> "#fd73a6"
// randomHexColorCode() -> "#4144c6"
```
[⬆ back to top](#table-of-contents)
### RGBToHex
Converts the values of RGB components to a color code.
@ -2348,35 +2409,6 @@ const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) ==
// validateNumber('10') -> true
```
[⬆ back to top](#table-of-contents)
## _Uncategorized_
### 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)
### negate
Negates a predicate function.
Take a predicate function and apply `not` to it with its arguments.
```js
const negate = func => (...args) => !fun(...args);
// filter([1, 2, 3, 4, 5, 6], negate(isEven)) -> [1, 3, 5]
// negate(isOdd)(1) -> false
```
[⬆ back to top](#table-of-contents)
## Credits

View File

@ -56,7 +56,7 @@
};
</script>
<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>
<a href="https://github.com/Chalarangelo/30-seconds-of-code/fork" 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">&nbsp;30 seconds of code</span>
<small>Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.</small>
@ -130,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>
@ -151,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>
@ -224,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>
@ -231,10 +236,6 @@
<a class="sublink-1" href="#uuidgenerator">UUIDGenerator</a>
<a class="sublink-1" href="#validatenumber">validateNumber</a>
<h3>Uncategorized
</h3><a class="sublink-1" href="#detectdevicetype">detectDeviceType</a>
<a class="sublink-1" href="#negate">negate</a>
</nav><main class="col-sm-12 col-md-8 col-lg-9" style="height:100%;overflow-y:auto;background:#eceef2;padding:0"><a id="top">&nbsp;</a><h2 style="text-align:center">Adapter</h2>
<div class="card fluid"><div class="section double-padded"><h3 id="call">call</h3></div><div class="section double-padded">
<p>Given a key and a set of arguments, call them when given a context. Primarily useful in composition.</p>
@ -266,7 +267,7 @@ Pall(p1, p2, p3).then(console.log)
let a = {name: 'John Smith'}
let b = {}
const mergeFrom = flip(Object.assign)
let mergePerson = mergeFrom.bind(a)
let mergePerson = mergeFrom.bind(null, a)
mergePerson(b) // == b
b = {}
Object.assign(b, a) // == b
@ -388,9 +389,9 @@ Returns the remaining elements.</p>
// dropElements([1, 2, 3, 4], n =&gt; n &gt;= 3) -&gt; [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) =&gt; n &lt; 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) =&gt; arr.slice(0, -n);
//dropRight([1,2,3]) -&gt; [1,2]
//dropRight([1,2,3], 2) -&gt; [1]
//dropRight([1,2,3], 42) -&gt; []
@ -680,6 +681,13 @@ If lengths of the argument-arrays vary, <code>undefined</code> is used where no
<pre><code class="language-js">const currentURL = () =&gt; window.location.href;
// currentUrl() -&gt; '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 = () =&gt; /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? &quot;Mobile&quot; : &quot;Desktop&quot;;
// detectDeviceType() -&gt; &quot;Mobile&quot;
// detectDeviceType() -&gt; &quot;Desktop&quot;
</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
@ -797,8 +805,8 @@ multiplyAndAdd5(5, 2) -&gt; 15
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="curry">curry</h3></div><div class="section double-padded">
<p>Curries a function.</p>
<p>Use recursion.
If the number of provided arguments (<code>args</code>) is sufficient, call the passed function <code>f</code>.
Otherwise, return a curried function <code>f</code> that expects the rest of the arguments.
If the number of provided arguments (<code>args</code>) is sufficient, call the passed function <code>fn</code>.
Otherwise, return a curried function <code>fn</code> that expects the rest of the arguments.
If you want to curry a function that accepts a variable number of arguments (a variadic function, e.g. <code>Math.min()</code>), you can optionally pass the number of arguments to the second parameter <code>arity</code>.</p>
<pre><code class="language-js">const curry = (fn, arity = fn.length, ...args) =&gt;
arity &lt;= args.length
@ -844,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 =&gt; (...args) =&gt; !func(...args);
// filter([1, 2, 3, 4, 5, 6], negate(isEven)) -&gt; [1, 3, 5]
// negate(isOdd)(1) -&gt; 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>
@ -1275,36 +1291,47 @@ Combine characters to get a string using <code>join('')</code>.</p>
</code></pre>
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="tocamelcase">toCamelCase</h3></div><div class="section double-padded">
<p>Converts a string to camelcase.</p>
<p>Use <code>replace()</code> to remove underscores, hyphens, and spaces and convert words to camelcase.</p>
<pre><code class="language-js">const toCamelCase = str =&gt;
str.replace(/^([A-Z])|[\s-_]+(\w)/g, (match, p1, p2, offset) =&gt; p2 ? p2.toUpperCase() : p1.toLowerCase());
<p>Break the string into words and combine them capitalizing the first letter of each word.
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 toCamelCase = str =&gt; {
let s = str &amp;&amp; str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map(x =&gt; x.slice(0,1).toUpperCase() + x.slice(1).toLowerCase())
.join('');
return s.slice(0,1).toLowerCase() + s.slice(1)
}
// toCamelCase(&quot;some_database_field_name&quot;) -&gt; 'someDatabaseFieldName'
// toCamelCase(&quot;Some label that needs to be camelized&quot;) -&gt; 'someLabelThatNeedsToBeCamelized'
// toCamelCase(&quot;some-javascript-property&quot;) -&gt; 'someJavascriptProperty'
// toCamelCase(&quot;some-mixed_string with spaces_underscores-and-hyphens&quot;) -&gt; '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>.
Use <code>replace()</code> to add spaces before capital letters, convert <code>toLowerCase()</code>, then <code>replace()</code> underscores and spaces with hyphens.
Also check if a string starts with a hyphen and remove it if yes.</p>
<pre><code class="language-js">const toKebabCase = str =&gt; {
str = str.replace(/([A-Z])/g,&quot; $1&quot;).toLowerCase().replace(/_/g,' ').replace(/-/g,' ').replace(/\s\s+/g, ' ').replace(/\s/g,'-');
return str.startsWith('-') ? str.slice(1,str.length) : str;
}
<p>Converts a string to kebab case.</p>
<p>Break the string into words and combine them using <code>-</code> as a separator.
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 =&gt;
str &amp;&amp; str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map(x =&gt; x.toLowerCase())
.join('-');
// toKebabCase(&quot;camelCase&quot;) -&gt; 'camel-case'
// toKebabCase(&quot;some text&quot;) -&gt; 'some-text'
// toKebabCase(&quot;some-mixed_string With spaces_underscores-and-hyphens&quot;) -&gt; 'some-mixed-string-with-spaces-underscores-and-hyphens'
// toKebabCase(&quot;AllThe-small Things&quot;) -&gt; &quot;all-the-small-things&quot;
// toKebabCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML') -&gt; &quot;i-am-listening-to-fm-while-loading-different-url-on-my-browser-and-also-editing-xml-and-html&quot;
</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 =&gt;
str.replace(/(\w)([A-Z])/g, '$1_$2').replace(/[\s-_]+/g, '_').toLowerCase();
<p>Converts a string to snake case.</p>
<p>Break the string into words and combine them using <code>_</code> as a separator.
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 toSnakeCase = str =&gt;{
str &amp;&amp; str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map(x =&gt; x.toLowerCase())
.join('_');
// toSnakeCase(&quot;camelCase&quot;) -&gt; 'camel_case'
// toSnakeCase(&quot;some text&quot;) -&gt; 'some_text'
// toSnakeCase(&quot;some-javascript-property&quot;) -&gt; 'some_javascript_property'
// toSnakeCase(&quot;some-mixed_string With spaces_underscores-and-hyphens&quot;) -&gt; 'some_mixed_string_with_spaces_underscores_and_hyphens'
// toKebabCase(&quot;AllThe-small Things&quot;) -&gt; &quot;all_the_smal_things&quot;
// toKebabCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML') -&gt; &quot;i_am_listening_to_fm_while_loading_different_url_on_my_browser_and_also_editing_some_xml_and_html&quot;
</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>
@ -1413,6 +1440,18 @@ Omit the second argument to use the default regex.</p>
// isSymbol('x') -&gt; false
// isSymbol(Symbol('x')) -&gt; 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 24-bit(6x4bits) hexadecimal number. Use bit shifting and then convert it to an hexadecimal String using <code>toString(16)</code>.</p>
<pre><code class="language-js">const randomHexColor = () =&gt; {
let n = (Math.random()*0xfffff|0).toString(16);
return '#' + (n.length !== 6
? (Math.random()*0xf|0).toString(16) + n : n);
}
// randomHexColorCode() -&gt; &quot;#e34155&quot;
// randomHexColorCode() -&gt; &quot;#fd73a6&quot;
// randomHexColorCode() -&gt; &quot;#4144c6&quot;
</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>&lt;&lt;</code>) and <code>toString(16)</code>, then <code>padStart(6,'0')</code> to get a 6-digit hexadecimal value.</p>
@ -1464,21 +1503,6 @@ Use <code>Number()</code> to check if the coercion holds.</p>
<pre><code class="language-js">const validateNumber = n =&gt; !isNaN(parseFloat(n)) &amp;&amp; isFinite(n) &amp;&amp; Number(n) == n;
// validateNumber('10') -&gt; true
</code></pre>
</div></div><br/><h2 style="text-align:center">Uncategorized</h2>
<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 = () =&gt; /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? &quot;Mobile&quot; : &quot;Desktop&quot;;
// detectDeviceType() -&gt; &quot;Mobile&quot;
// detectDeviceType() -&gt; &quot;Desktop&quot;
</code></pre>
</div></div><br/><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 =&gt; (...args) =&gt; !fun(...args);
// filter([1, 2, 3, 4, 5, 6], negate(isEven)) -&gt; [1, 3, 5]
// negate(isOdd)(1) -&gt; false
</code></pre>
</div></div><br/>
<footer>
<p style="display:inline-block"><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>.<br/>Ribbon made by <a href="https://github.com/tholman/github-corners">Tim Holman</a> is licensed by <a href="https://opensource.org/licenses/MIT">The MIT License</a><br/>Built with the <a href="https://minicss.org">mini.css framework</a>.</p>

File diff suppressed because one or more lines are too long

View File

@ -163,3 +163,11 @@ label#menu-toggle {
main {
padding: 0;
}
.token.operator,
.token.entity,
.token.url,
.language-css .token.string,
.style .token.string {
background: none !important;
}

View File

@ -3,8 +3,8 @@
Curries a function.
Use recursion.
If the number of provided arguments (`args`) is sufficient, call the passed function `f`.
Otherwise, return a curried function `f` that expects the rest of the arguments.
If the number of provided arguments (`args`) is sufficient, call the passed function `fn`.
Otherwise, return a curried function `fn` that expects the rest of the arguments.
If you want to curry a function that accepts a variable number of arguments (a variadic function, e.g. `Math.min()`), you can optionally pass the number of arguments to the second parameter `arity`.
```js

View File

@ -10,7 +10,7 @@ const flip = fn => (...args) => fn(args.pop(), ...args)
let a = {name: 'John Smith'}
let b = {}
const mergeFrom = flip(Object.assign)
let mergePerson = mergeFrom.bind(a)
let mergePerson = mergeFrom.bind(null, a)
mergePerson(b) // == b
b = {}
Object.assign(b, a) // == b

View File

@ -5,7 +5,7 @@ Negates a predicate function.
Take a predicate function and apply `not` to it with its arguments.
```js
const negate = func => (...args) => !fun(...args);
const negate = func => (...args) => !func(...args);
// filter([1, 2, 3, 4, 5, 6], negate(isEven)) -> [1, 3, 5]
// negate(isOdd)(1) -> false
```

View File

@ -0,0 +1,16 @@
### randomHexColorCode
Generates a random hexadecimal color code.
Use `Math.random` to generate a random 24-bit(6x4bits) hexadecimal number. Use bit shifting and then convert it to an hexadecimal String using `toString(16)`.
```js
const randomHexColor = () => {
let n = (Math.random()*0xfffff|0).toString(16);
return '#' + (n.length !== 6
? (Math.random()*0xf|0).toString(16) + n : n);
}
// randomHexColorCode() -> "#e34155"
// randomHexColorCode() -> "#fd73a6"
// randomHexColorCode() -> "#4144c6"
```

View File

@ -2,18 +2,16 @@
Converts a string to camelcase.
Use `replace()` to remove underscores, hyphens, and spaces and convert words to camelcase.
Break the string into words and combine them capitalizing the first letter of each word.
For more detailed explanation of this Regex, [visit this Site](https://regex101.com/r/bMCgAB/1).
```js
const toCamelCase = 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;
let arr = str.match(regex);
arr = arr.map(x =>{
return x.slice(0,1).toUpperCase() + x.slice(1).toLowerCase();
});
str = arr.join('')
return str.slice(0,1).toLowerCase() + str.slice(1)
}
let s = str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map(x => x.slice(0,1).toUpperCase() + x.slice(1).toLowerCase())
.join('');
return s.slice(0,1).toLowerCase() + s.slice(1)
}
// toCamelCase("some_database_field_name") -> 'someDatabaseFieldName'
// toCamelCase("Some label that needs to be camelized") -> 'someLabelThatNeedsToBeCamelized'
// toCamelCase("some-javascript-property") -> 'someJavascriptProperty'

View File

@ -1,23 +1,15 @@
### 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
Converts a string to kebab case.
For more detailed explanation of this Regex [Visit this Site](https://regex101.com/r/bMCgAB/1)
Break the string into words and combine them using `-` as a separator.
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('-');
}
const toKebabCase = str =>
str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map(x => 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'

View File

@ -1,20 +1,19 @@
### toSnakeCase
Converts a string to snakecase.
Converts a string to snake case.
Use `replace()` to add underscores before capital letters, convert `toLowerCase()`, then `replace()` hyphens and spaces with underscores.
Break the string into words and combine them using `_` as a separator.
For more detailed explanation of this Regex, [visit this Site](https://regex101.com/r/bMCgAB/1).
```js
const toSnakeCase = 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;
let arr = str.match(regex);
arr = arr.map(x =>{
return x.toLowerCase();
});
return arr.join('_')
}
str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map(x => x.toLowerCase())
.join('_');
// 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'
// toKebabCase("AllThe-small Things") -> "all_the_smal_things"
// toKebabCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML') -> "i_am_listening_to_fm_while_loading_different_url_on_my_browser_and_also_editing_some_xml_and_html"
```

View File

@ -56,7 +56,7 @@
};
</script>
<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>
<a href="https://github.com/Chalarangelo/30-seconds-of-code/fork" 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">&nbsp;30 seconds of code</span>
<small>Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.</small>

View File

@ -94,6 +94,7 @@ promisify:adapter
pull:array
pullAtIndex:array
pullAtValue:array
randomHexColorCode:utility
randomIntegerInRange:math
randomNumberInRange:math
readFileLines:node