Merge branch 'master' into isPrimitive
This commit is contained in:
@ -1,4 +1,4 @@
|
||||
### Capitalize
|
||||
### capitalize
|
||||
|
||||
Capitalizes the first letter of a string.
|
||||
|
||||
|
||||
33
snippets/copyToClipboard.md
Normal file
33
snippets/copyToClipboard.md
Normal file
@ -0,0 +1,33 @@
|
||||
### copyToClipboard
|
||||
|
||||
Copy a string to the clipboard. Only works as a result of user action (i.e. inside a `click` event listener).
|
||||
|
||||
Create a new `<textarea>` element, fill it with the supplied data and add it to the HTML document.
|
||||
Use `Selection.getRangeAt()`to store the selected range (if any).
|
||||
Use `document.execCommand('copy')` to copy to the clipboard.
|
||||
Remove the `<textarea>` element from the HTML document.
|
||||
Finally, use `Selection().addRange()` to recover the original selected range (if any).
|
||||
|
||||
```js
|
||||
const copyToClipboard = str => {
|
||||
const el = document.createElement('textarea');
|
||||
el.value = str;
|
||||
el.setAttribute('readonly', '');
|
||||
el.style.position = 'absolute';
|
||||
el.style.left = '-9999px';
|
||||
document.body.appendChild(el);
|
||||
const selected =
|
||||
document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
|
||||
el.select();
|
||||
document.execCommand('copy');
|
||||
document.body.removeChild(el);
|
||||
if (selected) {
|
||||
document.getSelection().removeAllRanges();
|
||||
document.getSelection().addRange(selected);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
copyToClipboard('Lorem ipsum'); // 'Lorem ipsum' copied to clipboard.
|
||||
```
|
||||
@ -17,5 +17,5 @@ const fibonacciUntilNum = num => {
|
||||
```
|
||||
|
||||
```js
|
||||
fibonacciCountUntilNum(10); // 7
|
||||
fibonacciUntilNum(10); // [ 0, 1, 1, 2, 3, 5, 8 ]
|
||||
```
|
||||
|
||||
15
snippets/isAbsoluteURL.md
Normal file
15
snippets/isAbsoluteURL.md
Normal file
@ -0,0 +1,15 @@
|
||||
### isAbsoluteURL
|
||||
|
||||
Returns `true` if the given string is an absolute URL, `false` otherwise.
|
||||
|
||||
Use a regular expression to test if the string is an absolute URL.
|
||||
|
||||
```js
|
||||
const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);
|
||||
```
|
||||
|
||||
```js
|
||||
isAbsoluteURL('https://google.com'); // true
|
||||
isAbsoluteURL('ftp://www.myserver.net'); // true
|
||||
isAbsoluteURL('/foo/bar'); // false
|
||||
```
|
||||
20
snippets/isArrayLike.md
Normal file
20
snippets/isArrayLike.md
Normal file
@ -0,0 +1,20 @@
|
||||
### isArrayLike
|
||||
|
||||
Checks if the provided argument is array-like (i.e. is iterable).
|
||||
|
||||
Check that the object is not a function or `null` and that its `length` property is a non-negative integer below `Number.MAX_SAFE_INTEGER`.
|
||||
|
||||
```js
|
||||
const isArrayLike = val =>
|
||||
val != null &&
|
||||
typeof val != 'function' &&
|
||||
val.length > -1 &&
|
||||
val.length % 1 == 0 &&
|
||||
val.length <= Number.MAX_SAFE_INTEGER;
|
||||
```
|
||||
|
||||
```js
|
||||
isArrayLike(document.querySelectorAll('.className')); // true
|
||||
isArrayLike('abc'); // true
|
||||
isArrayLike(null); // false
|
||||
```
|
||||
14
snippets/isNull.md
Normal file
14
snippets/isNull.md
Normal file
@ -0,0 +1,14 @@
|
||||
### isNull
|
||||
|
||||
Returns `true` if the specified value is `null`, `false` otherwise.
|
||||
|
||||
Use the strict equality operator to check if the value and of `val` are equal to `null`.
|
||||
|
||||
```js
|
||||
const isNull = val => val === null;
|
||||
```
|
||||
|
||||
```js
|
||||
isNull(null); // true
|
||||
isNull('null'); // false
|
||||
```
|
||||
@ -8,7 +8,7 @@ Return `false` if any of them divides the given number, else return `true`, unle
|
||||
```js
|
||||
const isPrime = num => {
|
||||
const boundary = Math.floor(Math.sqrt(num));
|
||||
for (var i = 2; i * i <= boundary; i++) if (num % i == 0) return false;
|
||||
for (var i = 2; i <= boundary; i++) if (num % i == 0) return false;
|
||||
return num >= 2;
|
||||
};
|
||||
```
|
||||
|
||||
22
snippets/isPromiseLike.md
Normal file
22
snippets/isPromiseLike.md
Normal file
@ -0,0 +1,22 @@
|
||||
### isPromiseLike
|
||||
|
||||
Returns `true` if an object looks like a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), `false` otherwise.
|
||||
|
||||
Check if the object is not `null`, its `typeof` matches either `object` or `function` and if it has a `.then` property, which is also a `function`.
|
||||
|
||||
```js
|
||||
const isPromiseLike = obj =>
|
||||
obj !== null &&
|
||||
(typeof obj === 'object' || typeof obj === 'function') &&
|
||||
typeof obj.then === 'function';
|
||||
```
|
||||
|
||||
```js
|
||||
isPromiseLike({
|
||||
then: function() {
|
||||
return '';
|
||||
}
|
||||
}); // true
|
||||
isPromiseLike(null); // false
|
||||
isPromiseLike({}); // false
|
||||
```
|
||||
22
snippets/isValidJSON.md
Normal file
22
snippets/isValidJSON.md
Normal file
@ -0,0 +1,22 @@
|
||||
### isValidJSON
|
||||
|
||||
Checks if the provided argument is a valid JSON.
|
||||
|
||||
Use `JSON.parse()` and a `try... catch` block to check if the provided argument is a valid JSON.
|
||||
|
||||
```js
|
||||
const isValidJSON = obj => {
|
||||
try {
|
||||
JSON.parse(obj);
|
||||
return true;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
isValidJSON('{"name":"Adam","age":20}'); // true
|
||||
isValidJSON('{"name":"Adam",age:"20"}'); // false
|
||||
isValidJSON(null); // true
|
||||
```
|
||||
20
snippets/memoize.md
Normal file
20
snippets/memoize.md
Normal file
@ -0,0 +1,20 @@
|
||||
### memoize
|
||||
|
||||
Returns the memoized (cached) function.
|
||||
|
||||
Use `Object.create(null)` to create an empty object without `Object.prototype` (so that those properties are not resolved if the input value is something like `'hasOwnProperty'`).
|
||||
Return a function which takes a single argument to be supplied to the memoized function by first checking if the function's output for that specific input value is already cached, or store and return it if not.
|
||||
|
||||
```js
|
||||
const memoize = fn => {
|
||||
const cache = Object.create(null);
|
||||
return value => cache[value] || (cache[value] = fn(value));
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
// See the `anagrams` snippet.
|
||||
const anagramsCached = memoize(anagrams);
|
||||
anagramsCached('javascript'); // takes a long time
|
||||
anagramsCached('javascript'); // returns virtually instantly since it's now cached
|
||||
```
|
||||
23
snippets/sampleSize.md
Normal file
23
snippets/sampleSize.md
Normal file
@ -0,0 +1,23 @@
|
||||
### sampleSize
|
||||
|
||||
Gets `n` random elements at unique keys from `array` up to the size of `array`.
|
||||
|
||||
Shuffle the array using the [Fisher-Yates algorithm](https://github.com/chalarangelo/30-seconds-of-code#shuffle).
|
||||
Use `Array.slice()` to get the first `n` elements.
|
||||
Omit the second argument, `n` to get only one element at random from the array.
|
||||
|
||||
```js
|
||||
const sampleSize = ([...arr], n = 1) => {
|
||||
let m = arr.length;
|
||||
while (m) {
|
||||
const i = Math.floor(Math.random() * m--);
|
||||
[arr[m], arr[i]] = [arr[i], arr[m]];
|
||||
}
|
||||
return arr.slice(0, n);
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
sampleSize([1, 2, 3], 2); // [3,1]
|
||||
sampleSize([1, 2, 3], 4); // [2,3,1]
|
||||
```
|
||||
25
snippets/size.md
Normal file
25
snippets/size.md
Normal file
@ -0,0 +1,25 @@
|
||||
### size
|
||||
|
||||
Get size of arrays, objects or strings.
|
||||
|
||||
Get type of `value` (`array`, `object` or `string`).
|
||||
Use `length` property for arrays.
|
||||
Use `length` or `size` value if available or number of keys for objects.
|
||||
Use `size` of a [`Blob` object](https://developer.mozilla.org/en-US/docs/Web/API/Blob) created from `value` for strings.
|
||||
|
||||
Split strings into array of characters with `split('')` and return its length.
|
||||
|
||||
```js
|
||||
const size = value =>
|
||||
Array.isArray(value)
|
||||
? value.length
|
||||
: value && typeof value === 'object'
|
||||
? value.size || value.length || Object.keys(value).length
|
||||
: typeof value === 'string' ? new Blob([value]).size : 0;
|
||||
```
|
||||
|
||||
```js
|
||||
size([1, 2, 3, 4, 5]); // 5
|
||||
size('size'); // 4
|
||||
size({ one: 1, two: 2, three: 3 }); // 3
|
||||
```
|
||||
19
snippets/sortedIndex.md
Normal file
19
snippets/sortedIndex.md
Normal file
@ -0,0 +1,19 @@
|
||||
### sortedIndex
|
||||
|
||||
Returns the lowest index at which value should be inserted into array in order to maintain its sort order.
|
||||
|
||||
Check if the array is sorted in descending order (loosely).
|
||||
Use `Array.findIndex()` to find the appropriate index where the element should be inserted.
|
||||
|
||||
```js
|
||||
const sortedIndex = (arr, n) => {
|
||||
const isDescending = arr[0] > arr[arr.length - 1];
|
||||
const index = arr.findIndex(el => (isDescending ? n >= el : n <= el));
|
||||
return index === -1 ? arr.length : index;
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
sortedIndex([5, 3, 2, 1], 4); // 1
|
||||
sortedIndex([30, 50], 40); // 1
|
||||
```
|
||||
@ -6,13 +6,12 @@ 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 => {
|
||||
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('_');
|
||||
};
|
||||
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('_');
|
||||
```
|
||||
|
||||
```js
|
||||
|
||||
18
snippets/yesNo.md
Normal file
18
snippets/yesNo.md
Normal file
@ -0,0 +1,18 @@
|
||||
### yesNo
|
||||
|
||||
Returns `true` if the string is `y`/`yes` or `false` if the string is `n`/`no`.
|
||||
|
||||
Use `RegExp.test()` to check if the string evaluates to `y/yes` or `n/no`.
|
||||
Omit the second argument, `def` to set the default answer as `no`.
|
||||
|
||||
```js
|
||||
const yesNo = (val, def = false) =>
|
||||
/^(y|yes)$/i.test(val) ? true : /^(n|no)$/i.test(val) ? false : def;
|
||||
```
|
||||
|
||||
```js
|
||||
yesNo('Y'); // true
|
||||
yesNo('yes'); // true
|
||||
yesNo('No'); // false
|
||||
yesNo('Foo', true); // true
|
||||
```
|
||||
Reference in New Issue
Block a user