Merge branch 'master' into event-utils
This commit is contained in:
@ -1,16 +0,0 @@
|
||||
### JSONToDate
|
||||
|
||||
Converts a JSON object to a date.
|
||||
|
||||
Use `Date()`, to convert dates in JSON format to readable format (`dd/mm/yyyy`).
|
||||
|
||||
```js
|
||||
const JSONToDate = arr => {
|
||||
const dt = new Date(parseInt(arr.toString().substr(6)));
|
||||
return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`;
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
JSONToDate(/Date(1489525200000)/); // "14/3/2017"
|
||||
```
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
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.
|
||||
Convert given RGB parameters to hexadecimal string using bitwise left-shift operator (`<<`) and `toString(16)`, then `String.padStart(6,'0')` to get a 6-digit hexadecimal value.
|
||||
|
||||
```js
|
||||
const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
|
||||
|
||||
@ -1,17 +1,14 @@
|
||||
### average
|
||||
|
||||
Returns the average of an of two or more numbers/arrays.
|
||||
Returns the average of an of two or more numbers.
|
||||
|
||||
Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array.
|
||||
|
||||
```js
|
||||
const average = (...arr) => {
|
||||
const nums = [].concat(...arr);
|
||||
return nums.reduce((acc, val) => acc + val, 0) / nums.length;
|
||||
};
|
||||
const average = (...nums) => [...nums].reduce((acc, val) => acc + val, 0) / nums.length;
|
||||
```
|
||||
|
||||
```js
|
||||
average([1, 2, 3]); // 2
|
||||
average(...[1, 2, 3]); // 2
|
||||
average(1, 2, 3); // 2
|
||||
```
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
### byteSize
|
||||
|
||||
Returns the length of string.
|
||||
Returns the length of a string in bytes.
|
||||
|
||||
Convert a given string to a [`Blob` Object](https://developer.mozilla.org/en-US/docs/Web/API/Blob) and find its `size`.
|
||||
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
Capitalizes the first letter of a string.
|
||||
|
||||
Use destructuring and `toUpperCase()` to capitalize first letter, `...rest` to get array of characters after first letter and then `Array.join('')` to make it a string again.
|
||||
Use array destructuring and `String.toUpperCase()` to capitalize first letter, `...rest` to get array of characters after first letter and then `Array.join('')` to make it a string again.
|
||||
Omit the `lowerRest` parameter to keep the rest of the string intact, or set it to `true` to convert to lowercase.
|
||||
|
||||
```js
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
Capitalizes the first letter of every word in a string.
|
||||
|
||||
Use `replace()` to match the first character of each word and `toUpperCase()` to capitalize it.
|
||||
Use `String.replace()` to match the first character of each word and `String.toUpperCase()` to capitalize it.
|
||||
|
||||
```js
|
||||
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
|
||||
|
||||
@ -2,8 +2,8 @@
|
||||
|
||||
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.
|
||||
Also if you give it a special key (`childIndicator`) it will search deeply inside it to apply function to inner objects too.
|
||||
Use `Object.keys()` method to loop over given JSON object and deleting keys that are not included in given array.
|
||||
If you pass a special key,`childIndicator`, it will search deeply apply the function to inner objects, too.
|
||||
|
||||
```js
|
||||
const cleanObj = (obj, keysToKeep = [], childIndicator) => {
|
||||
|
||||
@ -1,13 +0,0 @@
|
||||
### collatz
|
||||
|
||||
Applies the Collatz algorithm.
|
||||
|
||||
If `n` is even, return `n/2`. Otherwise, return `3n+1`.
|
||||
|
||||
```js
|
||||
const collatz = n => (n % 2 == 0 ? n / 2 : 3 * n + 1);
|
||||
```
|
||||
|
||||
```js
|
||||
collatz(8); // 4
|
||||
```
|
||||
@ -5,7 +5,7 @@ Counts the occurrences of a value in an array.
|
||||
Use `Array.reduce()` to increment a counter each time you encounter the specific value inside the array.
|
||||
|
||||
```js
|
||||
const countOccurrences = (arr, value) => arr.reduce((a, v) => (v === value ? a + 1 : a + 0), 0);
|
||||
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a + 0), 0);
|
||||
```
|
||||
|
||||
```js
|
||||
|
||||
@ -2,11 +2,11 @@
|
||||
|
||||
Converts a number to an array of digits.
|
||||
|
||||
Convert the number to a string, using spread operators in ES6(`[...string]`) build an array.
|
||||
Convert the number to a string, using the spread operator (`...`) to build an array.
|
||||
Use `Array.map()` and `parseInt()` to transform each value to an integer.
|
||||
|
||||
```js
|
||||
const digitize = n => [...('' + n)].map(i => parseInt(i));
|
||||
const digitize = n => [...`${n}`].map(i => parseInt(i));
|
||||
```
|
||||
|
||||
```js
|
||||
|
||||
@ -4,8 +4,10 @@ Computes the new ratings between two or more opponents using the [Elo rating sys
|
||||
of pre-ratings and returns an array containing post-ratings.
|
||||
The array should be ordered from best performer to worst performer (winner -> loser).
|
||||
|
||||
Use the exponent `**` operator and math operators to compute the expected score (chance of winning)
|
||||
of each opponent and compute the new rating for each. Loop through the ratings, using each permutation to compute the post-Elo rating for each player in a pairwise fashion. Omit the second argument to use the default K-factor of 32, or supply a custom K-factor value. For details on the third argument, see the last example.
|
||||
Use the exponent `**` operator and math operators to compute the expected score (chance of winning).
|
||||
of each opponent and compute the new rating for each.
|
||||
Loop through the ratings, using each permutation to compute the post-Elo rating for each player in a pairwise fashion.
|
||||
Omit the second argument to use the default `kFactor` of 32.
|
||||
|
||||
```js
|
||||
const elo = ([...ratings], kFactor = 32, selfRating) => {
|
||||
@ -35,7 +37,7 @@ elo([1200, 1200], 64); // [1232, 1168]
|
||||
// 4 player FFA, all same rank
|
||||
elo([1200, 1200, 1200, 1200]).map(Math.round); // [1246, 1215, 1185, 1154]
|
||||
/*
|
||||
For teams, each rating can adjusted based on own team's average rating vs.
|
||||
For teams, each rating can adjusted based on own team's average rating vs.
|
||||
average rating of opposing team, with the score being added to their
|
||||
own individual rating by supplying it as the third argument.
|
||||
*/
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
Escapes a string for use in HTML.
|
||||
|
||||
Use `String.replace()` with a regex that matches the characters that need to be escaped, using a callback function to replace each character instance with its associated escaped character using a dictionary (object).
|
||||
Use `String.replace()` with a regexp that matches the characters that need to be escaped, using a callback function to replace each character instance with its associated escaped character using a dictionary (object).
|
||||
|
||||
```js
|
||||
const escapeHTML = str =>
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
Escapes a string to use in a regular expression.
|
||||
|
||||
Use `replace()` to escape special characters.
|
||||
Use `String.replace()` to escape special characters.
|
||||
|
||||
```js
|
||||
const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
|
||||
@ -2,8 +2,9 @@
|
||||
|
||||
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.
|
||||
`String.slice()` is used to remove `#` from string start since it's added once.
|
||||
Use `Array.map()`, `String.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.
|
||||
|
||||
```js
|
||||
const extendHex = shortHex =>
|
||||
'#' +
|
||||
|
||||
@ -1,42 +0,0 @@
|
||||
### factors
|
||||
|
||||
Returns the array of factors of the given `num`.
|
||||
If the second argument is set to `true` returns only the prime factors of `num`.
|
||||
If `num` is `1` or `0` returns an empty array.
|
||||
If `num` is less than `0` returns all the factors of `-int` together with their additive inverses.
|
||||
|
||||
Use `Array.from()`, `Array.map()` and `Array.filter()` to find all the factors of `num`.
|
||||
If given `num` is negative, use `Array.reduce()` to add the additive inverses to the array.
|
||||
Return all results if `primes` is `false`, else determine and return only the prime factors using `isPrime` and `Array.filter()`.
|
||||
Omit the second argument, `primes`, to return prime and non-prime factors by default.
|
||||
|
||||
**Note**:- _Negative numbers are not considered prime._
|
||||
|
||||
```js
|
||||
const factors = (num, primes = false) => {
|
||||
const isPrime = num => {
|
||||
const boundary = Math.floor(Math.sqrt(num));
|
||||
for (var i = 2; i <= boundary; i++) if (num % i === 0) return false;
|
||||
return num >= 2;
|
||||
};
|
||||
const isNeg = num < 0;
|
||||
num = isNeg ? -num : num;
|
||||
let array = Array.from({ length: num - 1 })
|
||||
.map((val, i) => (num % (i + 2) === 0 ? i + 2 : false))
|
||||
.filter(val => val);
|
||||
if (isNeg)
|
||||
array = array.reduce((acc, val) => {
|
||||
acc.push(val);
|
||||
acc.push(-val);
|
||||
return acc;
|
||||
}, []);
|
||||
return primes ? array.filter(isPrime) : array;
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
factors(12); // [2,3,4,6,12]
|
||||
factors(12, true); // [2,3]
|
||||
factors(-12); // [2, -2, 3, -3, 4, -4, 6, -6, 12, -12]
|
||||
factors(-12, true); // [2,3]
|
||||
```
|
||||
@ -1,14 +0,0 @@
|
||||
### 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));
|
||||
```
|
||||
|
||||
```js
|
||||
fibonacciCountUntilNum(10); // 7
|
||||
```
|
||||
@ -1,21 +0,0 @@
|
||||
### 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),
|
||||
[]
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
fibonacciUntilNum(10); // [ 0, 1, 1, 2, 3, 5, 8 ]
|
||||
```
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
Flattens an array.
|
||||
|
||||
Use a new array and concatenate it with the spread input array causing a shallow denesting of any contained arrays.
|
||||
Use a new array, `Array.concat()` and the spread operator (`...`) to cause a shallow denesting of any contained arrays.
|
||||
|
||||
```js
|
||||
const flatten = arr => [].concat(...arr);
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
### flip
|
||||
|
||||
Flip takes a function as an argument, then makes the first argument the last
|
||||
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.
|
||||
|
||||
|
||||
@ -2,8 +2,8 @@
|
||||
|
||||
Converts a string from camelcase.
|
||||
|
||||
Use `replace()` to remove underscores, hyphens, and spaces and convert words to camelcase.
|
||||
Omit the second argument to use a default separator of `_`.
|
||||
Use `String.replace()` to remove underscores, hyphens, and spaces and convert words to camelcase.
|
||||
Omit the second argument to use a default `separator` of `_`.
|
||||
|
||||
```js
|
||||
const fromCamelCase = (str, separator = '_') =>
|
||||
|
||||
@ -9,10 +9,11 @@ Otherwise, return the GCD of `y` and the remainder of the division `x/y`.
|
||||
```js
|
||||
const gcd = (...arr) => {
|
||||
const _gcd = (x, y) => (!y ? x : gcd(y, x % y));
|
||||
return [].concat(...arr).reduce((a, b) => _gcd(a, b));
|
||||
return [...arr].reduce((a, b) => _gcd(a, b));
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
gcd(8, 36); // 4
|
||||
gcd(...[12, 8, 32]); // 4
|
||||
```
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
Returns the native type of a value.
|
||||
|
||||
Returns lowercased constructor name of value, "undefined" or "null" if value is undefined or null
|
||||
Returns lowercased constructor name of value, `"undefined"` or `"null"` if value is `undefined` or `null`.
|
||||
|
||||
```js
|
||||
const getType = v =>
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
Returns an object containing the parameters of the current URL.
|
||||
|
||||
Use `match()` with an appropriate regular expression to get all key-value pairs, `Array.reduce()` to map and combine them into a single object.
|
||||
Use `String.match()` with an appropriate regular expression to get all key-value pairs, `Array.reduce()` to map and combine them into a single object.
|
||||
Pass `location.search` as the argument to apply to the current `url`.
|
||||
|
||||
```js
|
||||
|
||||
@ -1,29 +0,0 @@
|
||||
### howManyTimes
|
||||
|
||||
Returns the number of times `num` can be divided by `divisor` (integer or fractional) without getting a fractional answer.
|
||||
Works for both negative and positive integers.
|
||||
|
||||
If `divisor` is `-1` or `1` return `Infinity`.
|
||||
If `divisor` is `-0` or `0` return `0`.
|
||||
Otherwise, keep dividing `num` with `divisor` and incrementing `i`, while the result is an integer.
|
||||
Return the number of times the loop was executed, `i`.
|
||||
|
||||
```js
|
||||
const howManyTimes = (num, divisor) => {
|
||||
if (divisor === 1 || divisor === -1) return Infinity;
|
||||
if (divisor === 0) return 0;
|
||||
let i = 0;
|
||||
while (Number.isInteger(num / divisor)) {
|
||||
i++;
|
||||
num = num / divisor;
|
||||
}
|
||||
return i;
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
howManyTimes(100, 2); // 2
|
||||
howManyTimes(100, 2.5); // 2
|
||||
howManyTimes(100, 0); // 0
|
||||
howManyTimes(100, -1); // Infinity
|
||||
```
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
Initializes an array containing the numbers in the specified range where `start` and `end` are inclusive with there common difference `step`.
|
||||
|
||||
Use `Array(Math.ceil((end+1-start)/step)` to create an array of the desired length(the amounts of elements is equal to `(end-start)/step` or `(end+1-start)/step` for inclusive end), `Array.map()` to fill with the desired values in a range.
|
||||
Use `Array.from(Math.ceil((end+1-start)/step))` to create an array of the desired length(the amounts of elements is equal to `(end-start)/step` or `(end+1-start)/step` for inclusive end), `Array.map()` to fill with the desired values in a range.
|
||||
You can omit `start` to use a default value of `0`.
|
||||
You can omit `step` to use a default value of `1`.
|
||||
|
||||
|
||||
@ -3,10 +3,10 @@
|
||||
Initializes and fills an array with the specified values.
|
||||
|
||||
Use `Array(n)` to create an array of the desired length, `fill(v)` to fill it with the desired values.
|
||||
You can omit `value` to use a default value of `0`.
|
||||
You can omit `val` to use a default value of `0`.
|
||||
|
||||
```js
|
||||
const initializeArrayWithValues = (n, value = 0) => Array(n).fill(value);
|
||||
const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val);
|
||||
```
|
||||
|
||||
```js
|
||||
|
||||
@ -1,17 +0,0 @@
|
||||
### isArmstrongNumber
|
||||
|
||||
Checks if the given number is an Armstrong number or not.
|
||||
|
||||
Convert the given number into an array of digits. Use the exponent operator (`**`) 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 =>
|
||||
(arr => arr.reduce((a, d) => a + parseInt(d) ** arr.length, 0) == digits)(
|
||||
(digits + '').split('')
|
||||
);
|
||||
```
|
||||
|
||||
```js
|
||||
isArmstrongNumber(1634); // true
|
||||
isArmstrongNumber(56); // false
|
||||
```
|
||||
@ -5,10 +5,9 @@ Checks if the given argument is an array.
|
||||
Use `Array.isArray()` to check if a value is classified as an array.
|
||||
|
||||
```js
|
||||
const isArray = val => !!val && Array.isArray(val);
|
||||
const isArray = val => Array.isArray(val);
|
||||
```
|
||||
|
||||
```js
|
||||
isArray(null); // false
|
||||
isArray([1]); // true
|
||||
```
|
||||
|
||||
@ -9,7 +9,6 @@ const isFunction = val => typeof val === 'function';
|
||||
```
|
||||
|
||||
```js
|
||||
isFunction(null); // false
|
||||
isFunction('x'); // false
|
||||
isFunction(x => x); // true
|
||||
```
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
### lcm
|
||||
|
||||
Returns the least common multiple of two or more numbers/arrays.
|
||||
Returns the least common multiple of two or more numbers.
|
||||
|
||||
Use the greatest common divisor (GCD) formula and `Math.abs()` to determine the least common multiple.
|
||||
The GCD formula uses recursion.
|
||||
@ -9,11 +9,11 @@ The GCD formula uses recursion.
|
||||
const lcm = (...arr) => {
|
||||
const gcd = (x, y) => (!y ? x : gcd(y, x % y));
|
||||
const _lcm = (x, y) => x * y / gcd(x, y);
|
||||
return [].concat(...arr).reduce((a, b) => _lcm(a, b));
|
||||
return [...arr].reduce((a, b) => _lcm(a, b));
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
lcm(12, 7); // 84
|
||||
lcm([1, 3, 4], 5); // 60
|
||||
lcm(...[1, 3, 4, 5]); // 60
|
||||
```
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
Replaces all but the last `num` of characters with the specified mask character.
|
||||
|
||||
Use `String.slice()` to grab the portion of the characters that need to be masked and use `String.replace()` with a regex to replace every character with the mask character.
|
||||
Use `String.slice()` to grab the portion of the characters that need to be masked and use `String.replace()` with a regexp to replace every character with the mask character.
|
||||
Concatenate the masked characters with the remaining unmasked portion of the string.
|
||||
Omit the second argument, `num`, to keep a default of `4` characters unmasked. If `num` is negative, the unmasked characters will be at the start of the string.
|
||||
Omit the third argument, `mask`, to use a default character of `'*'` for the mask.
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
Negates a predicate function.
|
||||
|
||||
Take a predicate function and apply `not` to it with its arguments.
|
||||
Take a predicate function and apply the not operator (`!`) to it with its arguments.
|
||||
|
||||
```js
|
||||
const negate = func => (...args) => !func(...args);
|
||||
|
||||
@ -2,8 +2,8 @@
|
||||
|
||||
Returns a sorted array of objects ordered by properties and orders.
|
||||
|
||||
Uses a custom implementation of sort, that reduces the props array argument with a default value of 0, it uses destructuring to swap the properties position depending on the order passed.
|
||||
If no orders array is passed it sort by 'asc' by default.
|
||||
Uses `Array.sort()`, `Array.reduce()` on the `props` array with a default value of `0`, use array destructuring to swap the properties position depending on the order passed.
|
||||
If no `orders` array is passed it sort by `'asc'` by default.
|
||||
|
||||
```js
|
||||
const orderBy = (arr, props, orders) =>
|
||||
|
||||
@ -2,8 +2,8 @@
|
||||
|
||||
Returns `true` if the given string is a palindrome, `false` otherwise.
|
||||
|
||||
Convert string `toLowerCase()` and use `replace()` to remove non-alphanumeric characters from it.
|
||||
Then, `split('')` into individual characters, `reverse()`, `join('')` and compare to the original, unreversed string, after converting it `tolowerCase()`.
|
||||
Convert string `String.toLowerCase()` and use `String.replace()` to remove non-alphanumeric characters from it.
|
||||
Then, `String.split('')` into individual characters, `Array.reverse()`, `String.join('')` and compare to the original, unreversed string, after converting it `String.tolowerCase()`.
|
||||
|
||||
```js
|
||||
const palindrome = str => {
|
||||
|
||||
@ -1,23 +0,0 @@
|
||||
### quickSort
|
||||
|
||||
QuickSort an Array (ascending sort by default).
|
||||
|
||||
Use recursion.
|
||||
Use `Array.filter` and spread operator (`...`) to create an array that all elements with values less than the pivot come before the pivot, and all elements with values greater than the pivot come after it.
|
||||
If the parameter `desc` is truthy, return array sorts in descending order.
|
||||
|
||||
```js
|
||||
const quickSort = ([n, ...nums], desc) =>
|
||||
isNaN(n)
|
||||
? []
|
||||
: [
|
||||
...quickSort(nums.filter(v => (desc ? v > n : v <= n)), desc),
|
||||
n,
|
||||
...quickSort(nums.filter(v => (!desc ? v > n : v <= n)), desc)
|
||||
];
|
||||
```
|
||||
|
||||
```js
|
||||
quickSort([4, 1, 3, 2]); // [1,2,3,4]
|
||||
quickSort([4, 1, 3, 2], true); // [4,3,2,1]
|
||||
```
|
||||
@ -1,16 +0,0 @@
|
||||
### 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;
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
repeatString('abc', 3); // 'abcabcabc'
|
||||
repeatString('abc'); // 'abcabc'
|
||||
```
|
||||
@ -2,13 +2,15 @@
|
||||
|
||||
Reverses a string.
|
||||
|
||||
Use `split('')` and `Array.reverse()` to reverse the order of the characters in the string.
|
||||
Combine characters to get a string using `join('')`.
|
||||
Use the spread operator (`...`) and `Array.reverse()` to reverse the order of the characters in the string.
|
||||
Combine characters to get a string using `String.join('')`.
|
||||
|
||||
```js
|
||||
|
||||
|
||||
|
||||
const reverseString = str =>
|
||||
str
|
||||
.split('')
|
||||
[..str]
|
||||
.reverse()
|
||||
.join('');
|
||||
```
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
### sbdm
|
||||
|
||||
This algorithm is a simple hash-algorithm that hashes it input string `s` into a whole number.
|
||||
Hashes the input string into a whole number.
|
||||
|
||||
Use `split('')` and `Array.reduce()` to create a hash of the input string, utilizing bit shifting.
|
||||
Use `String.split('')` and `Array.reduce()` to create a hash of the input string, utilizing bit shifting.
|
||||
|
||||
```js
|
||||
const sdbm = str => {
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
### select
|
||||
|
||||
Retrieve a property that indicated by the selector from an object.
|
||||
Retrieve a property indicated by the selector from an object.
|
||||
|
||||
If the property does not exists returns `undefined`.
|
||||
|
||||
|
||||
@ -2,10 +2,10 @@
|
||||
|
||||
Sets the value of a CSS rule for the specified element.
|
||||
|
||||
Use `element.style` to set the value of the CSS rule for the specified element to `value`.
|
||||
Use `element.style` to set the value of the CSS rule for the specified element to `val`.
|
||||
|
||||
```js
|
||||
const setStyle = (el, ruleName, value) => (el.style[ruleName] = value);
|
||||
const setStyle = (el, ruleName, val) => (el.style[ruleName] = val);
|
||||
```
|
||||
|
||||
```js
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
Randomizes the order of the values of an array, returning a new array.
|
||||
|
||||
Uses the Fisher-Yates algorithm to reorder the elements of the array, based on the [Lodash implementation](https://github.com/lodash/lodash/blob/b2ea6b1cd251796dcb5f9700c4911a7b6223920b/shuffle.js), but as a pure function.
|
||||
Uses the [Fisher-Yates algorithm](https://github.com/chalarangelo/30-seconds-of-code#shuffle) to reorder the elements of the array.
|
||||
|
||||
```js
|
||||
const shuffle = ([...arr]) => {
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
Returns an array of elements that appear in both arrays.
|
||||
|
||||
Use `filter()` to remove values that are not part of `values`, determined using `includes()`.
|
||||
Use `Array.filter()` to remove values that are not part of `values`, determined using `Array.includes()`.
|
||||
|
||||
```js
|
||||
const similarity = (arr, values) => arr.filter(v => values.includes(v));
|
||||
|
||||
@ -2,20 +2,20 @@
|
||||
|
||||
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.
|
||||
Get type of `val` (`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 `val` 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;
|
||||
const size = val =>
|
||||
Array.isArray(val)
|
||||
? val.length
|
||||
: val && typeof val === 'object'
|
||||
? val.size || val.length || Object.keys(val).length
|
||||
: typeof val === 'string' ? new Blob([val]).size : 0;
|
||||
```
|
||||
|
||||
```js
|
||||
|
||||
@ -1,45 +0,0 @@
|
||||
### solveRPN
|
||||
|
||||
Solves the given mathematical expression in [reverse polish notation](https://en.wikipedia.org/wiki/Reverse_Polish_notation).
|
||||
Throws appropriate errors if there are unrecognized symbols or the expression is wrong. The valid operators are :- `+`,`-`,`*`,`/`,`^`,`**` (`^`&`**` are the exponential symbols and are same). This snippet does not supports any unary operators.
|
||||
|
||||
Use a dictionary, `OPERATORS` to specify each operator's matching mathematical operation.
|
||||
Use `String.replace()` with a regular expression to replace `^` with `**`, `String.split()` to tokenize the string and `Array.filter()` to remove empty tokens.
|
||||
Use `Array.forEach()` to parse each `symbol`, evaluate it as a numeric value or operator and solve the mathematical expression.
|
||||
Numeric values are converted to floating point numbers and pushed to a `stack`, while operators are evaluated using the `OPERATORS` dictionary and pop elements from the `stack` to apply operations.
|
||||
|
||||
```js
|
||||
const solveRPN = rpn => {
|
||||
const OPERATORS = {
|
||||
'*': (a, b) => a * b,
|
||||
'+': (a, b) => a + b,
|
||||
'-': (a, b) => a - b,
|
||||
'/': (a, b) => a / b,
|
||||
'**': (a, b) => a ** b
|
||||
};
|
||||
const [stack, solve] = [
|
||||
[],
|
||||
rpn
|
||||
.replace(/\^/g, '**')
|
||||
.split(/\s+/g)
|
||||
.filter(el => !/\s+/.test(el) && el !== '')
|
||||
];
|
||||
solve.forEach(symbol => {
|
||||
if (!isNaN(parseFloat(symbol)) && isFinite(symbol)) {
|
||||
stack.push(symbol);
|
||||
} else if (Object.keys(OPERATORS).includes(symbol)) {
|
||||
const [a, b] = [stack.pop(), stack.pop()];
|
||||
stack.push(OPERATORS[symbol](parseFloat(b), parseFloat(a)));
|
||||
} else {
|
||||
throw `${symbol} is not a recognized symbol`;
|
||||
}
|
||||
});
|
||||
if (stack.length === 1) return stack.pop();
|
||||
else throw `${rpn} is not a proper RPN. Please check it and try again`;
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
solveRPN('15 7 1 1 + - / 3 * 2 1 1 + + -'); // 5
|
||||
solveRPN('2 3 ^'); // 8
|
||||
```
|
||||
@ -2,14 +2,10 @@
|
||||
|
||||
Alphabetically sorts the characters in a string.
|
||||
|
||||
Split the string using `split('')`, `Array.sort()` utilizing `localeCompare()`, recombine using `join('')`.
|
||||
Use the spread operator (`...`), `Array.sort()` and `String.localeCompare()` to sort the characters in `str`, recombine using `String.join('')`.
|
||||
|
||||
```js
|
||||
const sortCharactersInString = str =>
|
||||
str
|
||||
.split('')
|
||||
.sort((a, b) => a.localeCompare(b))
|
||||
.join('');
|
||||
const sortCharactersInString = str => [...str].sort((a, b) => a.localeCompare(b)).join('');
|
||||
```
|
||||
|
||||
```js
|
||||
|
||||
@ -1,20 +0,0 @@
|
||||
### speechSynthesis
|
||||
|
||||
Performs speech synthesis (experimental).
|
||||
|
||||
Use `SpeechSynthesisUtterance.voice` and `window.speechSynthesis.getVoices()` to convert a message to speech.
|
||||
Use `window.speechSynthesis.speak()` to play the message.
|
||||
|
||||
Learn more about the [SpeechSynthesisUtterance interface of the Web Speech API](https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisUtterance).
|
||||
|
||||
```js
|
||||
const speechSynthesis = message => {
|
||||
const msg = new SpeechSynthesisUtterance(message);
|
||||
msg.voice = window.speechSynthesis.getVoices()[0];
|
||||
window.speechSynthesis.speak(msg);
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
speechSynthesis('Hello, World'); // // plays the message
|
||||
```
|
||||
@ -5,9 +5,9 @@ Returns the sum of two or more numbers/arrays.
|
||||
Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`.
|
||||
|
||||
```js
|
||||
const sum = (...arr) => [].concat(...arr).reduce((acc, val) => acc + val, 0);
|
||||
const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0);
|
||||
```
|
||||
|
||||
```js
|
||||
sum([1, 2, 3, 4]); // 10
|
||||
sum(...[1, 2, 3, 4]); // 10
|
||||
```
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
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 `Array.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);
|
||||
|
||||
@ -2,8 +2,7 @@
|
||||
|
||||
Converts a string 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).
|
||||
Break the string into words and combine them capitalizing the first letter of each word, using a regexp.
|
||||
|
||||
```js
|
||||
const toCamelCase = str => {
|
||||
|
||||
@ -2,8 +2,7 @@
|
||||
|
||||
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).
|
||||
Break the string into words and combine them adding `-` as a separator, using a regexp.
|
||||
|
||||
```js
|
||||
const toKebabCase = str =>
|
||||
|
||||
@ -2,8 +2,7 @@
|
||||
|
||||
Converts a string to snake 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).
|
||||
Break the string into words and combine them adding `_` as a separator, using a regexp.
|
||||
|
||||
```js
|
||||
const toSnakeCase = str =>
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
### tomorrow
|
||||
|
||||
Results in a string representation of tomorrow's date.
|
||||
Use `new Date()` to get today's date, adding `86400000` of seconds to it(24 hours), using `toISOString` to convert Date object to string.
|
||||
Use `new Date()` to get today's date, adding `86400000` of seconds to it(24 hours), using `Date.toISOString()` to convert Date object to string.
|
||||
|
||||
```js
|
||||
const tomorrow = () => new Date(new Date().getTime() + 86400000).toISOString().split('T')[0];
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
Truncates a string up to a specified length.
|
||||
|
||||
Determine if the string's `length` is greater than `num`.
|
||||
Return the string truncated to the desired length, with `...` appended to the end or the original string.
|
||||
Return the string truncated to the desired length, with `'...'` appended to the end or the original string.
|
||||
|
||||
```js
|
||||
const truncateString = (str, num) =>
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
Returns `true` if the given value is a number, `false` otherwise.
|
||||
|
||||
Use `!isNaN` in combination with `parseFloat()` to check if the argument is a number.
|
||||
Use `!isNaN()` in combination with `parseFloat()` to check if the argument is a number.
|
||||
Use `isFinite()` to check if the number is finite.
|
||||
Use `Number()` to check if the coercion holds.
|
||||
|
||||
|
||||
@ -2,8 +2,8 @@
|
||||
|
||||
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.
|
||||
Omit the second argument to use the default regex.
|
||||
Use `String.split()` with a supplied pattern (defaults to non-alpha as a regexp) to convert to an array of strings. Use `Array.filter()` to remove any empty strings.
|
||||
Omit the second argument to use the default regexp.
|
||||
|
||||
```js
|
||||
const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean);
|
||||
|
||||
Reference in New Issue
Block a user