Fully renamed and updated everything, tagged, built

This commit is contained in:
Angelos Chalaris
2017-12-17 17:55:51 +02:00
parent c209d9e972
commit 9db5e43e66
108 changed files with 1317 additions and 914 deletions

View File

@ -13,15 +13,14 @@ Here's what you can do to help:
### Snippet submission and Pull request guidelines ### Snippet submission and Pull request guidelines
- **DO NOT MODIFY THE README.md FILE!** Make changes to individual snippet files. You can optionally run `npm run build-list` to update the README.md file automatically, based on the changes you have made. - **DO NOT MODIFY THE README.md FILE!** Make changes to individual snippet files. You can optionally run `npm run build-list` to update the README.md file automatically, based on the changes you have made.
- **Snippet filenames** must correspond to the title of the snippet. For example, if your snippet is titled `### Awesome snippet` the filename should be `awesome-snippet.md`. - **Snippet filenames** must correspond to the title of the snippet. For example, if your snippet is titled `### awesomeSnippet` the filename should be `awesomeSnippet.md`.
- Use `kebab-case`, not `snake_case`. - Use `camelCase`, not `kebab-case` or `snake_case`.
- Avoid capitalization of words, except if the whole word is capitalized (e.g. `URL` should be capitalized in the filename and the snippet title). - Avoid capitalization of words, except if the whole word is capitalized (e.g. `URL` should be capitalized in the filename and the snippet title).
- If there are parentheses in the title, add them to the filename (e.g. `awesome-snippet-(extra-awesome).md` if your snippet's title is `Awesome snippet (extra awesome)`). - **Snippet titles** should have be the same as the name of the function that is present in the snippet.
- **Snippet titles** should have only the first letter of the first word capitalized. Certain words can be in capitals (e.g. `URL`, `RGB`), but this is on a per-snippet basis.
- All snippet titles must be prefixed with `###` and be at the very first line of your snippet. - All snippet titles must be prefixed with `###` and be at the very first line of your snippet.
- Snippet titles must be unique (although if you cannot find a better title, just add some placeholder at the end of the filename and title and we will figure it out). - Snippet titles must be unique (although if you cannot find a better title, just add some placeholder at the end of the filename and title and we will figure it out).
- Follow snippet titles with an empty line. - Follow snippet titles with an empty line.
- **Snippet descriptions** must be short and to the point. Try to explain *how* the snippet works and what Javascript features are used. Remember to include what functions you are using and why. - **Snippet descriptions** must be short and to the point. Try to explain *what* the snippet does and *how* the snippet works and what Javascript features are used. Remember to include what functions you are using and why.
- Follow snippet descriptions with an empty line. - Follow snippet descriptions with an empty line.
- **Snippet code** must be enclosed inside ` ```js ` and ` ``` `. - **Snippet code** must be enclosed inside ` ```js ` and ` ``` `.
- Remember to start your snippet's code on a new line below the opening backticks. - Remember to start your snippet's code on a new line below the opening backticks.

1547
README.md

File diff suppressed because it is too large Load Diff

View File

@ -55,7 +55,7 @@ try {
for(let tag of [...new Set(Object.entries(tagDbData).map(t => t[1]))].filter(v => v).sort((a,b) => a.localeCompare(b))){ for(let tag of [...new Set(Object.entries(tagDbData).map(t => t[1]))].filter(v => v).sort((a,b) => a.localeCompare(b))){
output +=`### ${capitalize(tag, true)}\n`; output +=`### ${capitalize(tag, true)}\n`;
for(let taggedSnippet of Object.entries(tagDbData).filter(v => v[1] === tag)) for(let taggedSnippet of Object.entries(tagDbData).filter(v => v[1] === tag))
output += `* [${taggedSnippet[0][0].toUpperCase() + taggedSnippet[0].replace(/-/g,' ').slice(1)}](#${taggedSnippet[0].replace(/\(/g,'').replace(/\)/g,'').toLowerCase()})\n` output += `* [\`${taggedSnippet[0]}\`](#${taggedSnippet[0].toLowerCase()})\n`
output += '\n'; output += '\n';
} }
// Loop over tags and snippets to create the list of snippets // Loop over tags and snippets to create the list of snippets

View File

@ -1,4 +1,6 @@
### Snippet title ### functionName
Explain briefly what the snippet does.
Explain briefly how the snippet works. Explain briefly how the snippet works.

View File

@ -1,9 +1,11 @@
### JSON to date ### JSONToDate
Converts a JSON object to a date.
Use `Date()`, to convert dates in JSON format to readable format (`dd/mm/yyyy`). Use `Date()`, to convert dates in JSON format to readable format (`dd/mm/yyyy`).
```js ```js
const jsonToDate = arr => { const JSONToDate = arr => {
const dt = new Date(parseInt(arr.toString().substr(6))); const dt = new Date(parseInt(arr.toString().substr(6)));
return `${ dt.getDate() }/${ dt.getMonth() + 1 }/${ dt.getFullYear() }` return `${ dt.getDate() }/${ dt.getMonth() + 1 }/${ dt.getFullYear() }`
}; };

View File

@ -1,9 +1,11 @@
### Write JSON to file ### JSONToFile
Writes a JSON object to a file.
Use `fs.writeFile()`, template literals and `JSON.stringify()` to write a `json` object to a `.json` file. Use `fs.writeFile()`, template literals and `JSON.stringify()` to write a `json` object to a `.json` file.
```js ```js
const fs = require('fs'); const fs = require('fs');
const jsonToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2)) const JSONToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2))
// jsonToFile({test: "is passed"}, 'testJsonFile') -> writes the object to 'testJsonFile.json' // jsonToFile({test: "is passed"}, 'testJsonFile') -> writes the object to 'testJsonFile.json'
``` ```

View File

@ -1,8 +1,10 @@
### RGB to hexadecimal ### RGBToHex
Converts the values of RGB components to a colorcode.
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 `padStart(6,'0')` to get a 6-digit hexadecimal value.
```js ```js
const rgbToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0'); const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
// rgbToHex(255, 165, 1) -> 'ffa501' // rgbToHex(255, 165, 1) -> 'ffa501'
``` ```

View File

@ -1,9 +1,11 @@
### UUID generator ### UUIDGenerator
Generates a UUID.
Use `crypto` API to generate a UUID, compliant with [RFC4122](https://www.ietf.org/rfc/rfc4122.txt) version 4. Use `crypto` API to generate a UUID, compliant with [RFC4122](https://www.ietf.org/rfc/rfc4122.txt) version 4.
```js ```js
const uuidGenerator = () => const UUIDGenerator = () =>
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16) (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
); );

View File

@ -1,4 +1,6 @@
### Anagrams of string (with duplicates) ### anagrams
Generates all anagrams of a string (contains duplicates).
Use recursion. Use recursion.
For each letter in the given string, create all the partial anagrams for the rest of its letters. For each letter in the given string, create all the partial anagrams for the rest of its letters.

View File

@ -1,8 +1,10 @@
### Average of array of numbers ### arrayAverage
Returns the average of an array of numbers.
Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array. Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array.
```js ```js
const average = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length; const arrayAverage = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length;
// average([1,2,3]) -> 2 // average([1,2,3]) -> 2
``` ```

View File

@ -1,4 +1,6 @@
### Get max value from array ### arrayMax
Returns the maximum value in an array.
Use `Math.max()` combined with the spread operator (`...`) to get the maximum value in the array. Use `Math.max()` combined with the spread operator (`...`) to get the maximum value in the array.

View File

@ -1,4 +1,6 @@
### Get min value from array ### arrayMin
Returns the maximum value in an array.
Use `Math.min()` combined with the spread operator (`...`) to get the minimum value in the array. Use `Math.min()` combined with the spread operator (`...`) to get the minimum value in the array.

View File

@ -1,8 +1,10 @@
### Sum of array of numbers ### arraySum
Returns the sum of an array of numbers.
Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`. Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`.
```js ```js
const sumArrayNumbers = arr => arr.reduce((acc, val) => acc + val, 0); const arraySum = arr => arr.reduce((acc, val) => acc + val, 0);
// sum([1,2,3,4]) -> 10 // sum([1,2,3,4]) -> 10
``` ```

View File

@ -1,4 +1,6 @@
### Bottom visible ### bottomVisible
Returns `true` if the bottom of the page is visible, `false` otherwise.
Use `scrollY`, `scrollHeight` and `clientHeight` to determine if the bottom of the page is visible. Use `scrollY`, `scrollHeight` and `clientHeight` to determine if the bottom of the page is visible.

View File

@ -1,4 +1,6 @@
### Capitalize first letter ### Capitalize
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 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.
Omit the `lowerRest` parameter to keep the rest of the string intact, or set it to `true` to convert to lower case. Omit the `lowerRest` parameter to keep the rest of the string intact, or set it to `true` to convert to lower case.

View File

@ -1,4 +1,6 @@
### Capitalize first letter of every word ### capitalizeEveryWord
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 `replace()` to match the first character of each word and `toUpperCase()` to capitalize it.

View File

@ -1,4 +1,6 @@
### Chain asynchronous functions ### chainAsync
Chains asynchronous functions.
Loop through an array of functions containing asynchronous events, calling `next` when each asynchronous event has completed. Loop through an array of functions containing asynchronous events, calling `next` when each asynchronous event has completed.

View File

@ -1,4 +1,6 @@
### Chunk array ### chunk
Chunks an array into smaller arrays of a specified size.
Use `Array.from()` to create a new array, that fits the number of chunks that will be produced. Use `Array.from()` to create a new array, that fits the number of chunks that will be produced.
Use `Array.slice()` to map each element of the new array to a chunk the length of `size`. Use `Array.slice()` to map each element of the new array to a chunk the length of `size`.

View File

@ -1,4 +1,6 @@
### Clean JSON object ### cleanObj
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. also if you give it a special key(`childIndicator`) it will search deeply inside it to apply function to inner objects too.

View File

@ -1,4 +1,6 @@
### Collatz algorithm ### collatz
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`.

View File

@ -1,4 +1,6 @@
### Compact ### compact
Removes falsey values from an array.
Use `Array.filter()` to filter out falsey values (`false`, `null`, `0`, `""`, `undefined`, and `NaN`). Use `Array.filter()` to filter out falsey values (`false`, `null`, `0`, `""`, `undefined`, and `NaN`).

View File

@ -1,4 +1,6 @@
### Compose functions ### compose
Performs right-to-left function composition.
Use `Array.reduce()` to perform right-to-left function composition. Use `Array.reduce()` to perform right-to-left function composition.
The last (rightmost) function can accept one or more arguments; the remaining functions must be unary. The last (rightmost) function can accept one or more arguments; the remaining functions must be unary.

View File

@ -1,4 +1,6 @@
### Count occurrences of a value in array ### countOccurrences
Counts the occurences of a value in an array.
Use `Array.reduce()` to increment a counter each time you encounter the specific value inside the array. Use `Array.reduce()` to increment a counter each time you encounter the specific value inside the array.

View File

@ -1,8 +1,10 @@
### Current URL ### currentURL
Returns the current URL.
Use `window.location.href` to get current URL. Use `window.location.href` to get current URL.
```js ```js
const currentUrl = () => window.location.href; const currentURL = () => window.location.href;
// currentUrl() -> 'https://google.com' // currentUrl() -> 'https://google.com'
``` ```

View File

@ -1,4 +1,6 @@
### Curry ### curry
Curries a function.
Use recursion. Use recursion.
If the number of provided arguments (`args`) is sufficient, call the passed function `f`. If the number of provided arguments (`args`) is sufficient, call the passed function `f`.

View File

@ -1,4 +1,6 @@
### Deep flatten array ### deepFlatten
Deep flattens an array.
Use recursion. Use recursion.
Use `Array.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array. Use `Array.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array.

View File

@ -1,4 +1,6 @@
### Array difference ### difference
Returns the difference between two arrays.
Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values not contained in `b`. Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values not contained in `b`.

View File

@ -1,7 +1,9 @@
### Number to array of digits ### digitize
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 spread operators in ES6(`[...string]`) build an array.
Use `Array.map()` and `parseInt()` to transform each value to an integer. Use `Array.map()` and `parseInt()` to transform each value to an integer.
```js ```js
const digitize = n => [...''+n].map(i => parseInt(i)); const digitize = n => [...''+n].map(i => parseInt(i));

View File

@ -1,4 +1,6 @@
### Distance between two points ### distance
Returns the distance between two points.
Use `Math.hypot()` to calculate the Euclidean distance between two points. Use `Math.hypot()` to calculate the Euclidean distance between two points.

View File

@ -1,8 +1,10 @@
### Unique values of array ### distinctValuesOfArray
Returns all the distinct values of an array.
Use ES6 `Set` and the `...rest` operator to discard all duplicated values. Use ES6 `Set` and the `...rest` operator to discard all duplicated values.
```js ```js
const uniqueValuesOfArray = arr => [...new Set(arr)]; const distinctValuesOfArray = arr => [...new Set(arr)];
// unique([1,2,2,3,4,4,5]) -> [1,2,3,4,5] // unique([1,2,2,3,4,4,5]) -> [1,2,3,4,5]
``` ```

View File

@ -1,6 +1,8 @@
### Drop elements in array ### dropElements
Loop through the array, using `Array.shift()` to drop the first element of the array until the returned value from the function is `true`. Removes elements in an array until the passed function returns `true`. Returns the remaining elements in the array.
Loop through the array, using `Array.shift()` to drop the first element of the array until the returned value from the function is `true`.
Returns the remaining elements. Returns the remaining elements.
```js ```js

View File

@ -1,4 +1,6 @@
### Element is visible in viewport ### elementIsVisibleInViewport
Returns `true` if the element specified is visible in the viewport, `false` otherwise.
Use `Element.getBoundingClientRect()` and the `window.inner(Width|Height)` values Use `Element.getBoundingClientRect()` and the `window.inner(Width|Height)` values
to determine if a given element is visible in the viewport. to determine if a given element is visible in the viewport.

View File

@ -1,4 +1,6 @@
### Escape regular expression ### escapeRegExp
Escapes a string to use in a regular expression.
Use `replace()` to escape special characters. Use `replace()` to escape special characters.

View File

@ -1,4 +1,6 @@
### Take every nth element ### everyNth
Returns every nth element in an array.
Use `Array.filter()` to create a new array that contains every nth element of a given array. Use `Array.filter()` to create a new array that contains every nth element of a given array.

View File

@ -1,6 +1,8 @@
### 3-digit hexcode to 6-digit hexcode ### extendHex
Use `Array.map()`, `split()` and `Array.join()` to join the mapped array for converting a three-digit RGB notated hexadecimal color-code to the six-digit form. 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. `Array.slice()` is used to remove `#` from string start since it's added once.
```js ```js
const extendHex = shortHex => const extendHex = shortHex =>

View File

@ -1,4 +1,6 @@
### Factorial ### factorial
Calculates the factorial of a number.
Use recursion. Use recursion.
If `n` is less than or equal to `1`, return `1`. If `n` is less than or equal to `1`, return `1`.

View File

@ -1,4 +1,6 @@
### Fibonacci array generator ### fibonacci
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`). 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. Use `Array.reduce()` to add values into the array, using the sum of the last two values, except for the first two.

View File

@ -1,4 +1,6 @@
### Filter out non-unique values in an array ### filterNonUnique
Filters out the non-unique values in an array.
Use `Array.filter()` for an array containing only the unique values. Use `Array.filter()` for an array containing only the unique values.

View File

@ -1,4 +1,6 @@
### Flatten array ### flatten
Flattens an array.
Use `Array.reduce()` to get all elements inside the array and `concat()` to flatten them. Use `Array.reduce()` to get all elements inside the array and `concat()` to flatten them.

View File

@ -1,4 +1,6 @@
### Flatten array up to depth ### flattenDepth
Flattens an array up to the specified depth.
Use recursion, decrementing `depth` by 1 for each level of depth. Use recursion, decrementing `depth` by 1 for each level of depth.
Use `Array.reduce()` and `Array.concat()` to merge elements or arrays. Use `Array.reduce()` and `Array.concat()` to merge elements or arrays.

View File

@ -1,10 +1,12 @@
### Convert string from camelcase ### fromCamelCase
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 scond argument to use a default separator of '_'. Omit the scond argument to use a default separator of `_`.
```js ```js
const fromCamelCase = (str, separator = '_') => const fromCamelCase = (str, separator = '_') =>
str.replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2') str.replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2')
.replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2').toLowerCase(); .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2').toLowerCase();
// fromCamelCase('someDatabaseFieldName', ' ') -> 'some database field name' // fromCamelCase('someDatabaseFieldName', ' ') -> 'some database field name'

View File

@ -1,4 +1,6 @@
### Log function name ### functionName
Logs the name of a function.
Use `console.debug()` and the `name` property of the passed method to log the method's name to the `debug` channel of the console. Use `console.debug()` and the `name` property of the passed method to log the method's name to the `debug` channel of the console.

View File

@ -1,10 +1,12 @@
### Greatest common divisor (GCD) ### gcd
Calculates the greatest common divisor between two numbers.
Use recursion. Use recursion.
Base case is when `y` equals `0`. In this case, return `x`. Base case is when `y` equals `0`. In this case, return `x`.
Otherwise, return the GCD of `y` and the remainder of the division `x/y`. Otherwise, return the GCD of `y` and the remainder of the division `x/y`.
```js ```js
const greatestCommonDivisor = (x, y) => !y ? x : gcd(y, x % y); const gcd = (x, y) => !y ? x : gcd(y, x % y);
// gcd (8, 36) -> 4 // gcd (8, 36) -> 4
``` ```

View File

@ -1,4 +1,6 @@
### Get days difference between dates ### getDaysDiffBetweenDates
Returns the difference (in days) between two dates.
Calculate the difference (in days) between to `Date` objects. Calculate the difference (in days) between to `Date` objects.

View File

@ -1,4 +1,6 @@
### Get scroll position ### getScrollPosition
Returns the scroll position of the current page.
Use `pageXOffset` and `pageYOffset` if they are defined, otherwise `scrollLeft` and `scrollTop`. Use `pageXOffset` and `pageYOffset` if they are defined, otherwise `scrollLeft` and `scrollTop`.
You can omit `el` to use a default value of `window`. You can omit `el` to use a default value of `window`.

View File

@ -1,4 +1,6 @@
### Get native type of value ### getType
Returns the native type of a value.
Returns lower-cased constructor name of value, "undefined" or "null" if value is undefined or null Returns lower-cased constructor name of value, "undefined" or "null" if value is undefined or null

View File

@ -1,10 +1,12 @@
### URL parameters ### getURLParameters
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 `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`. Pass `location.search` as the argument to apply to the current `url`.
```js ```js
const getUrlParameters = url => const getURLParameters = url =>
url.match(/([^?=&]+)(=([^&]*))/g).reduce( url.match(/([^?=&]+)(=([^&]*))/g).reduce(
(a, v) => (a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1), a), {} (a, v) => (a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1), a), {}
); );

View File

@ -1,4 +1,6 @@
### Group by ### groupBy
Groups the element 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.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. Use `Array.reduce()` to create an object, where the keys are produced from the mapped results.

View File

@ -1,4 +1,6 @@
### Hamming distance ### 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 binary string using `toString(2)`.
Count and return the number of `1`s in the string, using `match(/1/g)`. Count and return the number of `1`s in the string, using `match(/1/g)`.

View File

@ -1,4 +1,6 @@
### Head of list ### head
Returns the head of a list.
Use `arr[0]` to return the first element of the passed array. Use `arr[0]` to return the first element of the passed array.

View File

@ -1,9 +1,11 @@
### Hexcode to RGB ### hexToRGB
Converts a colorcode to a `rgb()` string.
Use bitwise right-shift operator and mask bits with `&` (and) operator to convert a hexadecimal color code (prefixed with `#`) to a string with the RGB values. Use bitwise right-shift operator and mask bits with `&` (and) operator to convert a hexadecimal color code (prefixed with `#`) to a string with the RGB values.
```js ```js
const hexToRgb = hex => { const hexToRGB = hex => {
const h = parseInt(hex.slice(1), 16); const h = parseInt(hex.slice(1), 16);
return `rgb(${h >> 16}, ${(h & 0x00ff00) >> 8}, ${h & 0x0000ff})`; return `rgb(${h >> 16}, ${(h & 0x00ff00) >> 8}, ${h & 0x0000ff})`;
} }

View File

@ -1,4 +1,6 @@
### Initial of list ### 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.

View File

@ -1,10 +1,12 @@
### Initialize array with range ### initializeArrayWithRange
Initialized an array containing the numbers in the specified range.
Use `Array(end-start)` to create an array of the desired length, `Array.map()` to fill with the desired values in a range. Use `Array(end-start)` to create an array of the desired length, `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 `start` to use a default value of `0`.
```js ```js
const initializeArrayRange = (end, start = 0) => const initializeArrayWithRange = (end, start = 0) =>
Array.from({ length: end - start }).map((v, i) => i + start); Array.from({ length: end - start }).map((v, i) => i + start);
// initializeArrayRange(5) -> [0,1,2,3,4] // initializeArrayRange(5) -> [0,1,2,3,4]
``` ```

View File

@ -1,9 +1,11 @@
### Initialize array with values ### initializeArrayWithValues
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. 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 `value` to use a default value of `0`.
```js ```js
const initializeArray = (n, value = 0) => Array(n).fill(value); const initializeArrayWithValues = (n, value = 0) => Array(n).fill(value);
// initializeArray(5, 2) -> [2,2,2,2,2] // initializeArray(5, 2) -> [2,2,2,2,2]
``` ```

View File

@ -1,4 +1,6 @@
### Array intersection ### intersection
Returns a list of elements that exist in both arrays.
Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values contained in `b`. Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values contained in `b`.

View File

@ -1,4 +1,6 @@
### Is array ### isArray
Checks if the given argument is an array.
Use `Array.isArray()` to check if a value is classified as an array. Use `Array.isArray()` to check if a value is classified as an array.

View File

@ -1,4 +1,6 @@
### Is boolean ### isBoolean
Checks if the given argument is a native boolean element.
Use `typeof` to check if a value is classified as a boolean primitive. Use `typeof` to check if a value is classified as a boolean primitive.

View File

@ -1,4 +1,6 @@
### Divisible by number ### isDivisible
Checks if the first numeric argument is divisible by the second one.
Use the modulo operator (`%`) to check if the remainder is equal to `0`. Use the modulo operator (`%`) to check if the remainder is equal to `0`.

View File

@ -1,4 +1,6 @@
### Even or odd number ### isEven
Returns `true` if the given number is even, `false` otherwise.
Checks whether a number is odd or even using the modulo (`%`) operator. Checks whether a number is odd or even using the modulo (`%`) operator.
Returns `true` if the number is even, `false` if the number is odd. Returns `true` if the number is even, `false` if the number is odd.

View File

@ -1,4 +1,6 @@
### Is function ### isFunction
Checks if the given argument is a function.
Use `typeof` to check if a value is classified as a function primitive. Use `typeof` to check if a value is classified as a function primitive.

View File

@ -1,4 +1,6 @@
### Is number ### isNumber
Checks if the given argument is a number.
Use `typeof` to check if a value is classified as a number primitive. Use `typeof` to check if a value is classified as a number primitive.

View File

@ -1,4 +1,6 @@
### Is string ### isString
Checks if the given argument is a string.
Use `typeof` to check if a value is classified as a string primitive. Use `typeof` to check if a value is classified as a string primitive.

View File

@ -1,4 +1,6 @@
### Is symbol ### isSymbol
Checks if the given argument is a symbol.
Use `typeof` to check if a value is classified as a symbol primitive. Use `typeof` to check if a value is classified as a symbol primitive.

View File

@ -1,8 +1,10 @@
### Last of list ### last
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 index of the last element of the given array and returning it.
```js ```js
const lastOfArray = arr => arr[arr.length - 1]; const last = arr => arr[arr.length - 1];
// last([1,2,3]) -> 3 // last([1,2,3]) -> 3
``` ```

View File

@ -1,10 +1,12 @@
### Least common multiple (LCM) ### lcm
Returns the least common multiple of two numbers.
Use the greatest common divisor (GCD) formula and `Math.abs()` to determine the least common multiple. Use the greatest common divisor (GCD) formula and `Math.abs()` to determine the least common multiple.
The GCD formula uses recursion. The GCD formula uses recursion.
```js ```js
const leastCommonMultiple = (x,y) => { const lcm = (x,y) => {
const gcd = (x, y) => !y ? x : gcd(y, x % y); const gcd = (x, y) => !y ? x : gcd(y, x % y);
return Math.abs(x*y)/(gcd(x,y)); return Math.abs(x*y)/(gcd(x,y));
}; };

View File

@ -1,4 +1,6 @@
### Median of array of numbers ### median
Returns the median of an array of numbers.
Find the middle of the array, use `Array.sort()` to sort the values. Find the middle of the array, use `Array.sort()` to sort the values.
Return the number at the midpoint if `length` is odd, otherwise the average of the two middle numbers. Return the number at the midpoint if `length` is odd, otherwise the average of the two middle numbers.

View File

@ -1,4 +1,6 @@
### Nth element of array ### nthElement
Returns the nth element of an array.
Use `Array.slice()` to get an array containing the nth element at the first place. Use `Array.slice()` to get an array containing the nth element at the first place.
If the index is out of bounds, return `[]`. If the index is out of bounds, return `[]`.

View File

@ -1,4 +1,6 @@
### Object from key-value pairs ### objectFromPairs
Creates an object from the given key-value pairs.
Use `Array.reduce()` to create and combine key-value pairs. Use `Array.reduce()` to create and combine key-value pairs.

View File

@ -1,4 +1,6 @@
### Object to key-value pairs ### objectToPairs
Creates an array of key-value pair arrays from an object.
Use `Object.keys()` and `Array.map()` to iterate over the object's keys and produce an array with key-value pairs. Use `Object.keys()` and `Array.map()` to iterate over the object's keys and produce an array with key-value pairs.

View File

@ -1,4 +1,6 @@
### Check for palindrome ### palindrome
Returns `true` if the given string is a palindrome, `false` otherwise.
Convert string `toLowerCase()` and use `replace()` to remove non-alphanumeric characters from it. 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()`. Then, `split('')` into individual characters, `reverse()`, `join('')` and compare to the original, unreversed string, after converting it `tolowerCase()`.

View File

@ -1,10 +1,11 @@
### Percentile ### percentile
Use `Array.reduce()` to calculate how many numbers are below the value and how many are the same value and Uses the percentile formula to calculate how many numbers in the given array are less or equal to the given value.
apply the percentile formula.
Use `Array.reduce()` to calculate how many numbers are below the value and how many are the same value and apply the percentile formula.
```js ```js
const percentile = (arr, val) => const percentile = (arr, val) =>
100 * arr.reduce((acc,v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), 0) / arr.length; 100 * arr.reduce((acc,v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), 0) / arr.length;
// percentile([1,2,3,4,5,6,7,8,9,10], 6) -> 55 // percentile([1,2,3,4,5,6,7,8,9,10], 6) -> 55
``` ```

View File

@ -1,10 +1,11 @@
### Pick ### pick
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. 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.
```js ```js
const pick = (obj, arr) => const pick = (obj, arr) =>
arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {}); 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 } // pick({ 'a': 1, 'b': '2', 'c': 3 }, ['a', 'c']) -> { 'a': 1, 'c': 3 }
// pick(object, ['a', 'c'])['a'] -> 1
``` ```

View File

@ -1,4 +1,6 @@
### Pipe functions ### pipe
Performs left-to-right function composition.
Use `Array.reduce()` with the spread operator (`...`) to perform left-to-right function composition. Use `Array.reduce()` with the spread operator (`...`) to perform left-to-right function composition.
The first (leftmost) function can accept one or more arguments; the remaining functions must be unary. The first (leftmost) function can accept one or more arguments; the remaining functions must be unary.

View File

@ -1,4 +1,6 @@
### Powerset ### powerset
Returns the powerset of a given array of numbers.
Use `Array.reduce()` combined with `Array.map()` to iterate over elements and combine into an array containing all combinations. Use `Array.reduce()` combined with `Array.map()` to iterate over elements and combine into an array containing all combinations.

View File

@ -1,7 +1,9 @@
### Promisify ### promisify
Use currying to return a function returning a `Promise` that calls the original function. Converts an asynchronous function to return a promise.
Use the `...rest` operator to pass in all the parameters.
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)* *In Node 8+, you can use [`util.promisify`](https://nodejs.org/api/util.html#util_util_promisify_original)*

View File

@ -1,6 +1,8 @@
### Array pull (mutates array) ### pull
Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed. 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 array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
```js ```js

View File

@ -1,4 +1,6 @@
### Random integer in range ### randomIntegerInRange
Returns a random integer in the specified range.
Use `Math.random()` to generate a random number and map it to the desired range, using `Math.floor()` to make it an integer. Use `Math.random()` to generate a random number and map it to the desired range, using `Math.floor()` to make it an integer.

View File

@ -1,4 +1,6 @@
### Random number in range ### randomNumberInRange
Returns a random number in the specified range.
Use `Math.random()` to generate a random value, map it to the desired range using multiplication. Use `Math.random()` to generate a random value, map it to the desired range using multiplication.

View File

@ -1,4 +1,6 @@
### Read file as array of lines ### readFileLines
Returns an array of lines from the specified file.
Use `readFileSync` function in `fs` node package to create a `Buffer` from a file. Use `readFileSync` function in `fs` node package to create a `Buffer` from a file.
convert buffer to string using `toString(encoding)` function. convert buffer to string using `toString(encoding)` function.
@ -6,7 +8,7 @@ creating an array from contents of file by `split`ing file content line by line(
```js ```js
const fs = require('fs'); const fs = require('fs');
const readFileToArray = filename => fs.readFileSync(filename).toString('UTF8').split('\n'); const readFileLines = filename => fs.readFileSync(filename).toString('UTF8').split('\n');
/* /*
contents of test.txt : contents of test.txt :
line1 line1

View File

@ -1,4 +1,6 @@
### Redirect to URL ### redirect
Redirects to a specified URL.
Use `window.location.href` or `window.location.replace()` to redirect to `url`. Use `window.location.href` or `window.location.replace()` to redirect to `url`.
Pass a second argument to simulate a link click (`true` - default) or an HTTP redirect (`false`). Pass a second argument to simulate a link click (`true` - default) or an HTTP redirect (`false`).

View File

@ -1,4 +1,6 @@
### Array remove ### remove
Removes elements from an array for which the given function returns `false`.
Use `Array.filter()` to find array elements that return truthy values and `Array.reduce()` to remove elements using `Array.splice()`. Use `Array.filter()` to find array elements that return truthy values and `Array.reduce()` to remove elements using `Array.splice()`.
The `func` is invoked with three arguments (`value, index, array`). The `func` is invoked with three arguments (`value, index, array`).

View File

@ -1,4 +1,6 @@
### Reverse a string ### reverseString
Reverses a string.
Use array destructuring and `Array.reverse()` to reverse the order of the characters in the string. Use array destructuring and `Array.reverse()` to reverse the order of the characters in the string.
Combine characters to get a string using `join('')`. Combine characters to get a string using `join('')`.

View File

@ -1,4 +1,6 @@
### Round number to n digits ### round
Rounds a number to a specified amount of digits.
Use `Math.round()` and template literals to round the number to the specified number of digits. Use `Math.round()` and template literals to round the number to the specified number of digits.
Omit the second argument, `decimals` to round to an integer. Omit the second argument, `decimals` to round to an integer.

View File

@ -1,6 +1,8 @@
### Run promises in series ### runPromisesInSeries
Run an array of promises in series using `Array.reduce()` by creating a promise chain, where each promise returns the next promise when resolved. Runs an array of promises in series.
Use `Array.reduce()` to create a promise chain, where each promise returns the next promise when resolved.
```js ```js
const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve()); const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());

View File

@ -1,4 +1,6 @@
### Array sample ### 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 with `length` and round it of to the nearest whole number using `Math.floor()`.
This method also works with strings. This method also works with strings.

View File

@ -1,4 +1,6 @@
### Scroll to top ### scrollToTop
Smooth-scrolls to the top of the page.
Get distance from top using `document.documentElement.scrollTop` or `document.body.scrollTop`. 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 top. Use `window.requestAnimationFrame()` to animate the scrolling.

View File

@ -1,4 +1,6 @@
### Shallow clone object ### shallowClone
Creates a shallow clone of an object.
Use `Object.assign()` and an empty object (`{}`) to create a shallow clone of the original. Use `Object.assign()` and an empty object (`{}`) to create a shallow clone of the original.

View File

@ -1,8 +1,10 @@
### Shuffle array ### shuffle
Randomizes the order of the values of an array.
Use `Array.sort()` to reorder elements, using `Math.random()` in the comparator. Use `Array.sort()` to reorder elements, using `Math.random()` in the comparator.
```js ```js
const shuffleArray = arr => arr.sort(() => Math.random() - 0.5); const shuffle = arr => arr.sort(() => Math.random() - 0.5);
// shuffle([1,2,3]) -> [2,3,1] // shuffle([1,2,3]) -> [2,3,1]
``` ```

View File

@ -1,4 +1,6 @@
### Similarity between arrays ### similarity
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 `filter()` to remove values that are not part of `values`, determined using `includes()`.

View File

@ -1,4 +1,6 @@
### Sleep ### sleep
Delays the execution of an asynchronous function.
Delay executing part of an `async` function, by putting it to sleep, returning a `Promise`. Delay executing part of an `async` function, by putting it to sleep, returning a `Promise`.

View File

@ -1,4 +1,6 @@
### Sort characters in string (alphabetical) ### sortCharactersInString
Alphabetically sorts the characters in a string.
Split the string using `split('')`, `Array.sort()` utilizing `localeCompare()`, recombine using `join('')`. Split the string using `split('')`, `Array.sort()` utilizing `localeCompare()`, recombine using `join('')`.

View File

@ -1,4 +1,6 @@
### Speech synthesis (experimental) ### speechSynthesis
Performs speech synthesis (experimental).
Use `SpeechSynthesisUtterance.voice` and `window.speechSynthesis.getVoices()` to convert a message to speech. Use `SpeechSynthesisUtterance.voice` and `window.speechSynthesis.getVoices()` to convert a message to speech.
Use `window.speechSynthesis.speak()` to play the message. Use `window.speechSynthesis.speak()` to play the message.

View File

@ -1,4 +1,6 @@
### Standard deviation ### standardDeviation
Returns the standard deviation of an array of numbers.
Use `Array.reduce()` to calculate the mean, variance and the sum of the variance of the values, the variance of the values, then Use `Array.reduce()` to calculate the mean, variance and the sum of the variance of the values, the variance of the values, then
determine the standard deviation. determine the standard deviation.

View File

@ -1,4 +1,6 @@
### Array symmetric difference ### symmetricDifference
Returns the symmetric difference between two arrays.
Create a `Set` from each array, then use `Array.filter()` on each of them to only keep values not contained in the other. Create a `Set` from each array, then use `Array.filter()` on each of them to only keep values not contained in the other.

View File

@ -1,9 +1,11 @@
### Tail of list ### 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.
```js ```js
const tailOfList = arr => arr.length > 1 ? arr.slice(1) : arr; const tail = arr => arr.length > 1 ? arr.slice(1) : arr;
// tail([1,2,3]) -> [2,3] // tail([1,2,3]) -> [2,3]
// tail([1]) -> [1] // tail([1]) -> [1]
``` ```

View File

@ -1,4 +1,6 @@
### Take ### take
Returns an array with n elements removed from the beggining.
Use `Array.slice()` to create a slice of the array with `n` elements taken from the beginning. Use `Array.slice()` to create a slice of the array with `n` elements taken from the beginning.

View File

@ -1,4 +1,6 @@
### Take right ### takeRight
Returns an array with n elements removed from the end.
Use `Array.slice()` to create a slice of the array with `n` elements taken from the end. Use `Array.slice()` to create a slice of the array with `n` elements taken from the end.

View File

@ -1,13 +1,13 @@
### Measure time taken by function ### timeTaken
Measures the time taken by a function to execute.
Use `console.time()` and `console.timeEnd()` to measure the difference between the start and end times to determine how long the callback took to execute. Use `console.time()` and `console.timeEnd()` to measure the difference between the start and end times to determine how long the callback took to execute.
```js ```js
const timeTaken = callback => { const timeTaken = callback => {
console.time('timeTaken'); console.time('timeTaken'); const r = callback();
const r = callback(); console.timeEnd('timeTaken'); return r;
console.timeEnd('timeTaken');
return r;
}; };
// timeTaken(() => Math.pow(2, 10)) -> 1024 // timeTaken(() => Math.pow(2, 10)) -> 1024
// (logged): timeTaken: 0.02099609375ms // (logged): timeTaken: 0.02099609375ms

View File

@ -1,9 +1,11 @@
### Convert string to camelcase ### 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.
```js ```js
const toCamelCase = str => const toCamelCase = str =>
str.replace(/^([A-Z])|[\s-_]+(\w)/g, (match, p1, p2, offset) => p2 ? p2.toUpperCase() : p1.toLowerCase()); str.replace(/^([A-Z])|[\s-_]+(\w)/g, (match, p1, p2, offset) => p2 ? p2.toUpperCase() : p1.toLowerCase());
// toCamelCase("some_database_field_name") -> 'someDatabaseFieldName' // toCamelCase("some_database_field_name") -> 'someDatabaseFieldName'
// toCamelCase("Some label that needs to be camelized") -> 'someLabelThatNeedsToBeCamelized' // toCamelCase("Some label that needs to be camelized") -> 'someLabelThatNeedsToBeCamelized'

View File

@ -1,4 +1,6 @@
### Convert to English date ### 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 English format.
Throws an error if the passed time cannot be converted to a date. Throws an error if the passed time cannot be converted to a date.

Some files were not shown because too many files have changed in this diff Show More