diff --git a/.gitignore b/.gitignore
index f30159a31..9d6b39d2c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,3 +3,4 @@ currentSnippet\.js
*.md.temp.js
.idea
test.sh
+dist/
diff --git a/.travis/push.sh b/.travis/push.sh
index 277140235..e3483a676 100755
--- a/.travis/push.sh
+++ b/.travis/push.sh
@@ -1,8 +1,8 @@
#!/bin/sh
setup_git() {
- git config --global user.email "david10608@gmail.com"
- git config --global user.name "Pl4gue"
+ git config --global user.email "travis@travis-ci.org"
+ git config --global user.name "Travis CI"
}
commit_website_files() {
diff --git a/README.md b/README.md
index 5354b4407..99b31269b 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,8 @@

-# 30 seconds of code [](https://gitter.im/30-seconds-of-code/Lobby) [](https://travis-ci.org/Chalarangelo/30-seconds-of-code)
+# 30 seconds of code
+[](https://github.com/Chalarangelo/30-seconds-of-code/blob/master/LICENSE) [](https://gitter.im/30-seconds-of-code/Lobby) [](http://makeapullrequest.com) [](https://travis-ci.org/Chalarangelo/30-seconds-of-code) [](https://insight.io/github.com/Chalarangelo/30-seconds-of-code/tree/master/?source=0) [](https://github.com/Flet/semistandard)
+
> Curated collection of useful Javascript snippets that you can understand in 30 seconds or less.
@@ -11,6 +13,13 @@
## Table of Contents
+### Adapter
+* [`call`](#call)
+* [`collectInto`](#collectinto)
+* [`flip`](#flip)
+* [`promisify`](#promisify)
+* [`spreadOver`](#spreadover)
+
### Array
* [`arrayGcd`](#arraygcd)
* [`arrayLcm`](#arraylcm)
@@ -78,7 +87,6 @@
* [`curry`](#curry)
* [`functionName`](#functionname)
* [`pipe`](#pipe)
-* [`promisify`](#promisify)
* [`runPromisesInSeries`](#runpromisesinseries)
* [`sleep`](#sleep)
@@ -91,6 +99,8 @@
* [`distance`](#distance)
* [`factorial`](#factorial)
* [`fibonacci`](#fibonacci)
+* [`fibonacciCountUntilNum`](#fibonaccicountuntilnum)
+* [`fibonacciUntilNum`](#fibonacciuntilnum)
* [`gcd`](#gcd)
* [`hammingDistance`](#hammingdistance)
* [`inRange`](#inrange)
@@ -132,9 +142,12 @@
* [`countVowels`](#countvowels)
* [`escapeRegExp`](#escaperegexp)
* [`fromCamelCase`](#fromcamelcase)
+* [`repeatString`](#repeatstring)
* [`reverseString`](#reversestring)
* [`sortCharactersInString`](#sortcharactersinstring)
* [`toCamelCase`](#tocamelcase)
+* [`toKebabCase`](#tokebabcase)
+* [`toSnakeCase`](#tosnakecase)
* [`truncateString`](#truncatestring)
* [`words`](#words)
@@ -157,6 +170,107 @@
* [`UUIDGenerator`](#uuidgenerator)
* [`validateNumber`](#validatenumber)
+### _Uncategorized_
+* [`detectDeviceType`](#detectdevicetype)
+* [`negate`](#negate)
+
+## Adapter
+
+### call
+
+Given a key and a set of arguments, call them when given a context. Primarily useful in composition.
+
+Use a closure to call a stored key with stored arguments.
+
+```js
+const call = ( key, ...args ) => context => context[ key ]( ...args );
+/*
+Promise.resolve( [ 1, 2, 3 ] ).then( call('map', x => 2 * x ) ).then( console.log ) //[ 2, 4, 6 ]
+const map = call.bind(null, 'map')
+Promise.resolve( [ 1, 2, 3 ] ).then( map( x => 2 * x ) ).then( console.log ) //[ 2, 4, 6 ]
+*/
+```
+
+[⬆ back to top](#table-of-contents)
+
+### collectInto
+
+Changes a function that accepts an array into a variadic function.
+
+Given a function, return a closure that collects all inputs into an array-accepting function.
+
+```js
+const collectInto = fn => ( ...args ) => fn( args );
+/*
+const Pall = collectInto( Promise.all.bind(Promise) )
+let p1 = Promise.resolve(1)
+let p2 = Promise.resolve(2)
+let p3 = new Promise((resolve) => setTimeout(resolve,2000,3))
+Pall(p1, p2, p3).then(console.log)
+*/
+```
+
+[⬆ back to top](#table-of-contents)
+
+### flip
+
+Flip takes a function as an argument, then makes the first argument the last
+
+Return a closure that takes variadic inputs, and splices the last argument to make it the first argument before applying the rest.
+
+```js
+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)
+mergePerson(b) // == b
+b = {}
+Object.assign(b, a) // == b
+*/
+```
+
+[⬆ back to top](#table-of-contents)
+
+### promisify
+
+Converts an asynchronous function to return a promise.
+
+Use currying to return a function returning a `Promise` that calls the original function.
+Use the `...rest` operator to pass in all the parameters.
+
+*In Node 8+, you can use [`util.promisify`](https://nodejs.org/api/util.html#util_util_promisify_original)*
+
+```js
+const promisify = func =>
+ (...args) =>
+ new Promise((resolve, reject) =>
+ func(...args, (err, result) =>
+ err ? reject(err) : resolve(result))
+ );
+// const delay = promisify((d, cb) => setTimeout(cb, d))
+// delay(2000).then(() => console.log('Hi!')) -> Promise resolves after 2s
+```
+
+[⬆ back to top](#table-of-contents)
+
+### spreadOver
+
+Takes a variadic function and returns a closure that accepts an array of arguments to map to the inputs of the function.
+
+Use closures and the spread operator (`...`) to map the array of arguments to the inputs of the function.
+
+```js
+const spreadOver = fn => argsArr => fn(...argsArr);
+/*
+const arrayMax = spreadOver(Math.max)
+arrayMax([1,2,3]) // -> 3
+arrayMax([1,2,4]) // -> 4
+*/
+```
+
+[⬆ back to top](#table-of-contents)
## Array
### arrayGcd
@@ -178,14 +292,14 @@ const arrayGcd = arr =>{
### arrayLcm
-Calculates the lowest common multiple (lcm) of an array of numbers.
+Calculates the lowest common multiple (lcm) of an array of numbers.
-Use `Array.reduce()` and the `lcm` formula (uses recursion) to calculate the lowest common multiple of an array of numbers.
+Use `Array.reduce()` and the `lcm` formula (uses recursion) to calculate the lowest common multiple of an array of numbers.
```js
const arrayLcm = arr =>{
const gcd = (x, y) => !y ? x : gcd(y, x % y);
- const lcm = (x, y) => (x*y)/gcd(x, y)
+ const lcm = (x, y) => (x*y)/gcd(x, y);
return arr.reduce((a,b) => lcm(a,b));
}
// arrayLcm([1,2,3,4,5]) -> 60
@@ -378,10 +492,10 @@ const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexO
Flattens an array.
-Use `Array.reduce()` to get all elements inside the array and `concat()` to flatten them.
+Use a new array and concatenate it with the spread input array causing a shallow denesting of any contained arrays.
```js
-const flatten = arr => arr.reduce((a, v) => a.concat(v), []);
+const flatten = arr => [ ].concat( ...arr );
// flatten([1,[2],3,4]) -> [1,2,3,4]
```
@@ -407,7 +521,7 @@ const flattenDepth = (arr, depth = 1) =>
### groupBy
-Groups the element of an array based on the given function.
+Groups the elements of an array based on the given function.
Use `Array.map()` to map the values of an array to a function or property name.
Use `Array.reduce()` to create an object, where the keys are produced from the mapped results.
@@ -439,7 +553,7 @@ const head = arr => arr[0];
Returns all the elements of an array except the last one.
-Use `arr.slice(0,-1)`to return all but the last element of the array.
+Use `arr.slice(0,-1)` to return all but the last element of the array.
```js
const initial = arr => arr.slice(0, -1);
@@ -450,9 +564,9 @@ const initial = arr => arr.slice(0, -1);
### initialize2DArray
-Initializes an 2D array of given width and height and value.
+Initializes a 2D array of given width and height and value.
-Use `Array.map()` to generate h rows where each is a new array of size w initialize with value. If value is not provided, default to `null`.
+Use `Array.map()` to generate h rows where each is a new array of size w initialize with value. If the value is not provided, default to `null`.
```js
const initialize2DArray = (w, h, val = null) => Array(h).fill().map(() => Array(w).fill(val));
@@ -508,7 +622,7 @@ const intersection = (a, b) => { const s = new Set(b); return a.filter(x => s.ha
Returns the last element in an array.
-Use `arr.length - 1` to compute index of the last element of the given array and returning it.
+Use `arr.length - 1` to compute the index of the last element of the given array and returning it.
```js
const last = arr => arr[arr.length - 1];
@@ -521,7 +635,7 @@ const last = arr => arr[arr.length - 1];
Maps the values of an array to an object using a function, where the key-value pairs consist of the original value as the key and the mapped value.
-Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new `Array` to stor the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations).
+Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new `Array` to store the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations).
```js
const mapObject = (arr, fn) =>
@@ -554,7 +668,7 @@ const nthElement = (arr, n=0) => (n>0? arr.slice(n,n+1) : arr.slice(n))[0];
Picks the key-value pairs corresponding to the given keys from an object.
-Use `Array.reduce()` to convert the filtered/picked keys back to a object with the corresponding key-value pair if the key exist in the obj.
+Use `Array.reduce()` to convert the filtered/picked keys back to an object with the corresponding key-value pair if the key exists in the obj.
```js
const pick = (obj, arr) =>
@@ -569,7 +683,7 @@ const pick = (obj, arr) =>
Mutates the original array to filter out the values specified.
Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed.
-Use `Array.length = 0` to mutate the passed in array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
+Use `Array.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
_(For a snippet that does not mutate the original array see [`without`](#without))_
@@ -597,7 +711,7 @@ const pull = (arr, ...args) => {
Mutates the original array to filter out the values at the specified indexes.
Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed.
-Use `Array.length = 0` to mutate the passed in array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
+Use `Array.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
Use `Array.push()` to keep track of pulled values
```js
@@ -624,7 +738,7 @@ const pullAtIndex = (arr, pullArr) => {
Mutates the original array to filter out the values specified. Returns the removed elements.
Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed.
-Use `Array.length = 0` to mutate the passed in array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
+Use `Array.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
Use `Array.push()` to keep track of pulled values
```js
@@ -668,7 +782,7 @@ const remove = (arr, func) =>
Returns a random element from an array.
-Use `Math.random()` to generate a random number, multiply it with `length` and round it of to the nearest whole number using `Math.floor()`.
+Use `Math.random()` to generate a random number, multiply it by `length` and round it of to the nearest whole number using `Math.floor()`.
This method also works with strings.
```js
@@ -724,7 +838,7 @@ const symmetricDifference = (a, b) => {
Returns all elements in an array except for the first one.
-Return `arr.slice(1)` if the array's `length` is more than `1`, otherwise return the whole array.
+Return `arr.slice(1)` if the array's `length` is more than `1`, otherwise, return the whole array.
```js
const tail = arr => arr.length > 1 ? arr.slice(1) : arr;
@@ -878,6 +992,7 @@ it is partially visible.
```js
const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
const { top, left, bottom, right } = el.getBoundingClientRect();
+ const { innerHeight, innerWidth } = window;
return partiallyVisible
? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
@@ -957,7 +1072,7 @@ const redirect = (url, asLink = true) =>
Smooth-scrolls to the top of the page.
Get distance from top using `document.documentElement.scrollTop` or `document.body.scrollTop`.
-Scroll by a fraction of the distance from top. Use `window.requestAnimationFrame()` to animate the scrolling.
+Scroll by a fraction of the distance from the top. Use `window.requestAnimationFrame()` to animate the scrolling.
```js
const scrollToTop = () => {
@@ -977,7 +1092,7 @@ const scrollToTop = () => {
Returns the difference (in days) between two dates.
-Calculate the difference (in days) between to `Date` objects.
+Calculate the difference (in days) between two `Date` objects.
```js
const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24);
@@ -1006,7 +1121,7 @@ const JSONToDate = arr => {
Converts a date from American format to English format.
-Use `Date.toISOString()`, `split('T')` and `replace()` to convert a date from American format to English format.
+Use `Date.toISOString()`, `split('T')` and `replace()` to convert a date from American format to the English format.
Throws an error if the passed time cannot be converted to a date.
```js
@@ -1062,7 +1177,7 @@ 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.
+Otherwise, return a curried function `f` 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
@@ -1108,28 +1223,6 @@ multiplyAndAdd5(5, 2) -> 15
[⬆ back to top](#table-of-contents)
-### promisify
-
-Converts an asynchronous function to return a promise.
-
-Use currying to return a function returning a `Promise` that calls the original function.
-Use the `...rest` operator to pass in all the parameters.
-
-*In Node 8+, you can use [`util.promisify`](https://nodejs.org/api/util.html#util_util_promisify_original)*
-
-```js
-const promisify = func =>
- (...args) =>
- new Promise((resolve, reject) =>
- func(...args, (err, result) =>
- err ? reject(err) : resolve(result))
- );
-// const delay = promisify((d, cb) => setTimeout(cb, d))
-// delay(2000).then(() => console.log('Hi!')) -> Promise resolves after 2s
-```
-
-[⬆ back to top](#table-of-contents)
-
### runPromisesInSeries
Runs an array of promises in series.
@@ -1196,7 +1289,7 @@ Clamps `num` within the inclusive `lower` and `upper` bounds.
If `lower` is greater than `upper`, swap them.
If `num` falls within the range, return `num`.
-Otherwise return the nearest number in the range.
+Otherwise, return the nearest number in the range.
```js
const clampNumber = (num, lower, upper) => {
@@ -1214,7 +1307,7 @@ const clampNumber = (num, lower, upper) => {
Applies the Collatz algorithm.
-If `n` is even, return `n/2`. Otherwise return `3n+1`.
+If `n` is even, return `n/2`. Otherwise, return `3n+1`.
```js
const collatz = n => (n % 2 == 0) ? (n / 2) : (3 * n + 1);
@@ -1284,6 +1377,38 @@ const fibonacci = n =>
[⬆ back to top](#table-of-contents)
+### fibonacciCountUntilNum
+
+Returns the number of fibonnacci numbers up to `num`(`0` and `num` inclusive).
+
+Use a mathematical formula to calculate the number of fibonacci numbers until `num`.
+
+```js
+const fibonacciCountUntilNum = num =>
+ Math.ceil(Math.log(num * Math.sqrt(5) + 1/2) / Math.log((Math.sqrt(5)+1)/2));
+// fibonacciCountUntilNum(10) -> 7
+```
+
+[⬆ back to top](#table-of-contents)
+
+### fibonacciUntilNum
+
+Generates an array, containing the Fibonacci sequence, up until the nth term.
+
+Create an empty array of the specific length, initializing the first two values (`0` and `1`).
+Use `Array.reduce()` to add values into the array, using the sum of the last two values, except for the first two.
+Uses a mathematical formula to calculate the length of the array required.
+
+```js
+const fibonacciUntilNum = num => {
+ let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1/2) / Math.log((Math.sqrt(5)+1)/2));
+ return Array.from({ length: n}).reduce((acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), []);
+}
+// fibonacciUntilNum(15) -> [0,1,1,2,3,5,8,13]
+```
+
+[⬆ back to top](#table-of-contents)
+
### gcd
Calculates the greatest common divisor between two numbers.
@@ -1303,7 +1428,7 @@ const gcd = (x, y) => !y ? x : gcd(y, x % y);
Calculates the Hamming distance between two values.
-Use XOR operator (`^`) to find the bit difference between the two numbers, convert to binary string using `toString(2)`.
+Use XOR operator (`^`) to find the bit difference between the two numbers, convert to a binary string using `toString(2)`.
Count and return the number of `1`s in the string, using `match(/1/g)`.
```js
@@ -1316,10 +1441,10 @@ const hammingDistance = (num1, num2) =>
### inRange
-Checks if the given number falls in the given range.
+Checks if the given number falls within the given range.
Use arithmetic comparison to check if the given number is in the specified range.
-If the second parameter, `end`, is not specified, the reange is considered to be from `0` to `start`.
+If the second parameter, `end`, is not specified, the range is considered to be from `0` to `start`.
```js
const inRange = (n, start, end=null) => {
@@ -1336,9 +1461,9 @@ const inRange = (n, start, end=null) => {
### isArmstrongNumber
-Checks if the given number is an armstrong number or not.
+Checks if the given number is an Armstrong number or not.
-Convert the given number into array of digits. Use `Math.pow()` to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return `true` otherwise `false`.
+Convert the given number into an array of digits. Use `Math.pow()` to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return `true` otherwise `false`.
```js
const isArmstrongNumber = digits =>
@@ -1622,7 +1747,7 @@ const readFileLines = filename => fs.readFileSync(filename).toString('UTF8').spl
Removes any properties except the ones specified from a JSON object.
-Use `Object.keys()` method to loop over given json object and deleting keys that are not `include`d in given array.
+Use `Object.keys()` method to loop over given JSON object and deleting keys that are not `include`d in given array.
Also if you give it a special key (`childIndicator`) it will search deeply inside it to apply function to inner objects too.
```js
@@ -1696,14 +1821,13 @@ orderby(users, ['name', 'age']) -> [{name: 'barney', age: 34}, {name: 'barney',
*/
```
-
[⬆ back to top](#table-of-contents)
### select
-Retrieve a property that indicated by the selector from object.
+Retrieve a property that indicated by the selector from an object.
-If property not exists returns `undefined`.
+If the property does not exists returns `undefined`.
```js
const select = (from, selector) =>
@@ -1799,7 +1923,7 @@ const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperC
Retuns `number` of vowels in provided string.
-Use a regular expression to count number of vowels `(A, E, I, O, U)` in a `string`.
+Use a regular expression to count the number of vowels `(A, E, I, O, U)` in a `string`.
```js
const countVowels = str => (str.match(/[aeiou]/ig) || []).length;
@@ -1826,7 +1950,7 @@ const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
Converts a string from camelcase.
-Use `replace()` to remove underscores, hyphens and spaces and convert words to camelcase.
+Use `replace()` to remove underscores, hyphens, and spaces and convert words to camelcase.
Omit the second argument to use a default separator of `_`.
```js
@@ -1840,6 +1964,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.
@@ -1872,7 +2012,7 @@ const sortCharactersInString = str =>
Converts a string to camelcase.
-Use `replace()` to remove underscores, hyphens and spaces and convert words to camelcase.
+Use `replace()` to remove underscores, hyphens, and spaces and convert words to camelcase.
```js
const toCamelCase = str =>
@@ -1885,6 +2025,42 @@ 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).
+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.
+
+```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;
+}
+// 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"
+```
+
+[⬆ 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.
@@ -1904,7 +2080,7 @@ const truncateString = (str, num) =>
Converts a given string into an array of words.
-Use `String.split()` with a supplied pattern (defaults to non alpha as a regex) to convert to an array of strings. Use `Array.filter()` to remove any empty strings.
+Use `String.split()` with a supplied pattern (defaults to non-alpha as a regex) to convert to an array of strings. Use `Array.filter()` to remove any empty strings.
Omit the second argument to use the default regex.
```js
@@ -1948,7 +2124,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('')
@@ -1976,7 +2152,7 @@ const getType = v =>
Converts a color code to a `rgb()` or `rgba()` string if alpha value is provided.
-Use bitwise right-shift operator and mask bits with `&` (and) operator to convert a hexadecimal color code (with or without prefixed with `#`) to a string with the RGB values. If it's 3-digit color code, first convert to 6-digit version. If any alpha value is provided alongside 6-digit hex, give `rgba()` string in return.
+Use bitwise right-shift operator and mask bits with `&` (and) operator to convert a hexadecimal color code (with or without prefixed with `#`) to a string with the RGB values. If it's 3-digit color code, first convert to 6-digit version. If an alpha value is provided alongside 6-digit hex, give `rgba()` string in return.
```js
const hexToRGB = hex => {
@@ -2084,7 +2260,7 @@ const isSymbol = val => typeof val === 'symbol';
### RGBToHex
-Converts the values of RGB components to a colorcode.
+Converts the values of RGB components to a color code.
Convert given RGB parameters to hexadecimal string using bitwise left-shift operator (`<<`) and `toString(16)`, then `padStart(6,'0')` to get a 6-digit hexadecimal value.
@@ -2114,20 +2290,11 @@ const timeTaken = callback => {
### toDecimalMark
-Convert a float-point arithmetic to the [Decimal mark](https://en.wikipedia.org/wiki/Decimal_mark) form.
-
-Use `toString()` to convert the float `num` to a string, then use regex to separate every three characters of the integer part with a comma.
+Use `toLocaleString()` to convert a float-point arithmetic to the [Decimal mark](https://en.wikipedia.org/wiki/Decimal_mark) form. It makes a comma separated string from a number.
```js
-const toDecimalMark = (num) => {
- let cleanNum = num.toString().split('').filter(n => '0123456789.'.includes(n)).join('')
- let wholeNum = cleanNum.split('.')[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",")
- let decNum = `.${cleanNum.split('.')[1]}`
- return wholeNum + decNum;
-}
-// toDecimalMark(12305030388.9087) //-> '12,305,030,388.9087'
-// toDecimalMark(123.889087e2) //-> '12,388.9087'
-// toDecimalMark('12305abc030388.9087') // -> '12,305,030,388.9087'
+const toDecimalMark = num => num.toLocaleString("en-US");
+// toDecimalMark(12305030388.9087) -> "12,305,030,388.9087"
```
[⬆ back to top](#table-of-contents)
@@ -2181,6 +2348,35 @@ 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
diff --git a/docs/index.html b/docs/index.html
index 58e9617c8..e69391d07 100644
--- a/docs/index.html
+++ b/docs/index.html
@@ -17,12 +17,45 @@
-
@@ -316,7 +425,7 @@ Omit the second element, depth to flatten only to a depth of
// flattenDepth([1,[2],[[[3],4],5]], 2) -> [1,2,[3],4,5]
groupBy
-
Groups the element of an array based on the given function.
+
Groups the elements of an array based on the given function.
Use Array.map() to map the values of an array to a function or property name.
Use Array.reduce() to create an object, where the keys are produced from the mapped results.
const groupBy = (arr, func) =>
@@ -333,13 +442,13 @@ Use Array.reduce() to create an object, where the keys are produced
initial
Returns all the elements of an array except the last one.
-
Use arr.slice(0,-1)to return all but the last element of the array.
+
Use arr.slice(0,-1) to return all but the last element of the array.
Maps the values of an array to an object using a function, where the key-value pairs consist of the original value as the key and the mapped value.
-
Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new Array to stor the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations).
+
Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new Array to store the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations).
const mapObject = (arr, fn) =>
(a => (a = [arr, arr.map(fn)], a[0].reduce( (acc,val,ind) => (acc[val] = a[1][ind], acc), {}) )) ( );
/*
@@ -392,7 +501,7 @@ Omit the second argument, n, to get the first element of the array.
pick
Picks the key-value pairs corresponding to the given keys from an object.
-
Use Array.reduce() to convert the filtered/picked keys back to a object with the corresponding key-value pair if the key exist in the obj.
+
Use Array.reduce() to convert the filtered/picked keys back to an object with the corresponding key-value pair if the key exists in the obj.
const pick = (obj, arr) =>
arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {});
// pick({ 'a': 1, 'b': '2', 'c': 3 }, ['a', 'c']) -> { 'a': 1, 'c': 3 }
@@ -400,7 +509,7 @@ Omit the second argument, n, to get the first element of the array.
pull
Mutates the original array to filter out the values specified.
Use Array.filter() and Array.includes() to pull out the values that are not needed.
-Use Array.length = 0 to mutate the passed in array by resetting it's length to zero and Array.push() to re-populate it with only the pulled values.
+Use Array.length = 0 to mutate the passed in an array by resetting it's length to zero and Array.push() to re-populate it with only the pulled values.
(For a snippet that does not mutate the original array see without)
const pull = (arr, ...args) => {
let argState = Array.isArray(args[0]) ? args[0] : args;
@@ -420,7 +529,7 @@ Use Array.length = 0 to mutate the passed in array by resetting it'
pullAtIndex
Mutates the original array to filter out the values at the specified indexes.
Use Array.filter() and Array.includes() to pull out the values that are not needed.
-Use Array.length = 0 to mutate the passed in array by resetting it's length to zero and Array.push() to re-populate it with only the pulled values.
+Use Array.length = 0 to mutate the passed in an array by resetting it's length to zero and Array.push() to re-populate it with only the pulled values.
Use Array.push() to keep track of pulled values
const pullAtIndex = (arr, pullArr) => {
let removed = [];
@@ -440,7 +549,7 @@ Use Array.push() to keep track of pulled values
pullAtValue
Mutates the original array to filter out the values specified. Returns the removed elements.
Use Array.filter() and Array.includes() to pull out the values that are not needed.
-Use Array.length = 0 to mutate the passed in array by resetting it's length to zero and Array.push() to re-populate it with only the pulled values.
+Use Array.length = 0 to mutate the passed in an array by resetting it's length to zero and Array.push() to re-populate it with only the pulled values.
Use Array.push() to keep track of pulled values
const pullAtValue = (arr, pullArr) => {
let removed = [],
@@ -470,7 +579,7 @@ The func is invoked with three arguments (value, index, array
sample
Returns a random element from an array.
-
Use Math.random() to generate a random number, multiply it with length and round it of to the nearest whole number using Math.floor().
+
Use Math.random() to generate a random number, multiply it by length and round it of to the nearest whole number using Math.floor().
This method also works with strings.
const sample = arr => arr[Math.floor(Math.random() * arr.length)];
// sample([3, 7, 9, 11]) -> 9
@@ -498,7 +607,7 @@ This method also works with strings.
tail
Returns all elements in an array except for the first one.
-
Return arr.slice(1) if the array's length is more than 1, otherwise return the whole array.
+
Return arr.slice(1) if the array's length is more than 1, otherwise, return the whole array.
const tail = arr => arr.length > 1 ? arr.slice(1) : arr;
// tail([1,2,3]) -> [2,3]
// tail([1]) -> [1]
@@ -579,6 +688,7 @@ Omit the second argument to determine if the element is entirely visible, or spe
it is partially visible.
const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
const { top, left, bottom, right } = el.getBoundingClientRect();
+ const { innerHeight, innerWidth } = window;
return partiallyVisible
? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
@@ -625,7 +735,7 @@ Pass a second argument to simulate a link click (true - default) or
scrollToTop
Smooth-scrolls to the top of the page.
Get distance from top using document.documentElement.scrollTop or document.body.scrollTop.
-Scroll by a fraction of the distance from top. Use window.requestAnimationFrame() to animate the scrolling.
+Scroll by a fraction of the distance from the top. Use window.requestAnimationFrame() to animate the scrolling.
const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
@@ -638,7 +748,7 @@ Scroll by a fraction of the distance from top. Use window.requestAnimation
Date
getDaysDiffBetweenDates
Returns the difference (in days) between two dates.
-
Calculate the difference (in days) between to Date objects.
+
Calculate the difference (in days) between two Date objects.
@@ -653,7 +763,7 @@ Scroll by a fraction of the distance from top. Use window.requestAnimation
toEnglishDate
Converts a date from American format to English format.
-
Use Date.toISOString(), split('T') and replace() to convert a date from American format to English format.
+
Use Date.toISOString(), split('T') and replace() to convert a date from American format to the English format.
Throws an error if the passed time cannot be converted to a date.
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.
+Otherwise, return a curried function f 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.
Generates an array, containing the Fibonacci sequence, up until the nth term.
+
Create an empty array of the specific length, initializing the first two values (0 and 1).
+Use Array.reduce() to add values into the array, using the sum of the last two values, except for the first two.
+Uses a mathematical formula to calculate the length of the array required.
Calculates the greatest common divisor between two numbers.
Use recursion.
@@ -823,16 +937,16 @@ Otherwise, return the GCD of y and the remainder of the division
hammingDistance
Calculates the Hamming distance between two values.
-
Use XOR operator (^) to find the bit difference between the two numbers, convert to binary string using toString(2).
+
Use XOR operator (^) to find the bit difference between the two numbers, convert to a binary string using toString(2).
Count and return the number of 1s in the string, using match(/1/g).
Checks if the given number falls in the given range.
+
Checks if the given number falls within the given range.
Use arithmetic comparison to check if the given number is in the specified range.
-If the second parameter, end, is not specified, the reange is considered to be from 0 to start.
+If the second parameter, end, is not specified, the range is considered to be from 0 to start.
const inRange = (n, start, end=null) => {
if(end && start > end) end = [start, start=end][0];
return (end == null) ? (n>=0 && n<start) : (n>=start && n<end);
@@ -843,8 +957,8 @@ If the second parameter, end, is not specified, the reange is consi
// inrange(3, 2) -> false
isArmstrongNumber
-
Checks if the given number is an armstrong number or not.
-
Convert the given number into array of digits. Use Math.pow() to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return true otherwise false.
+
Checks if the given number is an Armstrong number or not.
+
Convert the given number into an array of digits. Use Math.pow() to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return true otherwise false.
Removes any properties except the ones specified from a JSON object.
-
Use Object.keys() method to loop over given json object and deleting keys that are not included in given array.
+
Use Object.keys() method to loop over given JSON object and deleting keys that are not included in given array.
Also if you give it a special key (childIndicator) it will search deeply inside it to apply function to inner objects too.
Use split('') and Array.reverse() to reverse the order of the characters in the string.
@@ -1152,7 +1275,7 @@ Combine characters to get a string using join('').
toCamelCase
Converts a string to camelcase.
-
Use replace() to remove underscores, hyphens and spaces and convert words to camelcase.
+
Use replace() to remove underscores, hyphens, and spaces and convert words to camelcase.
const toCamelCase = str =>
str.replace(/^([A-Z])|[\s-_]+(\w)/g, (match, p1, p2, offset) => p2 ? p2.toUpperCase() : p1.toLowerCase());
// toCamelCase("some_database_field_name") -> 'someDatabaseFieldName'
@@ -1160,6 +1283,29 @@ Combine characters to get a string using join('').
// toCamelCase("some-javascript-property") -> 'someJavascriptProperty'
// toCamelCase("some-mixed_string with spaces_underscores-and-hyphens") -> 'someMixedStringWithSpacesUnderscoresAndHyphens'
+
toKebabCase
+
Converts a string to kebab case.
+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.
Determine if the string's length is greater than num.
@@ -1170,7 +1316,7 @@ Return the string truncated to the desired length, with ... appende
words
Converts a given string into an array of words.
-
Use String.split() with a supplied pattern (defaults to non alpha as a regex) to convert to an array of strings. Use Array.filter() to remove any empty strings.
+
Use String.split() with a supplied pattern (defaults to non-alpha as a regex) to convert to an array of strings. Use Array.filter() to remove any empty strings.
Omit the second argument to use the default regex.
const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean);
// words("I love javaScript!!") -> ["I", "love", "javaScript"]
@@ -1193,7 +1339,7 @@ Omit the second argument to use the default regex.
extendHex
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.
const extendHex = shortHex =>
'#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split('').map(x => x+x).join('')
// extendHex('#03f') -> '#0033ff'
@@ -1208,7 +1354,7 @@ Omit the second argument to use the default regex.
hexToRGB
Converts a color code to a rgb() or rgba() string if alpha value is provided.
-
Use bitwise right-shift operator and mask bits with & (and) operator to convert a hexadecimal color code (with or without prefixed with #) to a string with the RGB values. If it's 3-digit color code, first convert to 6-digit version. If any alpha value is provided alongside 6-digit hex, give rgba() string in return.
+
Use bitwise right-shift operator and mask bits with & (and) operator to convert a hexadecimal color code (with or without prefixed with #) to a string with the RGB values. If it's 3-digit color code, first convert to 6-digit version. If an alpha value is provided alongside 6-digit hex, give rgba() string in return.
const hexToRGB = hex => {
let alpha = false, h = hex.slice(hex.startsWith('#') ? 1 : 0);
if (h.length === 3) h = [...h].map(x => x + x).join('');
@@ -1268,7 +1414,7 @@ Omit the second argument to use the default regex.
// isSymbol(Symbol('x')) -> true
RGBToHex
-
Converts the values of RGB components to a colorcode.
+
Converts the values of RGB components to a color code.
Convert given RGB parameters to hexadecimal string using bitwise left-shift operator (<<) and toString(16), then padStart(6,'0') to get a 6-digit hexadecimal value.
const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
// RGBToHex(255, 165, 1) -> 'ffa501'
@@ -1284,17 +1430,9 @@ Omit the second argument to use the default regex.
// (logged): timeTaken: 0.02099609375ms
toDecimalMark
-
Convert a float-point arithmetic to the Decimal mark form.
-
Use toString() to convert the float num to a string, then use regex to separate every three characters of the integer part with a comma.