Update snippet descriptions
This commit is contained in:
@ -5,7 +5,8 @@ tags: array,intermediate
|
|||||||
|
|
||||||
Executes a provided function once for each array element, starting from the array's last element.
|
Executes a provided function once for each array element, starting from the array's last element.
|
||||||
|
|
||||||
- Use `Array.prototype.slice()` to clone the given array, `Array.prototype.reverse()` to reverse it and `Array.prototype.forEach()` to iterate over the reversed array.
|
- Use `Array.prototype.slice()` to clone the given array and `Array.prototype.reverse()` to reverse it.
|
||||||
|
- Use `Array.prototype.forEach()` to iterate over the reversed array.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const forEachRight = (arr, callback) =>
|
const forEachRight = (arr, callback) =>
|
||||||
|
|||||||
@ -5,7 +5,8 @@ tags: object,intermediate
|
|||||||
|
|
||||||
Iterates over all own properties of an object, running a callback for each one.
|
Iterates over all own properties of an object, running a callback for each one.
|
||||||
|
|
||||||
- Use `Object.keys(obj)` to get all the properties of the object, `Array.prototype.forEach()` to run the provided function for each key-value pair.
|
- Use `Object.keys(obj)` to get all the properties of the object.
|
||||||
|
- Use `Array.prototype.forEach()` to run the provided function for each key-value pair.
|
||||||
- The callback receives three arguments - the value, the key and the object.
|
- The callback receives three arguments - the value, the key and the object.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -5,7 +5,8 @@ tags: object,intermediate
|
|||||||
|
|
||||||
Iterates over all own properties of an object in reverse, running a callback for each one.
|
Iterates over all own properties of an object in reverse, running a callback for each one.
|
||||||
|
|
||||||
- Use `Object.keys(obj)` to get all the properties of the object, `Array.prototype.reverse()` to reverse their order and `Array.prototype.forEach()` to run the provided function for each key-value pair.
|
- Use `Object.keys(obj)` to get all the properties of the object, `Array.prototype.reverse()` to reverse their order.
|
||||||
|
- Use `Array.prototype.forEach()` to run the provided function for each key-value pair.
|
||||||
- The callback receives three arguments - the value, the key and the object.
|
- The callback receives three arguments - the value, the key and the object.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -3,10 +3,10 @@ title: formToObject
|
|||||||
tags: browser,object,intermediate
|
tags: browser,object,intermediate
|
||||||
---
|
---
|
||||||
|
|
||||||
Encode a set of form elements as an `object`.
|
Encodes a set of form elements as an `object`.
|
||||||
|
|
||||||
- Use the `FormData` constructor to convert the HTML `form` to `FormData`, `Array.from()` to convert to an array.
|
- Use the `FormData` constructor to convert the HTML `form` to `FormData` and `Array.from()` to convert to an array.
|
||||||
- Collect the object from the array, using `Array.prototype.reduce()`.
|
- Collect the object from the array using `Array.prototype.reduce()`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const formToObject = form =>
|
const formToObject = form =>
|
||||||
@ -20,5 +20,6 @@ const formToObject = form =>
|
|||||||
```
|
```
|
||||||
|
|
||||||
```js
|
```js
|
||||||
formToObject(document.querySelector('#form')); // { email: 'test@email.com', name: 'Test Name' }
|
formToObject(document.querySelector('#form'));
|
||||||
|
// { email: 'test@email.com', name: 'Test Name' }
|
||||||
```
|
```
|
||||||
|
|||||||
@ -3,7 +3,7 @@ title: formatDuration
|
|||||||
tags: date,math,string,intermediate
|
tags: date,math,string,intermediate
|
||||||
---
|
---
|
||||||
|
|
||||||
Returns the human readable format of the given number of milliseconds.
|
Returns the human-readable format of the given number of milliseconds.
|
||||||
|
|
||||||
- Divide `ms` with the appropriate values to obtain the appropriate values for `day`, `hour`, `minute`, `second` and `millisecond`.
|
- Divide `ms` with the appropriate values to obtain the appropriate values for `day`, `hour`, `minute`, `second` and `millisecond`.
|
||||||
- Use `Object.entries()` with `Array.prototype.filter()` to keep only non-zero values.
|
- Use `Object.entries()` with `Array.prototype.filter()` to keep only non-zero values.
|
||||||
|
|||||||
@ -1,9 +1,9 @@
|
|||||||
---
|
---
|
||||||
title: frequencies
|
title: frequencies
|
||||||
tags: array,intermediate
|
tags: array,object,intermediate
|
||||||
---
|
---
|
||||||
|
|
||||||
Returns an object with the unique values of an array as keys and their frequencies as the values.
|
Creates an object with the unique values of an array as keys and their frequencies as the values.
|
||||||
|
|
||||||
- Use `Array.prototype.reduce()` to map unique values to an object's keys, adding to existing keys every time the same value is encountered.
|
- Use `Array.prototype.reduce()` to map unique values to an object's keys, adding to existing keys every time the same value is encountered.
|
||||||
|
|
||||||
|
|||||||
@ -5,8 +5,8 @@ tags: browser,intermediate
|
|||||||
|
|
||||||
Opens or closes an element in fullscreen mode.
|
Opens or closes an element in fullscreen mode.
|
||||||
|
|
||||||
- Use `document.querySelector()` and `Element.prototype.requestFullscreen()` to open the given element in fullscreen.
|
- Use `Document.querySelector()` and `Element.requestFullscreen()` to open the given element in fullscreen.
|
||||||
- Use `document.exitFullscreen()` to exit fullscreen mode.
|
- Use `Document.exitFullscreen()` to exit fullscreen mode.
|
||||||
- Omit the second argument, `el`, to use `body` as the default element.
|
- Omit the second argument, `el`, to use `body` as the default element.
|
||||||
- Omit the first element, `mode`, to open the element in fullscreen mode by default.
|
- Omit the first element, `mode`, to open the element in fullscreen mode by default.
|
||||||
|
|
||||||
|
|||||||
@ -5,12 +5,15 @@ tags: function,beginner
|
|||||||
|
|
||||||
Logs the name of a function.
|
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 function to log the function's name to the `debug` channel of the console.
|
||||||
|
- Return the given function `fn`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const functionName = fn => (console.debug(fn.name), fn);
|
const functionName = fn => (console.debug(fn.name), fn);
|
||||||
```
|
```
|
||||||
|
|
||||||
```js
|
```js
|
||||||
functionName(Math.max); // max (logged in debug channel of console)
|
let m = functionName(Math.max)(5, 6);
|
||||||
|
// max (logged in debug channel of console)
|
||||||
|
// m = 6
|
||||||
```
|
```
|
||||||
|
|||||||
@ -1,9 +1,9 @@
|
|||||||
---
|
---
|
||||||
title: functions
|
title: functions
|
||||||
tags: object,function,intermediate
|
tags: object,function,advanced
|
||||||
---
|
---
|
||||||
|
|
||||||
Returns an array of function property names from own (and optionally inherited) enumerable properties of an object.
|
Gets an array of function property names from own (and optionally inherited) enumerable properties of an object.
|
||||||
|
|
||||||
- Use `Object.keys(obj)` to iterate over the object's own properties.
|
- Use `Object.keys(obj)` to iterate over the object's own properties.
|
||||||
- If `inherited` is `true`, use `Object.get.PrototypeOf(obj)` to also get the object's inherited properties.
|
- If `inherited` is `true`, use `Object.get.PrototypeOf(obj)` to also get the object's inherited properties.
|
||||||
|
|||||||
@ -6,6 +6,7 @@ tags: array,function,intermediate
|
|||||||
Generates an array with the given amount of items, using the given function.
|
Generates an array with the given amount of items, using the given function.
|
||||||
|
|
||||||
- Use `Array.from()` to create an empty array of the specific length, calling `fn` with the index of each newly created element.
|
- Use `Array.from()` to create an empty array of the specific length, calling `fn` with the index of each newly created element.
|
||||||
|
- The callback takes one argument - the index of each element.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const generateItems = (n, fn) => Array.from({ length: n }, (_, i) => fn(i));
|
const generateItems = (n, fn) => Array.from({ length: n }, (_, i) => fn(i));
|
||||||
|
|||||||
@ -13,7 +13,7 @@ Returns an error if `step` equals `1`.
|
|||||||
```js
|
```js
|
||||||
const geometricProgression = (end, start = 1, step = 2) =>
|
const geometricProgression = (end, start = 1, step = 2) =>
|
||||||
Array.from({ length: Math.floor(Math.log(end / start) / Math.log(step)) + 1 }).map(
|
Array.from({ length: Math.floor(Math.log(end / start) / Math.log(step)) + 1 }).map(
|
||||||
(v, i) => start * step ** i
|
(_, i) => start * step ** i
|
||||||
);
|
);
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@ -1,12 +1,13 @@
|
|||||||
---
|
---
|
||||||
title: get
|
title: get
|
||||||
tags: object,intermediate
|
tags: object,regexp,intermediate
|
||||||
---
|
---
|
||||||
|
|
||||||
Retrieve a set of properties indicated by the given selectors from an object.
|
Retrieves a set of properties indicated by the given selectors from an object.
|
||||||
|
|
||||||
- Use `Array.prototype.map()` for each selector, `String.prototype.replace()` to replace square brackets with dots.
|
- Use `Array.prototype.map()` for each selector, `String.prototype.replace()` to replace square brackets with dots.
|
||||||
- Use `String.prototype.split('.')` to split each selector, `Array.prototype.filter()` to remove empty values and `Array.prototype.reduce()` to get the value indicated by it.
|
- Use `String.prototype.split('.')` to split each selector.
|
||||||
|
- Use `Array.prototype.filter()` to remove empty values and `Array.prototype.reduce()` to get the value indicated by each selector.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const get = (from, ...selectors) =>
|
const get = (from, ...selectors) =>
|
||||||
@ -20,6 +21,10 @@ const get = (from, ...selectors) =>
|
|||||||
```
|
```
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const obj = { selector: { to: { val: 'val to select' } }, target: [1, 2, { a: 'test' }] };
|
const obj = {
|
||||||
get(obj, 'selector.to.val', 'target[0]', 'target[2].a'); // ['val to select', 1, 'test']
|
selector: { to: { val: 'val to select' } },
|
||||||
|
target: [1, 2, { a: 'test' }],
|
||||||
|
};
|
||||||
|
get(obj, 'selector.to.val', 'target[0]', 'target[2].a');
|
||||||
|
// ['val to select', 1, 'test']
|
||||||
```
|
```
|
||||||
|
|||||||
@ -20,5 +20,6 @@ const getAncestors = el => {
|
|||||||
```
|
```
|
||||||
|
|
||||||
```js
|
```js
|
||||||
getAncestors(document.querySelector('nav')); // [document, html, body, header, nav]
|
getAncestors(document.querySelector('nav'));
|
||||||
|
// [document, html, body, header, nav]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -1,9 +1,9 @@
|
|||||||
---
|
---
|
||||||
title: getBaseURL
|
title: getBaseURL
|
||||||
tags: browser,string,beginner
|
tags: string,browser,beginner
|
||||||
---
|
---
|
||||||
|
|
||||||
Returns the current URL without any parameters.
|
Gets the current URL without any parameters.
|
||||||
|
|
||||||
- Use `String.prototype.indexOf()` to check if the given `url` has parameters, `String.prototype.slice()` to remove them if necessary.
|
- Use `String.prototype.indexOf()` to check if the given `url` has parameters, `String.prototype.slice()` to remove them if necessary.
|
||||||
|
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
title: getColonTimeFromDate
|
title: getColonTimeFromDate
|
||||||
tags: date,intermediate
|
tags: date,string,beginner
|
||||||
---
|
---
|
||||||
|
|
||||||
Returns a string of the form `HH:MM:SS` from a `Date` object.
|
Returns a string of the form `HH:MM:SS` from a `Date` object.
|
||||||
@ -12,5 +12,5 @@ const getColonTimeFromDate = date => date.toTimeString().slice(0, 8);
|
|||||||
```
|
```
|
||||||
|
|
||||||
```js
|
```js
|
||||||
getColonTimeFromDate(new Date()); // "08:38:00"
|
getColonTimeFromDate(new Date()); // '08:38:00'
|
||||||
```
|
```
|
||||||
|
|||||||
@ -3,9 +3,9 @@ title: getDaysDiffBetweenDates
|
|||||||
tags: date,intermediate
|
tags: date,intermediate
|
||||||
---
|
---
|
||||||
|
|
||||||
Returns the difference (in days) between two dates.
|
Calculates the difference (in days) between two dates.
|
||||||
|
|
||||||
- Calculate the difference (in days) between two `Date` objects.
|
- Subtract the two `Date` object and divide by the number of milliseconds in a day to get the difference (in days) between them.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>
|
const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>
|
||||||
|
|||||||
@ -5,14 +5,14 @@ tags: browser,intermediate
|
|||||||
|
|
||||||
Returns an array of HTML elements whose width is larger than that of the viewport's.
|
Returns an array of HTML elements whose width is larger than that of the viewport's.
|
||||||
|
|
||||||
- Use `HTMLElement.prototype.offsetWidth()` to get the width of the `document`.
|
- Use `HTMLElement.offsetWidth` to get the width of the `document`.
|
||||||
- Use `Array.prototype.filter()` on the result of `document.querySelectorAll()` to check the width of all elements in the document.
|
- Use `Array.prototype.filter()` on the result of `Document.querySelectorAll()` to check the width of all elements in the document.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const getElementsBiggerThanViewport = () => {
|
const getElementsBiggerThanViewport = () => {
|
||||||
const docWidth = document.documentElement.offsetWidth;
|
const docWidth = document.documentElement.offsetWidth;
|
||||||
return [...document.querySelectorAll('*')].filter(el => el.offsetWidth > docWidth);
|
return [...document.querySelectorAll('*')].filter(el => el.offsetWidth > docWidth);
|
||||||
}
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -19,8 +19,8 @@ const getMeridiemSuffixOfInteger = num =>
|
|||||||
```
|
```
|
||||||
|
|
||||||
```js
|
```js
|
||||||
getMeridiemSuffixOfInteger(0); // "12am"
|
getMeridiemSuffixOfInteger(0); // '12am'
|
||||||
getMeridiemSuffixOfInteger(11); // "11am"
|
getMeridiemSuffixOfInteger(11); // '11am'
|
||||||
getMeridiemSuffixOfInteger(13); // "1pm"
|
getMeridiemSuffixOfInteger(13); // '1pm'
|
||||||
getMeridiemSuffixOfInteger(25); // "1pm"
|
getMeridiemSuffixOfInteger(25); // '1pm'
|
||||||
```
|
```
|
||||||
|
|||||||
@ -3,7 +3,7 @@ title: getMonthsDiffBetweenDates
|
|||||||
tags: date,intermediate
|
tags: date,intermediate
|
||||||
---
|
---
|
||||||
|
|
||||||
Returns the difference (in months) between two dates.
|
Calculates the difference (in months) between two dates.
|
||||||
|
|
||||||
- Use `Date.prototype.getFullYear()` and `Date.prototype.getMonth()` to calculate the difference (in months) between two `Date` objects.
|
- Use `Date.prototype.getFullYear()` and `Date.prototype.getMonth()` to calculate the difference (in months) between two `Date` objects.
|
||||||
|
|
||||||
|
|||||||
@ -3,7 +3,7 @@ title: getProtocol
|
|||||||
tags: browser,beginner
|
tags: browser,beginner
|
||||||
---
|
---
|
||||||
|
|
||||||
Returns the protocol being used on the current page.
|
Gets the protocol being used on the current page.
|
||||||
|
|
||||||
- Use `window.location.protocol` to get the protocol (`http:` or `https:`) of the current page.
|
- Use `window.location.protocol` to get the protocol (`http:` or `https:`) of the current page.
|
||||||
|
|
||||||
|
|||||||
@ -5,8 +5,8 @@ tags: browser,intermediate
|
|||||||
|
|
||||||
Returns the scroll position of the current page.
|
Returns the scroll position of the current page.
|
||||||
|
|
||||||
- Use `pageXOffset` and `pageYOffset` if they are defined, otherwise `scrollLeft` and `scrollTop`.
|
- Use `Window.pageXOffset` and `Window.pageYOffset` if they are defined, otherwise `Element.scrollLeft` and `Element.scrollTop`.
|
||||||
- You can omit `el` to use a default value of `window`.
|
- Omit the single argument, `el`, to use a default value of `window`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const getScrollPosition = (el = window) => ({
|
const getScrollPosition = (el = window) => ({
|
||||||
|
|||||||
@ -3,9 +3,9 @@ title: getSelectedText
|
|||||||
tags: browser,beginner
|
tags: browser,beginner
|
||||||
---
|
---
|
||||||
|
|
||||||
Get the currently selected text.
|
Gets the currently selected text.
|
||||||
|
|
||||||
- Use `window.getSelection()` and `Selection.prototype.toString()` to get the currently selected text.
|
- Use `Window.getSelection()` and `Selection.toString()` to get the currently selected text.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const getSelectedText = () => window.getSelection().toString();
|
const getSelectedText = () => window.getSelection().toString();
|
||||||
|
|||||||
@ -5,7 +5,7 @@ tags: browser,intermediate
|
|||||||
|
|
||||||
Returns an array containing all the siblings of the given element.
|
Returns an array containing all the siblings of the given element.
|
||||||
|
|
||||||
- Use `Node.prototype.parentNode` and `Node.prototype.childNodes` to get a `NodeList` of all the elements contained in the element's parent.
|
- Use `Node.parentNode` and `Node.childNodes` to get a `NodeList` of all the elements contained in the element's parent.
|
||||||
- Use the spread operator (`...`) and `Array.prototype.filter()` to convert to an array and remove the given element from it.
|
- Use the spread operator (`...`) and `Array.prototype.filter()` to convert to an array and remove the given element from it.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -3,7 +3,7 @@ title: getStyle
|
|||||||
tags: browser,css,beginner
|
tags: browser,css,beginner
|
||||||
---
|
---
|
||||||
|
|
||||||
Returns the value of a CSS rule for the specified element.
|
Retrieves the value of a CSS rule for the specified element.
|
||||||
|
|
||||||
- Use `Window.getComputedStyle()` to get the value of the CSS rule for the specified element.
|
- Use `Window.getComputedStyle()` to get the value of the CSS rule for the specified element.
|
||||||
|
|
||||||
|
|||||||
@ -10,8 +10,7 @@ Gets the Unix timestamp from a `Date` object.
|
|||||||
- Omit the argument, `date`, to use the current date.
|
- Omit the argument, `date`, to use the current date.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const getTimestamp = (date = new Date()) =>
|
const getTimestamp = (date = new Date()) => Math.floor(date.getTime() / 1000);
|
||||||
Math.floor(date.getTime() / 1000);
|
|
||||||
```
|
```
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -9,7 +9,8 @@ Returns the native type of a value.
|
|||||||
- Otherwise, use `Object.prototype.constructor.name` to get the name of the constructor.
|
- Otherwise, use `Object.prototype.constructor.name` to get the name of the constructor.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const getType = v => (v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name);
|
const getType = v =>
|
||||||
|
(v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name);
|
||||||
```
|
```
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -1,11 +1,12 @@
|
|||||||
---
|
---
|
||||||
title: getURLParameters
|
title: getURLParameters
|
||||||
tags: browser,string,intermediate
|
tags: browser,string,regexp,intermediate
|
||||||
---
|
---
|
||||||
|
|
||||||
Returns an object containing the parameters of the current URL.
|
Returns an object containing the parameters of the current URL.
|
||||||
|
|
||||||
- Use `String.prototype.match()` with an appropriate regular expression to get all key-value pairs, `Array.prototype.reduce()` to map and combine them into a single object.
|
- Use `String.prototype.match()` with an appropriate regular expression to get all key-value pairs.
|
||||||
|
- Use `Array.prototype.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
|
||||||
@ -17,6 +18,7 @@ const getURLParameters = url =>
|
|||||||
```
|
```
|
||||||
|
|
||||||
```js
|
```js
|
||||||
getURLParameters('http://url.com/page?name=Adam&surname=Smith'); // {name: 'Adam', surname: 'Smith'}
|
|
||||||
getURLParameters('google.com'); // {}
|
getURLParameters('google.com'); // {}
|
||||||
|
getURLParameters('http://url.com/page?name=Adam&surname=Smith');
|
||||||
|
// {name: 'Adam', surname: 'Smith'}
|
||||||
```
|
```
|
||||||
|
|||||||
@ -5,7 +5,7 @@ tags: array,object,intermediate
|
|||||||
|
|
||||||
Groups the elements of an array based on the given function.
|
Groups the elements of an array based on the given function.
|
||||||
|
|
||||||
- Use `Array.prototype.map()` to map the values of an array to a function or property name.
|
- Use `Array.prototype.map()` to map the values of the array to a function or property name.
|
||||||
- Use `Array.prototype.reduce()` to create an object, where the keys are produced from the mapped results.
|
- Use `Array.prototype.reduce()` to create an object, where the keys are produced from the mapped results.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -1,15 +1,17 @@
|
|||||||
---
|
---
|
||||||
title: hammingDistance
|
title: hammingDistance
|
||||||
tags: math,regexp,intermediate
|
tags: math,intermediate
|
||||||
---
|
---
|
||||||
|
|
||||||
Calculates the Hamming distance between two values.
|
Calculates the Hamming distance between two values.
|
||||||
|
|
||||||
- Use the XOR operator (`^`) to find the bit difference between the two numbers, convert to a binary string using `toString(2)`.
|
- Use the XOR operator (`^`) to find the bit difference between the two numbers.
|
||||||
- Count and return the number of `1`s in the string, using `match(/1/g)`.
|
- Convert to a binary string using `Number.prototype.toString(2)`.
|
||||||
|
- Count and return the number of `1`s in the string, using `String.prototype.match(/1/g)`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const hammingDistance = (num1, num2) => ((num1 ^ num2).toString(2).match(/1/g) || '').length;
|
const hammingDistance = (num1, num2) =>
|
||||||
|
((num1 ^ num2).toString(2).match(/1/g) || '').length;
|
||||||
```
|
```
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -3,9 +3,9 @@ title: hasClass
|
|||||||
tags: browser,css,beginner
|
tags: browser,css,beginner
|
||||||
---
|
---
|
||||||
|
|
||||||
Returns `true` if the element has the specified class, `false` otherwise.
|
Checks if the given element has the specified class.
|
||||||
|
|
||||||
- Use `element.classList.contains()` to check if the element has the specified class.
|
- Use `Element.classList` and `DOMTokenList.contains()` to check if the element has the specified class.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const hasClass = (el, className) => el.classList.contains(className);
|
const hasClass = (el, className) => el.classList.contains(className);
|
||||||
|
|||||||
@ -3,7 +3,7 @@ title: hasFlags
|
|||||||
tags: node,intermediate
|
tags: node,intermediate
|
||||||
---
|
---
|
||||||
|
|
||||||
Check if the current process's arguments contain the specified flags.
|
Checks if the current process's arguments contain the specified flags.
|
||||||
|
|
||||||
- Use `Array.prototype.every()` and `Array.prototype.includes()` to check if `process.argv` contains all the specified flags.
|
- Use `Array.prototype.every()` and `Array.prototype.includes()` to check if `process.argv` contains all the specified flags.
|
||||||
- Use a regular expression to test if the specified flags are prefixed with `-` or `--` and prefix them accordingly.
|
- Use a regular expression to test if the specified flags are prefixed with `-` or `--` and prefix them accordingly.
|
||||||
|
|||||||
@ -3,7 +3,7 @@ title: hasKey
|
|||||||
tags: object,intermediate
|
tags: object,intermediate
|
||||||
---
|
---
|
||||||
|
|
||||||
Returns `true` if the target value exists in a JSON object, `false` otherwise.
|
Checks if the target value exists in a JSON object.
|
||||||
|
|
||||||
- Check if `keys` is non-empty and use `Array.prototype.every()` to sequentially check its keys to internal depth of the object, `obj`.
|
- Check if `keys` is non-empty and use `Array.prototype.every()` to sequentially check its keys to internal depth of the object, `obj`.
|
||||||
- Use `Object.prototype.hasOwnProperty()` to check if `obj` does not have the current key or is not an object, stop propagation and return `false`.
|
- Use `Object.prototype.hasOwnProperty()` to check if `obj` does not have the current key or is not an object, stop propagation and return `false`.
|
||||||
|
|||||||
@ -3,7 +3,7 @@ title: haveSameContents
|
|||||||
tags: array,intermediate
|
tags: array,intermediate
|
||||||
---
|
---
|
||||||
|
|
||||||
Returns `true` if two arrays contain the same elements regardless of order, `false` otherwise.
|
Checks if two arrays contain the same elements regardless of order.
|
||||||
|
|
||||||
- Use a `for...of` loop over a `Set` created from the values of both arrays.
|
- Use a `for...of` loop over a `Set` created from the values of both arrays.
|
||||||
- Use `Array.prototype.filter()` to compare the amount of occurrences of each distinct value in both arrays.
|
- Use `Array.prototype.filter()` to compare the amount of occurrences of each distinct value in both arrays.
|
||||||
@ -12,7 +12,8 @@ Returns `true` if two arrays contain the same elements regardless of order, `fal
|
|||||||
```js
|
```js
|
||||||
const haveSameContents = (a, b) => {
|
const haveSameContents = (a, b) => {
|
||||||
for (const v of new Set([...a, ...b]))
|
for (const v of new Set([...a, ...b]))
|
||||||
if (a.filter(e => e === v).length !== b.filter(e => e === v).length) return false;
|
if (a.filter(e => e === v).length !== b.filter(e => e === v).length)
|
||||||
|
return false;
|
||||||
return true;
|
return true;
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|||||||
@ -5,7 +5,8 @@ tags: array,beginner
|
|||||||
|
|
||||||
Returns the head of an array.
|
Returns the head of an array.
|
||||||
|
|
||||||
- Check if `arr` is truthy and has a `length` property, use `arr[0]` if possible to return the first element, otherwise return `undefined`.
|
- Check if `arr` is truthy and has a `length` property.
|
||||||
|
- Use `arr[0]` if possible to return the first element, otherwise return `undefined`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const head = arr => (arr && arr.length ? arr[0] : undefined);
|
const head = arr => (arr && arr.length ? arr[0] : undefined);
|
||||||
|
|||||||
@ -3,7 +3,7 @@ title: hexToRGB
|
|||||||
tags: string,math,advanced
|
tags: string,math,advanced
|
||||||
---
|
---
|
||||||
|
|
||||||
Converts a color code to a `rgb()` or `rgba()` string if alpha value is provided.
|
Converts a color code to an `rgb()` or `rgba()` string if alpha value is provided.
|
||||||
|
|
||||||
- Use bitwise right-shift operator and mask bits with `&` (and) operator to convert a hexadecimal color code (with or without prefixed with `#`) to a string with the RGB values.
|
- Use bitwise right-shift operator and mask bits with `&` (and) operator to convert a hexadecimal color code (with or without prefixed with `#`) to a string with the RGB values.
|
||||||
- If it's 3-digit color code, first convert to 6-digit version.
|
- If it's 3-digit color code, first convert to 6-digit version.
|
||||||
|
|||||||
@ -5,7 +5,7 @@ tags: browser,intermediate
|
|||||||
|
|
||||||
Makes a `DELETE` request to the passed URL.
|
Makes a `DELETE` request to the passed URL.
|
||||||
|
|
||||||
- Use `XMLHttpRequest` web api to make a `delete` request to the given `url`.
|
- Use the `XMLHttpRequest` web API to make a `DELETE` request to the given `url`.
|
||||||
- Handle the `onload` event, by running the provided `callback` function.
|
- Handle the `onload` event, by running the provided `callback` function.
|
||||||
- Handle the `onerror` event, by running the provided `err` function.
|
- Handle the `onerror` event, by running the provided `err` function.
|
||||||
- Omit the third argument, `err` to log the request to the console's error stream by default.
|
- Omit the third argument, `err` to log the request to the console's error stream by default.
|
||||||
@ -23,7 +23,5 @@ const httpDelete = (url, callback, err = console.error) => {
|
|||||||
```js
|
```js
|
||||||
httpDelete('https://jsonplaceholder.typicode.com/posts/1', request => {
|
httpDelete('https://jsonplaceholder.typicode.com/posts/1', request => {
|
||||||
console.log(request.responseText);
|
console.log(request.responseText);
|
||||||
}); /*
|
}); // Logs: {}
|
||||||
Logs: {}
|
|
||||||
*/
|
|
||||||
```
|
```
|
||||||
|
|||||||
@ -5,7 +5,7 @@ tags: browser,intermediate
|
|||||||
|
|
||||||
Makes a `GET` request to the passed URL.
|
Makes a `GET` request to the passed URL.
|
||||||
|
|
||||||
- Use [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest) web api to make a `get` request to the given `url`.
|
- Use the `XMLHttpRequest` web API to make a `GET` request to the given `url`.
|
||||||
- Handle the `onload` event, by calling the given `callback` the `responseText`.
|
- Handle the `onload` event, by calling the given `callback` the `responseText`.
|
||||||
- Handle the `onerror` event, by running the provided `err` function.
|
- Handle the `onerror` event, by running the provided `err` function.
|
||||||
- Omit the third argument, `err`, to log errors to the console's `error` stream by default.
|
- Omit the third argument, `err`, to log errors to the console's `error` stream by default.
|
||||||
|
|||||||
@ -5,11 +5,10 @@ tags: browser,intermediate
|
|||||||
|
|
||||||
Makes a `POST` request to the passed URL.
|
Makes a `POST` request to the passed URL.
|
||||||
|
|
||||||
- Use [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest) web api to make a `post` request to the given `url`.
|
- Use the `XMLHttpRequest` web API to make a `POST` request to the given `url`.
|
||||||
- Set the value of an `HTTP` request header with `setRequestHeader` method.
|
- Set the value of an `HTTP` request header with `setRequestHeader` method.
|
||||||
- Handle the `onload` event, by calling the given `callback` the `responseText`.
|
- Handle the `onload` event, by calling the given `callback` the `responseText`.
|
||||||
- Handle the `onerror` event, by running the provided `err` function.
|
- Handle the `onerror` event, by running the provided `err` function.
|
||||||
- Omit the third argument, `data`, to send no data to the provided `url`.
|
|
||||||
- Omit the fourth argument, `err`, to log errors to the console's `error` stream by default.
|
- Omit the fourth argument, `err`, to log errors to the console's `error` stream by default.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -5,7 +5,7 @@ tags: browser,intermediate
|
|||||||
|
|
||||||
Makes a `PUT` request to the passed URL.
|
Makes a `PUT` request to the passed URL.
|
||||||
|
|
||||||
- Use `XMLHttpRequest` web api to make a `put` request to the given `url`.
|
- Use `XMLHttpRequest` web api to make a `PUT` request to the given `url`.
|
||||||
- Set the value of an `HTTP` request header with `setRequestHeader` method.
|
- Set the value of an `HTTP` request header with `setRequestHeader` method.
|
||||||
- Handle the `onload` event, by running the provided `callback` function.
|
- Handle the `onload` event, by running the provided `callback` function.
|
||||||
- Handle the `onerror` event, by running the provided `err` function.
|
- Handle the `onerror` event, by running the provided `err` function.
|
||||||
|
|||||||
@ -3,11 +3,12 @@ title: httpsRedirect
|
|||||||
tags: browser,intermediate
|
tags: browser,intermediate
|
||||||
---
|
---
|
||||||
|
|
||||||
Redirects the page to HTTPS if its currently in HTTP. Also, pressing the back button doesn't take it back to the HTTP page as its replaced in the history.
|
Redirects the page to HTTPS if it's currently in HTTP.
|
||||||
|
|
||||||
- Use `location.protocol` to get the protocol currently being used.
|
- Use `location.protocol` to get the protocol currently being used.
|
||||||
- If it's not HTTPS, use `location.replace()` to replace the existing page with the HTTPS version of the page.
|
- If it's not HTTPS, use `location.replace()` to replace the existing page with the HTTPS version of the page.
|
||||||
- Use `location.href` to get the full address, split it with `String.prototype.split()` and remove the protocol part of the URL.
|
- Use `location.href` to get the full address, split it with `String.prototype.split()` and remove the protocol part of the URL.
|
||||||
|
- Note that pressing the back button doesn't take it back to the HTTP page as its replaced in the history.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const httpsRedirect = () => {
|
const httpsRedirect = () => {
|
||||||
@ -16,5 +17,6 @@ const httpsRedirect = () => {
|
|||||||
```
|
```
|
||||||
|
|
||||||
```js
|
```js
|
||||||
httpsRedirect(); // If you are on http://mydomain.com, you are redirected to https://mydomain.com
|
httpsRedirect();
|
||||||
|
// If you are on http://mydomain.com, you are redirected to https://mydomain.com
|
||||||
```
|
```
|
||||||
|
|||||||
@ -3,8 +3,7 @@ title: hz
|
|||||||
tags: function,intermediate
|
tags: function,intermediate
|
||||||
---
|
---
|
||||||
|
|
||||||
Returns the number of times a function executed per second.
|
Measures the number of times a function is executed per second (`hz`/`hertz`).
|
||||||
`hz` is the unit for `hertz`, the unit of frequency defined as one cycle per second.
|
|
||||||
|
|
||||||
- Use `performance.now()` to get the difference in milliseconds before and after the iteration loop to calculate the time elapsed executing the function `iterations` times.
|
- Use `performance.now()` to get the difference in milliseconds before and after the iteration loop to calculate the time elapsed executing the function `iterations` times.
|
||||||
- Return the number of cycles per second by converting milliseconds to seconds and dividing it by the time elapsed.
|
- Return the number of cycles per second by converting milliseconds to seconds and dividing it by the time elapsed.
|
||||||
@ -19,12 +18,8 @@ const hz = (fn, iterations = 100) => {
|
|||||||
```
|
```
|
||||||
|
|
||||||
```js
|
```js
|
||||||
// 10,000 element array
|
const numbers = Array(10000).fill().map((_, i) => i);
|
||||||
const numbers = Array(10000)
|
|
||||||
.fill()
|
|
||||||
.map((_, i) => i);
|
|
||||||
|
|
||||||
// Test functions with the same goal: sum up the elements in the array
|
|
||||||
const sumReduce = () => numbers.reduce((acc, n) => acc + n, 0);
|
const sumReduce = () => numbers.reduce((acc, n) => acc + n, 0);
|
||||||
const sumForLoop = () => {
|
const sumForLoop = () => {
|
||||||
let sum = 0;
|
let sum = 0;
|
||||||
@ -32,7 +27,6 @@ const sumForLoop = () => {
|
|||||||
return sum;
|
return sum;
|
||||||
};
|
};
|
||||||
|
|
||||||
// `sumForLoop` is nearly 10 times faster
|
|
||||||
Math.round(hz(sumReduce)); // 572
|
Math.round(hz(sumReduce)); // 572
|
||||||
Math.round(hz(sumForLoop)); // 4784
|
Math.round(hz(sumForLoop)); // 4784
|
||||||
```
|
```
|
||||||
|
|||||||
Reference in New Issue
Block a user