diff --git a/snippets/CSVToJSON.md b/snippets/CSVToJSON.md index 4c1c30bf0..40c76fbfb 100644 --- a/snippets/CSVToJSON.md +++ b/snippets/CSVToJSON.md @@ -19,7 +19,10 @@ const CSVToJSON = (data, delimiter = ',') => { .split('\n') .map(v => { const values = v.split(delimiter); - return titles.reduce((obj, title, index) => ((obj[title] = values[index]), obj), {}); + return titles.reduce( + (obj, title, index) => ((obj[title] = values[index]), obj), + {} + ); }); }; ``` diff --git a/snippets/JSONtoCSV.md b/snippets/JSONtoCSV.md index b9664a644..7e9aa089f 100644 --- a/snippets/JSONtoCSV.md +++ b/snippets/JSONtoCSV.md @@ -16,10 +16,11 @@ const JSONtoCSV = (arr, columns, delimiter = ',') => columns.join(delimiter), ...arr.map(obj => columns.reduce( - (acc, key) => `${acc}${!acc.length ? '' : delimiter}"${!obj[key] ? '' : obj[key]}"`, + (acc, key) => + `${acc}${!acc.length ? '' : delimiter}"${!obj[key] ? '' : obj[key]}"`, '' ) - ) + ), ].join('\n'); ``` diff --git a/snippets/accumulate.md b/snippets/accumulate.md index 84a0d4ef6..ae8683905 100644 --- a/snippets/accumulate.md +++ b/snippets/accumulate.md @@ -9,7 +9,8 @@ Creates an array of partial sums. - Use `Array.prototype.slice(-1)`, the spread operator (`...`) and the unary `+` operator to add each value to the accumulator array containing the previous sums. ```js -const accumulate = (...nums) => nums.reduce((acc, n) => [...acc, n + +acc.slice(-1)],[]); +const accumulate = (...nums) => + nums.reduce((acc, n) => [...acc, n + +acc.slice(-1)],[]); ``` ```js diff --git a/snippets/addMultipleEvents.md b/snippets/addMultipleEvents.md index 0cfe02386..0a6098c0d 100644 --- a/snippets/addMultipleEvents.md +++ b/snippets/addMultipleEvents.md @@ -9,8 +9,10 @@ Adds multiple event listeners with the same handler to an element. ```js const addMultipleListeners = (el, types, listener, options, useCapture) => { - types.forEach(type => el.addEventListener(type, listener, options, useCapture)); -} + types.forEach(type => + el.addEventListener(type, listener, options, useCapture) + ); +}; ``` ```js diff --git a/snippets/addWeekDays.md b/snippets/addWeekDays.md index 1498a2ea4..b1f841f8b 100644 --- a/snippets/addWeekDays.md +++ b/snippets/addWeekDays.md @@ -11,15 +11,13 @@ Calculates the date after adding the ginen number of business days. - **NOTE:** Does not take official holidays into account. ```js -const addWeekDays = (startDate, count) => - Array - .from({ length: count }) - .reduce(date => { - date = new Date(date.setDate(date.getDate() + 1)); - if (date.getDay() % 6 === 0) - date = new Date(date.setDate(date.getDate() + ((date.getDay() / 6) + 1))); - return date; - }, startDate); +const addWeekDays = (startDate, count) => + Array.from({ length: count }).reduce(date => { + date = new Date(date.setDate(date.getDate() + 1)); + if (date.getDay() % 6 === 0) + date = new Date(date.setDate(date.getDate() + (date.getDay() / 6 + 1))); + return date; + }, startDate); ``` ```js diff --git a/snippets/approximatelyEqual.md b/snippets/approximatelyEqual.md index fc26b51cf..2bb46b686 100644 --- a/snippets/approximatelyEqual.md +++ b/snippets/approximatelyEqual.md @@ -9,7 +9,8 @@ Checks if two numbers are approximately equal to each other. - Omit the third parameter, `epsilon`, to use a default value of `0.001`. ```js -const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon; +const approximatelyEqual = (v1, v2, epsilon = 0.001) => + Math.abs(v1 - v2) < epsilon; ``` ```js diff --git a/snippets/average.md b/snippets/average.md index 5facaed82..dd4bd7771 100644 --- a/snippets/average.md +++ b/snippets/average.md @@ -9,7 +9,8 @@ Calculates the average of two or more numbers. - Divide the resulting array by its length. ```js -const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length; +const average = (...nums) => + nums.reduce((acc, val) => acc + val, 0) / nums.length; ``` ```js diff --git a/snippets/bifurcate.md b/snippets/bifurcate.md index be45bb12d..bfa307628 100644 --- a/snippets/bifurcate.md +++ b/snippets/bifurcate.md @@ -10,7 +10,10 @@ Splits values into two groups, based on the result of the given `filter` array. ```js const bifurcate = (arr, filter) => - arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]); + arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [ + [], + [], + ]); ``` ```js diff --git a/snippets/bifurcateBy.md b/snippets/bifurcateBy.md index 69b18ad35..75d0b9b06 100644 --- a/snippets/bifurcateBy.md +++ b/snippets/bifurcateBy.md @@ -10,7 +10,10 @@ Splits values into two groups, based on the result of the given filtering functi ```js const bifurcateBy = (arr, fn) => - arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]); + arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [ + [], + [], + ]); ``` ```js diff --git a/snippets/bottomVisible.md b/snippets/bottomVisible.md index ac6687743..6355041f5 100644 --- a/snippets/bottomVisible.md +++ b/snippets/bottomVisible.md @@ -10,7 +10,8 @@ Checks if the bottom of the page is visible. ```js const bottomVisible = () => document.documentElement.clientHeight + window.scrollY >= - (document.documentElement.scrollHeight || document.documentElement.clientHeight); + (document.documentElement.scrollHeight || + document.documentElement.clientHeight); ``` ```js diff --git a/snippets/capitalize.md b/snippets/capitalize.md index a8118dfbe..d9187b7a7 100644 --- a/snippets/capitalize.md +++ b/snippets/capitalize.md @@ -11,7 +11,8 @@ Capitalizes the first letter of a string. ```js const capitalize = ([first, ...rest], lowerRest = false) => - first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join('')); + first.toUpperCase() + + (lowerRest ? rest.join('').toLowerCase() : rest.join('')); ``` ```js diff --git a/snippets/capitalizeEveryWord.md b/snippets/capitalizeEveryWord.md index 82349b4bc..ff29c5862 100644 --- a/snippets/capitalizeEveryWord.md +++ b/snippets/capitalizeEveryWord.md @@ -8,7 +8,8 @@ Capitalizes the first letter of every word in a string. - Use `String.prototype.replace()` to match the first character of each word and `String.prototype.toUpperCase()` to capitalize it. ```js -const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase()); +const capitalizeEveryWord = str => + str.replace(/\b[a-z]/g, char => char.toUpperCase()); ``` ```js diff --git a/snippets/clampNumber.md b/snippets/clampNumber.md index fbe896da6..1d01ed463 100644 --- a/snippets/clampNumber.md +++ b/snippets/clampNumber.md @@ -9,7 +9,8 @@ Clamps `num` within the inclusive range specified by the boundary values `a` and - Otherwise, return the nearest number in the range. ```js -const clampNumber = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b)); +const clampNumber = (num, a, b) => + Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b)); ``` ```js diff --git a/snippets/cloneRegExp.md b/snippets/cloneRegExp.md index b1db00580..33d8b1998 100644 --- a/snippets/cloneRegExp.md +++ b/snippets/cloneRegExp.md @@ -1,6 +1,6 @@ --- title: cloneRegExp -tags: regexp,intermediate +tags: type,intermediate --- Clones a regular expression. diff --git a/snippets/coalesceFactory.md b/snippets/coalesceFactory.md index 1a7e1de90..1c181a1c6 100644 --- a/snippets/coalesceFactory.md +++ b/snippets/coalesceFactory.md @@ -12,6 +12,8 @@ const coalesceFactory = valid => (...args) => args.find(valid); ``` ```js -const customCoalesce = coalesceFactory(v => ![null, undefined, '', NaN].includes(v)); +const customCoalesce = coalesceFactory( + v => ![null, undefined, '', NaN].includes(v) +); customCoalesce(undefined, null, NaN, '', 'Waldo'); // 'Waldo' ``` diff --git a/snippets/colorize.md b/snippets/colorize.md index b0f81cc59..7883e4900 100644 --- a/snippets/colorize.md +++ b/snippets/colorize.md @@ -32,5 +32,6 @@ const colorize = (...args) => ({ ```js console.log(colorize('foo').red); // 'foo' (red letters) console.log(colorize('foo', 'bar').bgBlue); // 'foo bar' (blue background) -console.log(colorize(colorize('foo').yellow, colorize('foo').green).bgWhite); // 'foo bar' (first word in yellow letters, second word in green letters, white background for both) +console.log(colorize(colorize('foo').yellow, colorize('foo').green).bgWhite); +// 'foo bar' (first word in yellow letters, second word in green letters, white background for both) ``` diff --git a/snippets/compact.md b/snippets/compact.md index 0e9f3ed24..e7b6250e4 100644 --- a/snippets/compact.md +++ b/snippets/compact.md @@ -12,5 +12,6 @@ const compact = arr => arr.filter(Boolean); ``` ```js -compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); // [ 1, 2, 3, 'a', 's', 34 ] +compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); +// [ 1, 2, 3, 'a', 's', 34 ] ``` diff --git a/snippets/compose.md b/snippets/compose.md index 74853cefa..d160e3702 100644 --- a/snippets/compose.md +++ b/snippets/compose.md @@ -9,7 +9,8 @@ Performs right-to-left function composition. - The last (rightmost) function can accept one or more arguments; the remaining functions must be unary. ```js -const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args))); +const compose = (...fns) => + fns.reduce((f, g) => (...args) => f(g(...args))); ``` ```js diff --git a/snippets/composeRight.md b/snippets/composeRight.md index 0e93e4272..af9e1ba2d 100644 --- a/snippets/composeRight.md +++ b/snippets/composeRight.md @@ -9,7 +9,8 @@ Performs left-to-right function composition. - The first (leftmost) function can accept one or more arguments; the remaining functions must be unary. ```js -const composeRight = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); +const composeRight = (...fns) => + fns.reduce((f, g) => (...args) => g(f(...args))); ``` ```js diff --git a/snippets/copyToClipboard.md b/snippets/copyToClipboard.md index d9f93ff55..d4c684b46 100644 --- a/snippets/copyToClipboard.md +++ b/snippets/copyToClipboard.md @@ -22,7 +22,9 @@ const copyToClipboard = str => { el.style.left = '-9999px'; document.body.appendChild(el); const selected = - document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false; + document.getSelection().rangeCount > 0 + ? document.getSelection().getRangeAt(0) + : false; el.select(); document.execCommand('copy'); document.body.removeChild(el); diff --git a/snippets/counter.md b/snippets/counter.md index 5dfc2dbff..8f41068c6 100644 --- a/snippets/counter.md +++ b/snippets/counter.md @@ -26,5 +26,6 @@ const counter = (selector, start, end, step = 1, duration = 2000) => { ``` ```js -counter('#my-id', 1, 1000, 5, 2000); // Creates a 2-second timer for the element with id="my-id" +counter('#my-id', 1, 1000, 5, 2000); +// Creates a 2-second timer for the element with id="my-id" ``` diff --git a/snippets/createDirIfNotExists.md b/snippets/createDirIfNotExists.md index 6ed92f015..2e76b0b7d 100644 --- a/snippets/createDirIfNotExists.md +++ b/snippets/createDirIfNotExists.md @@ -14,5 +14,6 @@ const createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : u ``` ```js -createDirIfNotExists('test'); // creates the directory 'test', if it doesn't exist +createDirIfNotExists('test'); +// creates the directory 'test', if it doesn't exist ``` diff --git a/snippets/curry.md b/snippets/curry.md index 1ef511cb7..a54dfd2b5 100644 --- a/snippets/curry.md +++ b/snippets/curry.md @@ -1,6 +1,6 @@ --- title: curry -tags: function,recursion,intermediate +tags: function,recursion,advanced --- Curries a function. diff --git a/snippets/dayName.md b/snippets/dayName.md index cbda0bd8d..842c63aaf 100644 --- a/snippets/dayName.md +++ b/snippets/dayName.md @@ -9,7 +9,8 @@ Gets the name of the weekday from a `Date` object. - Use the optional second parameter to get a language-specific name or omit it to use the default locale. ```js -const dayName = (date, locale) => date.toLocaleDateString(locale, { weekday: 'long' }); +const dayName = (date, locale) => + date.toLocaleDateString(locale, { weekday: 'long' }); ``` ```js diff --git a/snippets/decapitalize.md b/snippets/decapitalize.md index c59a80d70..01a1292a0 100644 --- a/snippets/decapitalize.md +++ b/snippets/decapitalize.md @@ -10,7 +10,8 @@ Decapitalizes the first letter of a string. ```js const decapitalize = ([first, ...rest], upperRest = false) => - first.toLowerCase() + (upperRest ? rest.join('').toUpperCase() : rest.join('')); + first.toLowerCase() + + (upperRest ? rest.join('').toUpperCase() : rest.join('')); ``` ```js diff --git a/snippets/deepClone.md b/snippets/deepClone.md index 9bfc09926..54bcb9b9d 100644 --- a/snippets/deepClone.md +++ b/snippets/deepClone.md @@ -17,7 +17,9 @@ const deepClone = obj => { if (obj === null) return null; let clone = Object.assign({}, obj); Object.keys(clone).forEach( - key => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key]) + key => + (clone[key] = + typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key]) ); if (Array.isArray(obj)) { clone.length = obj.length; diff --git a/snippets/deepFlatten.md b/snippets/deepFlatten.md index e7fa0180a..200d486a2 100644 --- a/snippets/deepFlatten.md +++ b/snippets/deepFlatten.md @@ -10,7 +10,8 @@ Deep flattens an array. - Recursively flatten each element that is an array. ```js -const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v))); +const deepFlatten = arr => + [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v))); ``` ```js diff --git a/snippets/defaults.md b/snippets/defaults.md index c2ec18710..a72fcfe84 100644 --- a/snippets/defaults.md +++ b/snippets/defaults.md @@ -10,7 +10,8 @@ Assigns default values for all properties in an object that are `undefined`. - Finally, use `obj` again to overwrite properties that originally had a value. ```js -const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj); +const defaults = (obj, ...defs) => + Object.assign({}, obj, ...defs.reverse(), obj); ``` ```js diff --git a/snippets/defer.md b/snippets/defer.md index 4fe76d8e7..fe485d5f0 100644 --- a/snippets/defer.md +++ b/snippets/defer.md @@ -18,6 +18,8 @@ defer(console.log, 'a'), console.log('b'); // logs 'b' then 'a' // Example B: document.querySelector('#someElement').innerHTML = 'Hello'; -longRunningFunction(); // Browser will not update the HTML until this has finished -defer(longRunningFunction); // Browser will update the HTML then run the function +longRunningFunction(); +// Browser will not update the HTML until this has finished +defer(longRunningFunction); +// Browser will update the HTML then run the function ``` diff --git a/snippets/detectDeviceType.md b/snippets/detectDeviceType.md index 311da2ab3..16675c863 100644 --- a/snippets/detectDeviceType.md +++ b/snippets/detectDeviceType.md @@ -9,7 +9,9 @@ Detects whether the page is being viewed on a mobile device or a desktop. ```js const detectDeviceType = () => - /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) + /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( + navigator.userAgent + ) ? 'Mobile' : 'Desktop'; ``` diff --git a/snippets/differenceWith.md b/snippets/differenceWith.md index 48c78874f..a68f8abc9 100644 --- a/snippets/differenceWith.md +++ b/snippets/differenceWith.md @@ -14,6 +14,10 @@ const differenceWith = (arr, val, comp = (a, b) => a === b) => ``` ```js -differenceWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0], (a, b) => Math.round(a) === Math.round(b)); // [1, 1.2] +differenceWith( + [1, 1.2, 1.5, 3, 0], + [1.9, 3, 0], + (a, b) => Math.round(a) === Math.round(b) +); // [1, 1.2] differenceWith([1, 1.2, 1.3], [1, 1.3, 1.5]); // [1.2] ``` diff --git a/snippets/drop.md b/snippets/drop.md index daa0ae84f..4d5c77169 100644 --- a/snippets/drop.md +++ b/snippets/drop.md @@ -3,7 +3,7 @@ title: drop tags: array,beginner --- -Returns a new array with `n` elements removed from the left. +Creates a new array with `n` elements removed from the left. - Use `Array.prototype.slice()` to remove the specified number of elements from the left. @@ -12,7 +12,7 @@ const drop = (arr, n = 1) => arr.slice(n); ``` ```js -drop([1, 2, 3]); // [2,3] +drop([1, 2, 3]); // [2, 3] drop([1, 2, 3], 2); // [3] drop([1, 2, 3], 42); // [] -``` \ No newline at end of file +``` diff --git a/snippets/dropRight.md b/snippets/dropRight.md index befde7ac3..33fbb849a 100644 --- a/snippets/dropRight.md +++ b/snippets/dropRight.md @@ -3,7 +3,7 @@ title: dropRight tags: array,beginner --- -Returns a new array with `n` elements removed from the right. +Creates a new array with `n` elements removed from the right. - Use `Array.prototype.slice()` to remove the specified number of elements from the right. diff --git a/snippets/elementContains.md b/snippets/elementContains.md index 2e2ab5c02..90707ba29 100644 --- a/snippets/elementContains.md +++ b/snippets/elementContains.md @@ -9,10 +9,13 @@ Checks if the `parent` element contains the `child` element. - Use `Node.contains()` to check if the `parent` element contains the `child` element. ```js -const elementContains = (parent, child) => parent !== child && parent.contains(child); +const elementContains = (parent, child) => + parent !== child && parent.contains(child); ``` ```js -elementContains(document.querySelector('head'), document.querySelector('title')); // true -elementContains(document.querySelector('body'), document.querySelector('body')); // false +elementContains(document.querySelector('head'), document.querySelector('title')); +// true +elementContains(document.querySelector('body'), document.querySelector('body')); +// false ``` diff --git a/snippets/elementIsVisibleInViewport.md b/snippets/elementIsVisibleInViewport.md index db3fae005..cc08a7cba 100644 --- a/snippets/elementIsVisibleInViewport.md +++ b/snippets/elementIsVisibleInViewport.md @@ -13,7 +13,8 @@ const elementIsVisibleInViewport = (el, partiallyVisible = false) => { const { top, left, bottom, right } = el.getBoundingClientRect(); const { innerHeight, innerWidth } = window; return partiallyVisible - ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) && + ? ((top > 0 && top < innerHeight) || + (bottom > 0 && bottom < innerHeight)) && ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)) : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth; }; diff --git a/snippets/equals.md b/snippets/equals.md index 0035052a7..8f6ba4dae 100644 --- a/snippets/equals.md +++ b/snippets/equals.md @@ -13,8 +13,10 @@ Performs a deep comparison between two values to determine if they are equivalen ```js const equals = (a, b) => { if (a === b) return true; - if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime(); - if (!a || !b || (typeof a !== 'object' && typeof b !== 'object')) return a === b; + if (a instanceof Date && b instanceof Date) + return a.getTime() === b.getTime(); + if (!a || !b || (typeof a !== 'object' && typeof b !== 'object')) + return a === b; if (a.prototype !== b.prototype) return false; let keys = Object.keys(a); if (keys.length !== Object.keys(b).length) return false; @@ -23,6 +25,9 @@ const equals = (a, b) => { ``` ```js -equals({ a: [2, { e: 3 }], b: [4], c: 'foo' }, { a: [2, { e: 3 }], b: [4], c: 'foo' }); // true +equals( + { a: [2, { e: 3 }], b: [4], c: 'foo' }, + { a: [2, { e: 3 }], b: [4], c: 'foo' } +); // true equals([1, 2, 3], { 0: 1, 1: 2, 2: 3 }); // true ``` diff --git a/snippets/filterNonUnique.md b/snippets/filterNonUnique.md index 6205362d3..53e5d3b2f 100644 --- a/snippets/filterNonUnique.md +++ b/snippets/filterNonUnique.md @@ -3,12 +3,13 @@ title: filterNonUnique tags: array,beginner --- -Returns an array with the non-unique values filtered out. +Creates an array with the non-unique values filtered out. - Use `Array.prototype.filter()` to create an array containing only the unique values. ```js -const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i)); +const filterNonUnique = arr => + arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i)); ``` ```js diff --git a/snippets/filterNonUniqueBy.md b/snippets/filterNonUniqueBy.md index 1b079195d..ee282c55e 100644 --- a/snippets/filterNonUniqueBy.md +++ b/snippets/filterNonUniqueBy.md @@ -3,7 +3,7 @@ title: filterNonUniqueBy tags: array,intermediate --- -Returns an array with the non-unique values filtered out, based on a provided comparator function. +Creates an array with the non-unique values filtered out, based on a provided comparator function. - Use `Array.prototype.filter()` and `Array.prototype.every()` to create an array containing only the unique values, based on the comparator function, `fn`. - The comparator function takes four arguments: the values of the two elements being compared and their indexes. diff --git a/snippets/findKey.md b/snippets/findKey.md index f7bdd81e8..c4b793314 100644 --- a/snippets/findKey.md +++ b/snippets/findKey.md @@ -3,14 +3,15 @@ title: findKey tags: object,intermediate --- -Returns the first key that satisfies the provided testing function. +Finds the first key that satisfies the provided testing function. Otherwise `undefined` is returned. - Use `Object.keys(obj)` to get all the properties of the object, `Array.prototype.find()` to test each key-value pair using `fn`. - The callback receives three arguments - the value, the key and the object. ```js -const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj)); +const findKey = (obj, fn) => + Object.keys(obj).find(key => fn(obj[key], key, obj)); ``` ```js diff --git a/snippets/findLast.md b/snippets/findLast.md index ed8db3593..a44829381 100644 --- a/snippets/findLast.md +++ b/snippets/findLast.md @@ -3,7 +3,7 @@ title: findLast tags: array,beginner --- -Returns the last element for which the provided function returns a truthy value. +Finds the last element for which the provided function returns a truthy value. - Use `Array.prototype.filter()` to remove elements for which `fn` returns falsy values. - Use `Array.prototype.pop()` to get the last element in the filtered array. diff --git a/snippets/findLastIndex.md b/snippets/findLastIndex.md index 3b86ed6f0..a5716b9a5 100644 --- a/snippets/findLastIndex.md +++ b/snippets/findLastIndex.md @@ -3,7 +3,7 @@ title: findLastIndex tags: array,intermediate --- -Returns the index of the last element for which the provided function returns a truthy value. +Finds the index of the last element for which the provided function returns a truthy value. - Use `Array.prototype.map()` to map each element to an array with its index and value. - Use `Array.prototype.filter()` to remove elements for which `fn` returns falsy values diff --git a/snippets/findLastKey.md b/snippets/findLastKey.md index ae86d0517..c866157d4 100644 --- a/snippets/findLastKey.md +++ b/snippets/findLastKey.md @@ -3,7 +3,7 @@ title: findLastKey tags: object,intermediate --- -Returns the last key that satisfies the provided testing function. +Finds the last key that satisfies the provided testing function. Otherwise `undefined` is returned. - Use `Object.keys(obj)` to get all the properties of the object. diff --git a/snippets/flatten.md b/snippets/flatten.md index c222c430b..617e477d2 100644 --- a/snippets/flatten.md +++ b/snippets/flatten.md @@ -12,7 +12,11 @@ Flattens an array up to the specified depth. ```js const flatten = (arr, depth = 1) => - arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []); + arr.reduce( + (a, v) => + a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), + [] + ); ``` ```js diff --git a/snippets/forOwn.md b/snippets/forOwn.md index 01773585b..185d0eda0 100644 --- a/snippets/forOwn.md +++ b/snippets/forOwn.md @@ -10,7 +10,8 @@ Iterates over all own properties of an object, running a callback for each one. - The callback receives three arguments - the value, the key and the object. ```js -const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj)); +const forOwn = (obj, fn) => + Object.keys(obj).forEach(key => fn(obj[key], key, obj)); ``` ```js diff --git a/snippets/formatDuration.md b/snippets/formatDuration.md index 79135760d..7e488a522 100644 --- a/snippets/formatDuration.md +++ b/snippets/formatDuration.md @@ -29,5 +29,6 @@ const formatDuration = ms => { ```js formatDuration(1001); // '1 second, 1 millisecond' -formatDuration(34325055574); // '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds' +formatDuration(34325055574); +// '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds' ``` diff --git a/snippets/formatNumber.md b/snippets/formatNumber.md index 79bbe8567..b572226c4 100644 --- a/snippets/formatNumber.md +++ b/snippets/formatNumber.md @@ -3,7 +3,7 @@ title: formatNumber tags: string,math,beginner --- -Returns a number using the local number format order. +Formats a number using the local number format order. - Use `Number.prototype.toLocaleString()` to convert a number to using the local number format separators. diff --git a/snippets/fromCamelCase.md b/snippets/fromCamelCase.md index 452aef813..3d6a79125 100644 --- a/snippets/fromCamelCase.md +++ b/snippets/fromCamelCase.md @@ -18,7 +18,8 @@ const fromCamelCase = (str, separator = '_') => ```js fromCamelCase('someDatabaseFieldName', ' '); // 'some database field name' -fromCamelCase('someLabelThatNeedsToBeDecamelized', '-'); // 'some-label-that-needs-to-be-decamelized' +fromCamelCase('someLabelThatNeedsToBeDecamelized', '-'); +// 'some-label-that-needs-to-be-decamelized' fromCamelCase('someJavascriptProperty', '_'); // 'some_javascript_property' fromCamelCase('JSONToCSV', '.'); // 'json.to.csv' ``` diff --git a/snippets/generateItems.md b/snippets/generateItems.md index 70a9a11dc..3bb0f8a34 100644 --- a/snippets/generateItems.md +++ b/snippets/generateItems.md @@ -13,5 +13,6 @@ const generateItems = (n, fn) => Array.from({ length: n }, (_, i) => fn(i)); ``` ```js -generateItems(10, Math.random); // [0.21, 0.08, 0.40, 0.96, 0.96, 0.24, 0.19, 0.96, 0.42, 0.70] +generateItems(10, Math.random); +// [0.21, 0.08, 0.40, 0.96, 0.96, 0.24, 0.19, 0.96, 0.42, 0.70] ``` diff --git a/snippets/geometricProgression.md b/snippets/geometricProgression.md index dfb5dbd2c..40a7b7c47 100644 --- a/snippets/geometricProgression.md +++ b/snippets/geometricProgression.md @@ -12,9 +12,9 @@ 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( - (_, i) => start * step ** i - ); + Array.from({ + length: Math.floor(Math.log(end / start) / Math.log(step)) + 1, + }).map((_, i) => start * step ** i); ``` ```js diff --git a/snippets/getBaseURL.md b/snippets/getBaseURL.md index c75b3635c..984cfbf9c 100644 --- a/snippets/getBaseURL.md +++ b/snippets/getBaseURL.md @@ -13,5 +13,6 @@ const getBaseURL = url => ``` ```js -getBaseURL('http://url.com/page?name=Adam&surname=Smith'); // 'http://url.com/page' +getBaseURL('http://url.com/page?name=Adam&surname=Smith'); +// 'http://url.com/page' ``` diff --git a/snippets/getElementsBiggerThanViewport.md b/snippets/getElementsBiggerThanViewport.md index f53dac496..ae96f26b3 100644 --- a/snippets/getElementsBiggerThanViewport.md +++ b/snippets/getElementsBiggerThanViewport.md @@ -11,7 +11,9 @@ Returns an array of HTML elements whose width is larger than that of the viewpor ```js const getElementsBiggerThanViewport = () => { const docWidth = document.documentElement.offsetWidth; - return [...document.querySelectorAll('*')].filter(el => el.offsetWidth > docWidth); + return [...document.querySelectorAll('*')].filter( + el => el.offsetWidth > docWidth + ); }; ``` diff --git a/snippets/getImages.md b/snippets/getImages.md index 6a291340d..2fc8535b9 100644 --- a/snippets/getImages.md +++ b/snippets/getImages.md @@ -12,7 +12,9 @@ Fetches all images from within an element and puts them into an array. ```js const getImages = (el, includeDuplicates = false) => { - const images = [...el.getElementsByTagName('img')].map(img => img.getAttribute('src')); + const images = [...el.getElementsByTagName('img')].map(img => + img.getAttribute('src') + ); return includeDuplicates ? images : [...new Set(images)]; }; ``` diff --git a/snippets/getURLParameters.md b/snippets/getURLParameters.md index 4c0f04af2..dec79d33d 100644 --- a/snippets/getURLParameters.md +++ b/snippets/getURLParameters.md @@ -3,7 +3,7 @@ title: getURLParameters tags: browser,string,regexp,intermediate --- -Returns an object containing the parameters of the current URL. +Creates an object containing the parameters of the current URL. - 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. @@ -12,7 +12,9 @@ Returns an object containing the parameters of the current URL. ```js const getURLParameters = url => (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 + ), {} ); ``` diff --git a/snippets/groupBy.md b/snippets/groupBy.md index 575b971c9..1c966c1e7 100644 --- a/snippets/groupBy.md +++ b/snippets/groupBy.md @@ -10,10 +10,12 @@ Groups the elements of an array based on the given function. ```js const groupBy = (arr, fn) => - arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => { - acc[val] = (acc[val] || []).concat(arr[i]); - return acc; - }, {}); + arr + .map(typeof fn === 'function' ? fn : val => val[fn]) + .reduce((acc, val, i) => { + acc[val] = (acc[val] || []).concat(arr[i]); + return acc; + }, {}); ``` ```js diff --git a/snippets/hasFlags.md b/snippets/hasFlags.md index af841f827..3b7bdf34a 100644 --- a/snippets/hasFlags.md +++ b/snippets/hasFlags.md @@ -10,7 +10,9 @@ Checks if the current process's arguments contain the specified flags. ```js const hasFlags = (...flags) => - flags.every(flag => process.argv.includes(/^-{1,2}/.test(flag) ? flag : '--' + flag)); + flags.every(flag => + process.argv.includes(/^-{1,2}/.test(flag) ? flag : '--' + flag) + ); ``` ```js diff --git a/snippets/hashBrowser.md b/snippets/hashBrowser.md index 9bff5fedb..47863305c 100644 --- a/snippets/hashBrowser.md +++ b/snippets/hashBrowser.md @@ -14,13 +14,15 @@ Returns a promise. ```js const hashBrowser = val => - crypto.subtle.digest('SHA-256', new TextEncoder('utf-8').encode(val)).then(h => { - let hexes = [], - view = new DataView(h); - for (let i = 0; i < view.byteLength; i += 4) - hexes.push(('00000000' + view.getUint32(i).toString(16)).slice(-8)); - return hexes.join(''); - }); + crypto.subtle + .digest('SHA-256', new TextEncoder('utf-8').encode(val)) + .then(h => { + let hexes = [], + view = new DataView(h); + for (let i = 0; i < view.byteLength; i += 4) + hexes.push(('00000000' + view.getUint32(i).toString(16)).slice(-8)); + return hexes.join(''); + }); ``` ```js diff --git a/snippets/httpsRedirect.md b/snippets/httpsRedirect.md index 469e893a6..88106e023 100644 --- a/snippets/httpsRedirect.md +++ b/snippets/httpsRedirect.md @@ -12,7 +12,8 @@ Redirects the page to HTTPS if it's currently in HTTP. ```js const httpsRedirect = () => { - if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]); + if (location.protocol !== 'https:') + location.replace('https://' + location.href.split('//')[1]); }; ``` diff --git a/snippets/indexOfAll.md b/snippets/indexOfAll.md index 4b7abbf29..890c41868 100644 --- a/snippets/indexOfAll.md +++ b/snippets/indexOfAll.md @@ -3,7 +3,7 @@ title: indexOfAll tags: array,intermediate --- -Returns all indexes of `val` in an array. +Finds all indexes of `val` in an array. If `val` never occurs, returns an empty array. - Use `Array.prototype.reduce()` to loop over elements and store indexes for matching elements. diff --git a/snippets/initializeArrayWithRange.md b/snippets/initializeArrayWithRange.md index aeb8c9da1..ba6b9693e 100644 --- a/snippets/initializeArrayWithRange.md +++ b/snippets/initializeArrayWithRange.md @@ -12,7 +12,10 @@ Initializes an array containing the numbers in the specified range where `start` ```js const initializeArrayWithRange = (end, start = 0, step = 1) => - Array.from({ length: Math.ceil((end - start + 1) / step) }, (_, i) => i * step + start); + Array.from( + { length: Math.ceil((end - start + 1) / step) }, + (_, i) => i * step + start + ); ``` ```js diff --git a/snippets/initializeNDArray.md b/snippets/initializeNDArray.md index 2a44b1d9b..7bf44514d 100644 --- a/snippets/initializeNDArray.md +++ b/snippets/initializeNDArray.md @@ -12,7 +12,9 @@ Create a n-dimensional array with given value. const initializeNDArray = (val, ...args) => args.length === 0 ? val - : Array.from({ length: args[0] }).map(() => initializeNDArray(val, ...args.slice(1))); + : Array.from({ length: args[0] }).map(() => + initializeNDArray(val, ...args.slice(1)) + ); ``` ```js diff --git a/snippets/injectCSS.md b/snippets/injectCSS.md index f21935528..abd760647 100644 --- a/snippets/injectCSS.md +++ b/snippets/injectCSS.md @@ -17,7 +17,7 @@ const injectCSS = css => { el.innerText = css; document.head.appendChild(el); return el; -} +}; ``` ```js diff --git a/snippets/isContainedIn.md b/snippets/isContainedIn.md index 7bea6100f..836d448c4 100644 --- a/snippets/isContainedIn.md +++ b/snippets/isContainedIn.md @@ -13,7 +13,10 @@ Checks if the elements of the first array are contained in the second one regard ```js const isContainedIn = (a, b) => { for (const v of new Set(a)) { - if (!b.some(e => e === v) || a.filter(e => e === v).length > b.filter(e => e === v).length) + if ( + !b.some(e => e === v) || + a.filter(e => e === v).length > b.filter(e => e === v).length + ) return false; } return true; diff --git a/snippets/isObject.md b/snippets/isObject.md index 817e9d401..93ffc19a1 100644 --- a/snippets/isObject.md +++ b/snippets/isObject.md @@ -3,7 +3,7 @@ title: isObject tags: type,object,beginner --- -Returns a boolean determining if the passed value is an object or not. +Checks if the passed value is an object or not. - Uses the `Object` constructor to create an object wrapper for the given value. - If the value is `null` or `undefined`, create and return an empty object. diff --git a/snippets/isPrimitive.md b/snippets/isPrimitive.md index 60d08fd7f..839a24630 100644 --- a/snippets/isPrimitive.md +++ b/snippets/isPrimitive.md @@ -3,7 +3,7 @@ title: isPrimitive tags: type,intermediate --- -Returns a boolean determining if the passed value is primitive or not. +Checks if the passed value is primitive or not. - Create an object from `val` and compare it with `val` to determine if the passed value is primitive (i.e. not equal to the created object). diff --git a/snippets/join.md b/snippets/join.md index fc0d992db..70bae7471 100644 --- a/snippets/join.md +++ b/snippets/join.md @@ -25,7 +25,7 @@ const join = (arr, separator = ',', end = separator) => ``` ```js -join(['pen', 'pineapple', 'apple', 'pen'], ',', '&'); // 'pen,pineapple,apple&pen' +join(['pen', 'pineapple', 'apple', 'pen'],',','&'); // 'pen,pineapple,apple&pen' join(['pen', 'pineapple', 'apple', 'pen'], ','); // 'pen,pineapple,apple,pen' join(['pen', 'pineapple', 'apple', 'pen']); // 'pen,pineapple,apple,pen' ``` diff --git a/snippets/lcm.md b/snippets/lcm.md index c519ea84c..328d5c72b 100644 --- a/snippets/lcm.md +++ b/snippets/lcm.md @@ -3,7 +3,7 @@ title: lcm tags: math,recursion,intermediate --- -Returns the least common multiple of two or more numbers. +Calculates the least common multiple of two or more numbers. - Use the greatest common divisor (GCD) formula and the fact that `lcm(x,y) = x * y / gcd(x,y)` to determine the least common multiple. - The GCD formula uses recursion. diff --git a/snippets/listenOnce.md b/snippets/listenOnce.md index fa62b9bd0..f06e72543 100644 --- a/snippets/listenOnce.md +++ b/snippets/listenOnce.md @@ -9,7 +9,8 @@ Adds an event listener to an element that will only run the callback the first t - Use `{ once: true }` as options to only run the given callback once. ```js -const listenOnce = (el, evt, fn) => el.addEventListener(evt, fn, { once: true }); +const listenOnce = (el, evt, fn) => + el.addEventListener(evt, fn, { once: true }); ``` ```js diff --git a/snippets/logBase.md b/snippets/logBase.md index c55f52d73..ebc6dcd65 100644 --- a/snippets/logBase.md +++ b/snippets/logBase.md @@ -3,7 +3,7 @@ title: logBase tags: math,beginner --- -Returns the logarithm of the given number in the given base. +Calculates the logarithm of the given number in the given base. - Use `Math.log()` to get the logarithm from the value and the base and divide them. diff --git a/snippets/longestItem.md b/snippets/longestItem.md index c10a32fb2..3e41e8a1b 100644 --- a/snippets/longestItem.md +++ b/snippets/longestItem.md @@ -10,7 +10,8 @@ Takes any number of iterable objects or objects with a `length` property and ret - Returns `undefined` if no arguments are provided. ```js -const longestItem = (...vals) => vals.reduce((a, x) => (x.length > a.length ? x : a)); +const longestItem = (...vals) => + vals.reduce((a, x) => (x.length > a.length ? x : a)); ``` ```js diff --git a/snippets/median.md b/snippets/median.md index bcace19e9..af273a19e 100644 --- a/snippets/median.md +++ b/snippets/median.md @@ -3,7 +3,7 @@ title: median tags: math,array,intermediate --- -Returns the median of an array of numbers. +Calculates the median of an array of numbers. - Find the middle of the array, use `Array.prototype.sort()` to sort the values. - Return the number at the midpoint if `Array.prototype.length` is odd, otherwise the average of the two middle numbers.