diff --git a/snippets/forEachRight.md b/snippets/forEachRight.md index 8e9686f2c..eca45a102 100644 --- a/snippets/forEachRight.md +++ b/snippets/forEachRight.md @@ -5,7 +5,8 @@ tags: array,intermediate 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 const forEachRight = (arr, callback) => diff --git a/snippets/forOwn.md b/snippets/forOwn.md index add62d1b9..01773585b 100644 --- a/snippets/forOwn.md +++ b/snippets/forOwn.md @@ -5,7 +5,8 @@ tags: object,intermediate 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. ```js diff --git a/snippets/forOwnRight.md b/snippets/forOwnRight.md index f775582f1..acc992e4d 100644 --- a/snippets/forOwnRight.md +++ b/snippets/forOwnRight.md @@ -5,7 +5,8 @@ tags: object,intermediate 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. ```js diff --git a/snippets/formToObject.md b/snippets/formToObject.md index cfc0d5917..49b10e7e6 100644 --- a/snippets/formToObject.md +++ b/snippets/formToObject.md @@ -3,10 +3,10 @@ title: formToObject 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. -- Collect the object from the array, using `Array.prototype.reduce()`. +- 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()`. ```js const formToObject = form => @@ -20,5 +20,6 @@ const formToObject = form => ``` ```js -formToObject(document.querySelector('#form')); // { email: 'test@email.com', name: 'Test Name' } +formToObject(document.querySelector('#form')); +// { email: 'test@email.com', name: 'Test Name' } ``` diff --git a/snippets/formatDuration.md b/snippets/formatDuration.md index 4e9df4e71..79135760d 100644 --- a/snippets/formatDuration.md +++ b/snippets/formatDuration.md @@ -3,7 +3,7 @@ title: formatDuration 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`. - Use `Object.entries()` with `Array.prototype.filter()` to keep only non-zero values. diff --git a/snippets/frequencies.md b/snippets/frequencies.md index 8c2e14835..1b3afdcc7 100644 --- a/snippets/frequencies.md +++ b/snippets/frequencies.md @@ -1,9 +1,9 @@ --- 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. diff --git a/snippets/fullscreen.md b/snippets/fullscreen.md index d394ec91d..e2118dbfc 100644 --- a/snippets/fullscreen.md +++ b/snippets/fullscreen.md @@ -5,8 +5,8 @@ tags: browser,intermediate Opens or closes an element in fullscreen mode. -- Use `document.querySelector()` and `Element.prototype.requestFullscreen()` to open the given element in fullscreen. -- Use `document.exitFullscreen()` to exit fullscreen mode. +- Use `Document.querySelector()` and `Element.requestFullscreen()` to open the given element in fullscreen. +- Use `Document.exitFullscreen()` to exit fullscreen mode. - 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. diff --git a/snippets/functionName.md b/snippets/functionName.md index be32b9cb7..1c9353cd9 100644 --- a/snippets/functionName.md +++ b/snippets/functionName.md @@ -5,12 +5,15 @@ tags: function,beginner 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 const functionName = fn => (console.debug(fn.name), fn); ``` ```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 ``` diff --git a/snippets/functions.md b/snippets/functions.md index 488c32a97..2b6155e9a 100644 --- a/snippets/functions.md +++ b/snippets/functions.md @@ -1,9 +1,9 @@ --- 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. - If `inherited` is `true`, use `Object.get.PrototypeOf(obj)` to also get the object's inherited properties. diff --git a/snippets/generateItems.md b/snippets/generateItems.md index 192fcd93a..70a9a11dc 100644 --- a/snippets/generateItems.md +++ b/snippets/generateItems.md @@ -6,6 +6,7 @@ tags: array,function,intermediate 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. +- The callback takes one argument - the index of each element. ```js const generateItems = (n, fn) => Array.from({ length: n }, (_, i) => fn(i)); diff --git a/snippets/geometricProgression.md b/snippets/geometricProgression.md index 7e58898c6..dfb5dbd2c 100644 --- a/snippets/geometricProgression.md +++ b/snippets/geometricProgression.md @@ -13,7 +13,7 @@ Returns an error if `step` equals `1`. ```js const geometricProgression = (end, start = 1, step = 2) => Array.from({ length: Math.floor(Math.log(end / start) / Math.log(step)) + 1 }).map( - (v, i) => start * step ** i + (_, i) => start * step ** i ); ``` diff --git a/snippets/get.md b/snippets/get.md index 78f37cf75..fe5c2f084 100644 --- a/snippets/get.md +++ b/snippets/get.md @@ -1,12 +1,13 @@ --- 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 `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 const get = (from, ...selectors) => @@ -20,6 +21,10 @@ const get = (from, ...selectors) => ``` ```js -const obj = { 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'] +const obj = { + 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'] ``` diff --git a/snippets/getAncestors.md b/snippets/getAncestors.md index f962c47e6..3dacd10de 100644 --- a/snippets/getAncestors.md +++ b/snippets/getAncestors.md @@ -20,5 +20,6 @@ const getAncestors = el => { ``` ```js -getAncestors(document.querySelector('nav')); // [document, html, body, header, nav] +getAncestors(document.querySelector('nav')); +// [document, html, body, header, nav] ``` diff --git a/snippets/getBaseURL.md b/snippets/getBaseURL.md index 5bc4bc9be..c75b3635c 100644 --- a/snippets/getBaseURL.md +++ b/snippets/getBaseURL.md @@ -1,9 +1,9 @@ --- 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. diff --git a/snippets/getColonTimeFromDate.md b/snippets/getColonTimeFromDate.md index 5488e2e22..0d35a6397 100644 --- a/snippets/getColonTimeFromDate.md +++ b/snippets/getColonTimeFromDate.md @@ -1,6 +1,6 @@ --- title: getColonTimeFromDate -tags: date,intermediate +tags: date,string,beginner --- 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 -getColonTimeFromDate(new Date()); // "08:38:00" +getColonTimeFromDate(new Date()); // '08:38:00' ``` diff --git a/snippets/getDaysDiffBetweenDates.md b/snippets/getDaysDiffBetweenDates.md index c3282fb3e..91e4695a3 100644 --- a/snippets/getDaysDiffBetweenDates.md +++ b/snippets/getDaysDiffBetweenDates.md @@ -3,9 +3,9 @@ title: getDaysDiffBetweenDates 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 const getDaysDiffBetweenDates = (dateInitial, dateFinal) => diff --git a/snippets/getElementsBiggerThanViewport.md b/snippets/getElementsBiggerThanViewport.md index 1dab76f2f..f53dac496 100644 --- a/snippets/getElementsBiggerThanViewport.md +++ b/snippets/getElementsBiggerThanViewport.md @@ -5,14 +5,14 @@ tags: browser,intermediate 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 `Array.prototype.filter()` on the result of `document.querySelectorAll()` to check the width of all elements in 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. ```js const getElementsBiggerThanViewport = () => { const docWidth = document.documentElement.offsetWidth; return [...document.querySelectorAll('*')].filter(el => el.offsetWidth > docWidth); -} +}; ``` ```js diff --git a/snippets/getMeridiemSuffixOfInteger.md b/snippets/getMeridiemSuffixOfInteger.md index 024dd7673..1dfb0c90e 100644 --- a/snippets/getMeridiemSuffixOfInteger.md +++ b/snippets/getMeridiemSuffixOfInteger.md @@ -19,8 +19,8 @@ const getMeridiemSuffixOfInteger = num => ``` ```js -getMeridiemSuffixOfInteger(0); // "12am" -getMeridiemSuffixOfInteger(11); // "11am" -getMeridiemSuffixOfInteger(13); // "1pm" -getMeridiemSuffixOfInteger(25); // "1pm" +getMeridiemSuffixOfInteger(0); // '12am' +getMeridiemSuffixOfInteger(11); // '11am' +getMeridiemSuffixOfInteger(13); // '1pm' +getMeridiemSuffixOfInteger(25); // '1pm' ``` diff --git a/snippets/getMonthsDiffBetweenDates.md b/snippets/getMonthsDiffBetweenDates.md index 2d4b4161f..077cf3b66 100644 --- a/snippets/getMonthsDiffBetweenDates.md +++ b/snippets/getMonthsDiffBetweenDates.md @@ -3,7 +3,7 @@ title: getMonthsDiffBetweenDates 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. diff --git a/snippets/getProtocol.md b/snippets/getProtocol.md index 9139116cb..36dae5297 100644 --- a/snippets/getProtocol.md +++ b/snippets/getProtocol.md @@ -3,7 +3,7 @@ title: getProtocol 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. diff --git a/snippets/getScrollPosition.md b/snippets/getScrollPosition.md index ff200c0f9..236b6a02f 100644 --- a/snippets/getScrollPosition.md +++ b/snippets/getScrollPosition.md @@ -5,8 +5,8 @@ tags: browser,intermediate Returns the scroll position of the current page. -- Use `pageXOffset` and `pageYOffset` if they are defined, otherwise `scrollLeft` and `scrollTop`. -- You can omit `el` to use a default value of `window`. +- Use `Window.pageXOffset` and `Window.pageYOffset` if they are defined, otherwise `Element.scrollLeft` and `Element.scrollTop`. +- Omit the single argument, `el`, to use a default value of `window`. ```js const getScrollPosition = (el = window) => ({ diff --git a/snippets/getSelectedText.md b/snippets/getSelectedText.md index be6965d06..983af8bb5 100644 --- a/snippets/getSelectedText.md +++ b/snippets/getSelectedText.md @@ -3,9 +3,9 @@ title: getSelectedText 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 const getSelectedText = () => window.getSelection().toString(); diff --git a/snippets/getSiblings.md b/snippets/getSiblings.md index ae2230433..31b1b8954 100644 --- a/snippets/getSiblings.md +++ b/snippets/getSiblings.md @@ -5,7 +5,7 @@ tags: browser,intermediate 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. ```js diff --git a/snippets/getStyle.md b/snippets/getStyle.md index 21d190184..7a930bf4e 100644 --- a/snippets/getStyle.md +++ b/snippets/getStyle.md @@ -3,7 +3,7 @@ title: getStyle 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. diff --git a/snippets/getTimestamp.md b/snippets/getTimestamp.md index 54fac6213..3606ddb7c 100644 --- a/snippets/getTimestamp.md +++ b/snippets/getTimestamp.md @@ -10,8 +10,7 @@ Gets the Unix timestamp from a `Date` object. - Omit the argument, `date`, to use the current date. ```js -const getTimestamp = (date = new Date()) => - Math.floor(date.getTime() / 1000); +const getTimestamp = (date = new Date()) => Math.floor(date.getTime() / 1000); ``` ```js diff --git a/snippets/getType.md b/snippets/getType.md index 4d67e4cee..e7d00a14e 100644 --- a/snippets/getType.md +++ b/snippets/getType.md @@ -9,7 +9,8 @@ Returns the native type of a value. - Otherwise, use `Object.prototype.constructor.name` to get the name of the constructor. ```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 diff --git a/snippets/getURLParameters.md b/snippets/getURLParameters.md index 9abd2dcaa..4c0f04af2 100644 --- a/snippets/getURLParameters.md +++ b/snippets/getURLParameters.md @@ -1,11 +1,12 @@ --- title: getURLParameters -tags: browser,string,intermediate +tags: browser,string,regexp,intermediate --- 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`. ```js @@ -17,6 +18,7 @@ const getURLParameters = url => ``` ```js -getURLParameters('http://url.com/page?name=Adam&surname=Smith'); // {name: 'Adam', surname: 'Smith'} getURLParameters('google.com'); // {} +getURLParameters('http://url.com/page?name=Adam&surname=Smith'); +// {name: 'Adam', surname: 'Smith'} ``` diff --git a/snippets/groupBy.md b/snippets/groupBy.md index 93750a57d..575b971c9 100644 --- a/snippets/groupBy.md +++ b/snippets/groupBy.md @@ -5,7 +5,7 @@ tags: array,object,intermediate 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. ```js diff --git a/snippets/hammingDistance.md b/snippets/hammingDistance.md index 631e4235e..51530ad35 100644 --- a/snippets/hammingDistance.md +++ b/snippets/hammingDistance.md @@ -1,15 +1,17 @@ --- title: hammingDistance -tags: math,regexp,intermediate +tags: math,intermediate --- 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)`. -- Count and return the number of `1`s in the string, using `match(/1/g)`. +- Use the XOR operator (`^`) to find the bit difference between the two numbers. +- 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 -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 diff --git a/snippets/hasClass.md b/snippets/hasClass.md index 1cba5bc88..2b72c17f5 100644 --- a/snippets/hasClass.md +++ b/snippets/hasClass.md @@ -3,9 +3,9 @@ title: hasClass 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 const hasClass = (el, className) => el.classList.contains(className); diff --git a/snippets/hasFlags.md b/snippets/hasFlags.md index b1c9a13a1..af841f827 100644 --- a/snippets/hasFlags.md +++ b/snippets/hasFlags.md @@ -3,7 +3,7 @@ title: hasFlags 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 a regular expression to test if the specified flags are prefixed with `-` or `--` and prefix them accordingly. diff --git a/snippets/hasKey.md b/snippets/hasKey.md index 09241ac3e..a0be3ee2a 100644 --- a/snippets/hasKey.md +++ b/snippets/hasKey.md @@ -3,7 +3,7 @@ title: hasKey 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`. - Use `Object.prototype.hasOwnProperty()` to check if `obj` does not have the current key or is not an object, stop propagation and return `false`. diff --git a/snippets/haveSameContents.md b/snippets/haveSameContents.md index e2eb73ee3..97b232f6c 100644 --- a/snippets/haveSameContents.md +++ b/snippets/haveSameContents.md @@ -3,7 +3,7 @@ title: haveSameContents 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 `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 const haveSameContents = (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; }; ``` diff --git a/snippets/head.md b/snippets/head.md index 244afd216..b790e655b 100644 --- a/snippets/head.md +++ b/snippets/head.md @@ -5,7 +5,8 @@ tags: array,beginner 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 const head = arr => (arr && arr.length ? arr[0] : undefined); diff --git a/snippets/hexToRGB.md b/snippets/hexToRGB.md index fe0bcc27f..0e74a66d2 100644 --- a/snippets/hexToRGB.md +++ b/snippets/hexToRGB.md @@ -3,7 +3,7 @@ title: hexToRGB 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. - If it's 3-digit color code, first convert to 6-digit version. diff --git a/snippets/httpDelete.md b/snippets/httpDelete.md index 5471bded2..506929f34 100644 --- a/snippets/httpDelete.md +++ b/snippets/httpDelete.md @@ -5,7 +5,7 @@ tags: browser,intermediate 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 `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. @@ -23,7 +23,5 @@ const httpDelete = (url, callback, err = console.error) => { ```js httpDelete('https://jsonplaceholder.typicode.com/posts/1', request => { console.log(request.responseText); -}); /* -Logs: {} -*/ +}); // Logs: {} ``` diff --git a/snippets/httpGet.md b/snippets/httpGet.md index f246a2592..f42d8f7ac 100644 --- a/snippets/httpGet.md +++ b/snippets/httpGet.md @@ -5,7 +5,7 @@ tags: browser,intermediate 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 `onerror` event, by running the provided `err` function. - Omit the third argument, `err`, to log errors to the console's `error` stream by default. diff --git a/snippets/httpPost.md b/snippets/httpPost.md index e44b49f3f..cde8c2c6d 100644 --- a/snippets/httpPost.md +++ b/snippets/httpPost.md @@ -5,11 +5,10 @@ tags: browser,intermediate 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. - Handle the `onload` event, by calling the given `callback` the `responseText`. - 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. ```js diff --git a/snippets/httpPut.md b/snippets/httpPut.md index feecfdbea..6e357afce 100644 --- a/snippets/httpPut.md +++ b/snippets/httpPut.md @@ -5,7 +5,7 @@ tags: browser,intermediate 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. - Handle the `onload` event, by running the provided `callback` function. - Handle the `onerror` event, by running the provided `err` function. diff --git a/snippets/httpsRedirect.md b/snippets/httpsRedirect.md index a0a5b385e..469e893a6 100644 --- a/snippets/httpsRedirect.md +++ b/snippets/httpsRedirect.md @@ -3,11 +3,12 @@ title: httpsRedirect 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. - 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. +- Note that pressing the back button doesn't take it back to the HTTP page as its replaced in the history. ```js const httpsRedirect = () => { @@ -16,5 +17,6 @@ const httpsRedirect = () => { ``` ```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 ``` diff --git a/snippets/hz.md b/snippets/hz.md index 35bc6842c..06528367a 100644 --- a/snippets/hz.md +++ b/snippets/hz.md @@ -3,8 +3,7 @@ title: hz tags: function,intermediate --- -Returns the number of times a function executed per second. -`hz` is the unit for `hertz`, the unit of frequency defined as one cycle per second. +Measures the number of times a function is executed per second (`hz`/`hertz`). - 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. @@ -19,12 +18,8 @@ const hz = (fn, iterations = 100) => { ``` ```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 sumForLoop = () => { let sum = 0; @@ -32,7 +27,6 @@ const sumForLoop = () => { return sum; }; -// `sumForLoop` is nearly 10 times faster Math.round(hz(sumReduce)); // 572 Math.round(hz(sumForLoop)); // 4784 ```