Format snippets

This commit is contained in:
Isabelle Viktoria Maciohsek
2020-10-22 20:23:47 +03:00
parent 3936a1d3b8
commit aedcded750
70 changed files with 185 additions and 101 deletions

View File

@ -19,7 +19,10 @@ const CSVToJSON = (data, delimiter = ',') => {
.split('\n') .split('\n')
.map(v => { .map(v => {
const values = v.split(delimiter); 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),
{}
);
}); });
}; };
``` ```

View File

@ -16,10 +16,11 @@ const JSONtoCSV = (arr, columns, delimiter = ',') =>
columns.join(delimiter), columns.join(delimiter),
...arr.map(obj => ...arr.map(obj =>
columns.reduce( columns.reduce(
(acc, key) => `${acc}${!acc.length ? '' : delimiter}"${!obj[key] ? '' : obj[key]}"`, (acc, key) =>
`${acc}${!acc.length ? '' : delimiter}"${!obj[key] ? '' : obj[key]}"`,
'' ''
) )
) ),
].join('\n'); ].join('\n');
``` ```

View File

@ -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. - 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 ```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 ```js

View File

@ -9,8 +9,10 @@ Adds multiple event listeners with the same handler to an element.
```js ```js
const addMultipleListeners = (el, types, listener, options, useCapture) => { 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 ```js

View File

@ -12,12 +12,10 @@ Calculates the date after adding the ginen number of business days.
```js ```js
const addWeekDays = (startDate, count) => const addWeekDays = (startDate, count) =>
Array Array.from({ length: count }).reduce(date => {
.from({ length: count })
.reduce(date => {
date = new Date(date.setDate(date.getDate() + 1)); date = new Date(date.setDate(date.getDate() + 1));
if (date.getDay() % 6 === 0) if (date.getDay() % 6 === 0)
date = new Date(date.setDate(date.getDate() + ((date.getDay() / 6) + 1))); date = new Date(date.setDate(date.getDate() + (date.getDay() / 6 + 1)));
return date; return date;
}, startDate); }, startDate);
``` ```

View File

@ -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`. - Omit the third parameter, `epsilon`, to use a default value of `0.001`.
```js ```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 ```js

View File

@ -9,7 +9,8 @@ Calculates the average of two or more numbers.
- Divide the resulting array by its length. - Divide the resulting array by its length.
```js ```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 ```js

View File

@ -10,7 +10,10 @@ Splits values into two groups, based on the result of the given `filter` array.
```js ```js
const bifurcate = (arr, filter) => 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 ```js

View File

@ -10,7 +10,10 @@ Splits values into two groups, based on the result of the given filtering functi
```js ```js
const bifurcateBy = (arr, fn) => 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 ```js

View File

@ -10,7 +10,8 @@ Checks if the bottom of the page is visible.
```js ```js
const bottomVisible = () => const bottomVisible = () =>
document.documentElement.clientHeight + window.scrollY >= document.documentElement.clientHeight + window.scrollY >=
(document.documentElement.scrollHeight || document.documentElement.clientHeight); (document.documentElement.scrollHeight ||
document.documentElement.clientHeight);
``` ```
```js ```js

View File

@ -11,7 +11,8 @@ Capitalizes the first letter of a string.
```js ```js
const capitalize = ([first, ...rest], lowerRest = false) => const capitalize = ([first, ...rest], lowerRest = false) =>
first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join('')); first.toUpperCase() +
(lowerRest ? rest.join('').toLowerCase() : rest.join(''));
``` ```
```js ```js

View File

@ -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. - Use `String.prototype.replace()` to match the first character of each word and `String.prototype.toUpperCase()` to capitalize it.
```js ```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 ```js

View File

@ -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. - Otherwise, return the nearest number in the range.
```js ```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 ```js

View File

@ -1,6 +1,6 @@
--- ---
title: cloneRegExp title: cloneRegExp
tags: regexp,intermediate tags: type,intermediate
--- ---
Clones a regular expression. Clones a regular expression.

View File

@ -12,6 +12,8 @@ const coalesceFactory = valid => (...args) => args.find(valid);
``` ```
```js ```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' customCoalesce(undefined, null, NaN, '', 'Waldo'); // 'Waldo'
``` ```

View File

@ -32,5 +32,6 @@ const colorize = (...args) => ({
```js ```js
console.log(colorize('foo').red); // 'foo' (red letters) console.log(colorize('foo').red); // 'foo' (red letters)
console.log(colorize('foo', 'bar').bgBlue); // 'foo bar' (blue background) 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)
``` ```

View File

@ -12,5 +12,6 @@ const compact = arr => arr.filter(Boolean);
``` ```
```js ```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 ]
``` ```

View File

@ -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. - The last (rightmost) function can accept one or more arguments; the remaining functions must be unary.
```js ```js
const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args))); const compose = (...fns) =>
fns.reduce((f, g) => (...args) => f(g(...args)));
``` ```
```js ```js

View File

@ -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. - The first (leftmost) function can accept one or more arguments; the remaining functions must be unary.
```js ```js
const composeRight = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); const composeRight = (...fns) =>
fns.reduce((f, g) => (...args) => g(f(...args)));
``` ```
```js ```js

View File

@ -22,7 +22,9 @@ const copyToClipboard = str => {
el.style.left = '-9999px'; el.style.left = '-9999px';
document.body.appendChild(el); document.body.appendChild(el);
const selected = const selected =
document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false; document.getSelection().rangeCount > 0
? document.getSelection().getRangeAt(0)
: false;
el.select(); el.select();
document.execCommand('copy'); document.execCommand('copy');
document.body.removeChild(el); document.body.removeChild(el);

View File

@ -26,5 +26,6 @@ const counter = (selector, start, end, step = 1, duration = 2000) => {
``` ```
```js ```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"
``` ```

View File

@ -14,5 +14,6 @@ const createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : u
``` ```
```js ```js
createDirIfNotExists('test'); // creates the directory 'test', if it doesn't exist createDirIfNotExists('test');
// creates the directory 'test', if it doesn't exist
``` ```

View File

@ -1,6 +1,6 @@
--- ---
title: curry title: curry
tags: function,recursion,intermediate tags: function,recursion,advanced
--- ---
Curries a function. Curries a function.

View File

@ -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. - Use the optional second parameter to get a language-specific name or omit it to use the default locale.
```js ```js
const dayName = (date, locale) => date.toLocaleDateString(locale, { weekday: 'long' }); const dayName = (date, locale) =>
date.toLocaleDateString(locale, { weekday: 'long' });
``` ```
```js ```js

View File

@ -10,7 +10,8 @@ Decapitalizes the first letter of a string.
```js ```js
const decapitalize = ([first, ...rest], upperRest = false) => const decapitalize = ([first, ...rest], upperRest = false) =>
first.toLowerCase() + (upperRest ? rest.join('').toUpperCase() : rest.join('')); first.toLowerCase() +
(upperRest ? rest.join('').toUpperCase() : rest.join(''));
``` ```
```js ```js

View File

@ -17,7 +17,9 @@ const deepClone = obj => {
if (obj === null) return null; if (obj === null) return null;
let clone = Object.assign({}, obj); let clone = Object.assign({}, obj);
Object.keys(clone).forEach( 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)) { if (Array.isArray(obj)) {
clone.length = obj.length; clone.length = obj.length;

View File

@ -10,7 +10,8 @@ Deep flattens an array.
- Recursively flatten each element that is an array. - Recursively flatten each element that is an array.
```js ```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 ```js

View File

@ -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. - Finally, use `obj` again to overwrite properties that originally had a value.
```js ```js
const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj); const defaults = (obj, ...defs) =>
Object.assign({}, obj, ...defs.reverse(), obj);
``` ```
```js ```js

View File

@ -18,6 +18,8 @@ defer(console.log, 'a'), console.log('b'); // logs 'b' then 'a'
// Example B: // Example B:
document.querySelector('#someElement').innerHTML = 'Hello'; document.querySelector('#someElement').innerHTML = 'Hello';
longRunningFunction(); // Browser will not update the HTML until this has finished longRunningFunction();
defer(longRunningFunction); // Browser will update the HTML then run the function // Browser will not update the HTML until this has finished
defer(longRunningFunction);
// Browser will update the HTML then run the function
``` ```

View File

@ -9,7 +9,9 @@ Detects whether the page is being viewed on a mobile device or a desktop.
```js ```js
const detectDeviceType = () => 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' ? 'Mobile'
: 'Desktop'; : 'Desktop';
``` ```

View File

@ -14,6 +14,10 @@ const differenceWith = (arr, val, comp = (a, b) => a === b) =>
``` ```
```js ```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] differenceWith([1, 1.2, 1.3], [1, 1.3, 1.5]); // [1.2]
``` ```

View File

@ -3,7 +3,7 @@ title: drop
tags: array,beginner 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. - Use `Array.prototype.slice()` to remove the specified number of elements from the left.

View File

@ -3,7 +3,7 @@ title: dropRight
tags: array,beginner 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. - Use `Array.prototype.slice()` to remove the specified number of elements from the right.

View File

@ -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. - Use `Node.contains()` to check if the `parent` element contains the `child` element.
```js ```js
const elementContains = (parent, child) => parent !== child && parent.contains(child); const elementContains = (parent, child) =>
parent !== child && parent.contains(child);
``` ```
```js ```js
elementContains(document.querySelector('head'), document.querySelector('title')); // true elementContains(document.querySelector('head'), document.querySelector('title'));
elementContains(document.querySelector('body'), document.querySelector('body')); // false // true
elementContains(document.querySelector('body'), document.querySelector('body'));
// false
``` ```

View File

@ -13,7 +13,8 @@ const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
const { top, left, bottom, right } = el.getBoundingClientRect(); const { top, left, bottom, right } = el.getBoundingClientRect();
const { innerHeight, innerWidth } = window; const { innerHeight, innerWidth } = window;
return partiallyVisible 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)) ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
: top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth; : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
}; };

View File

@ -13,8 +13,10 @@ Performs a deep comparison between two values to determine if they are equivalen
```js ```js
const equals = (a, b) => { const equals = (a, b) => {
if (a === b) return true; if (a === b) return true;
if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime(); if (a instanceof Date && b instanceof Date)
if (!a || !b || (typeof a !== 'object' && typeof b !== 'object')) return a === b; return a.getTime() === b.getTime();
if (!a || !b || (typeof a !== 'object' && typeof b !== 'object'))
return a === b;
if (a.prototype !== b.prototype) return false; if (a.prototype !== b.prototype) return false;
let keys = Object.keys(a); let keys = Object.keys(a);
if (keys.length !== Object.keys(b).length) return false; if (keys.length !== Object.keys(b).length) return false;
@ -23,6 +25,9 @@ const equals = (a, b) => {
``` ```
```js ```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 equals([1, 2, 3], { 0: 1, 1: 2, 2: 3 }); // true
``` ```

View File

@ -3,12 +3,13 @@ title: filterNonUnique
tags: array,beginner 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. - Use `Array.prototype.filter()` to create an array containing only the unique values.
```js ```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 ```js

View File

@ -3,7 +3,7 @@ title: filterNonUniqueBy
tags: array,intermediate 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`. - 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. - The comparator function takes four arguments: the values of the two elements being compared and their indexes.

View File

@ -3,14 +3,15 @@ title: findKey
tags: object,intermediate 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. 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`. - 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. - The callback receives three arguments - the value, the key and the object.
```js ```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 ```js

View File

@ -3,7 +3,7 @@ title: findLast
tags: array,beginner 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.filter()` to remove elements for which `fn` returns falsy values.
- Use `Array.prototype.pop()` to get the last element in the filtered array. - Use `Array.prototype.pop()` to get the last element in the filtered array.

View File

@ -3,7 +3,7 @@ title: findLastIndex
tags: array,intermediate 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.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 - Use `Array.prototype.filter()` to remove elements for which `fn` returns falsy values

View File

@ -3,7 +3,7 @@ title: findLastKey
tags: object,intermediate 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. Otherwise `undefined` is returned.
- Use `Object.keys(obj)` to get all the properties of the object. - Use `Object.keys(obj)` to get all the properties of the object.

View File

@ -12,7 +12,11 @@ Flattens an array up to the specified depth.
```js ```js
const flatten = (arr, depth = 1) => 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 ```js

View File

@ -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. - The callback receives three arguments - the value, the key and the object.
```js ```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 ```js

View File

@ -29,5 +29,6 @@ const formatDuration = ms => {
```js ```js
formatDuration(1001); // '1 second, 1 millisecond' 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'
``` ```

View File

@ -3,7 +3,7 @@ title: formatNumber
tags: string,math,beginner 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. - Use `Number.prototype.toLocaleString()` to convert a number to using the local number format separators.

View File

@ -18,7 +18,8 @@ const fromCamelCase = (str, separator = '_') =>
```js ```js
fromCamelCase('someDatabaseFieldName', ' '); // 'some database field name' 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('someJavascriptProperty', '_'); // 'some_javascript_property'
fromCamelCase('JSONToCSV', '.'); // 'json.to.csv' fromCamelCase('JSONToCSV', '.'); // 'json.to.csv'
``` ```

View File

@ -13,5 +13,6 @@ const generateItems = (n, fn) => Array.from({ length: n }, (_, i) => fn(i));
``` ```
```js ```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]
``` ```

View File

@ -12,9 +12,9 @@ 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({
(_, i) => start * step ** i length: Math.floor(Math.log(end / start) / Math.log(step)) + 1,
); }).map((_, i) => start * step ** i);
``` ```
```js ```js

View File

@ -13,5 +13,6 @@ const getBaseURL = url =>
``` ```
```js ```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'
``` ```

View File

@ -11,7 +11,9 @@ Returns an array of HTML elements whose width is larger than that of the viewpor
```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
);
}; };
``` ```

View File

@ -12,7 +12,9 @@ Fetches all images from within an element and puts them into an array.
```js ```js
const getImages = (el, includeDuplicates = false) => { 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)]; return includeDuplicates ? images : [...new Set(images)];
}; };
``` ```

View File

@ -3,7 +3,7 @@ title: getURLParameters
tags: browser,string,regexp,intermediate 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 `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. - 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 ```js
const getURLParameters = url => const getURLParameters = url =>
(url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce( (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
(a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a), (a, v) => (
(a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a
),
{} {}
); );
``` ```

View File

@ -10,7 +10,9 @@ Groups the elements of an array based on the given function.
```js ```js
const groupBy = (arr, fn) => const groupBy = (arr, fn) =>
arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => { arr
.map(typeof fn === 'function' ? fn : val => val[fn])
.reduce((acc, val, i) => {
acc[val] = (acc[val] || []).concat(arr[i]); acc[val] = (acc[val] || []).concat(arr[i]);
return acc; return acc;
}, {}); }, {});

View File

@ -10,7 +10,9 @@ Checks if the current process's arguments contain the specified flags.
```js ```js
const hasFlags = (...flags) => 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 ```js

View File

@ -14,7 +14,9 @@ Returns a promise.
```js ```js
const hashBrowser = val => const hashBrowser = val =>
crypto.subtle.digest('SHA-256', new TextEncoder('utf-8').encode(val)).then(h => { crypto.subtle
.digest('SHA-256', new TextEncoder('utf-8').encode(val))
.then(h => {
let hexes = [], let hexes = [],
view = new DataView(h); view = new DataView(h);
for (let i = 0; i < view.byteLength; i += 4) for (let i = 0; i < view.byteLength; i += 4)

View File

@ -12,7 +12,8 @@ Redirects the page to HTTPS if it's currently in HTTP.
```js ```js
const httpsRedirect = () => { const httpsRedirect = () => {
if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]); if (location.protocol !== 'https:')
location.replace('https://' + location.href.split('//')[1]);
}; };
``` ```

View File

@ -3,7 +3,7 @@ title: indexOfAll
tags: array,intermediate 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. If `val` never occurs, returns an empty array.
- Use `Array.prototype.reduce()` to loop over elements and store indexes for matching elements. - Use `Array.prototype.reduce()` to loop over elements and store indexes for matching elements.

View File

@ -12,7 +12,10 @@ Initializes an array containing the numbers in the specified range where `start`
```js ```js
const initializeArrayWithRange = (end, start = 0, step = 1) => 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 ```js

View File

@ -12,7 +12,9 @@ Create a n-dimensional array with given value.
const initializeNDArray = (val, ...args) => const initializeNDArray = (val, ...args) =>
args.length === 0 args.length === 0
? val ? val
: Array.from({ length: args[0] }).map(() => initializeNDArray(val, ...args.slice(1))); : Array.from({ length: args[0] }).map(() =>
initializeNDArray(val, ...args.slice(1))
);
``` ```
```js ```js

View File

@ -17,7 +17,7 @@ const injectCSS = css => {
el.innerText = css; el.innerText = css;
document.head.appendChild(el); document.head.appendChild(el);
return el; return el;
} };
``` ```
```js ```js

View File

@ -13,7 +13,10 @@ Checks if the elements of the first array are contained in the second one regard
```js ```js
const isContainedIn = (a, b) => { const isContainedIn = (a, b) => {
for (const v of new Set(a)) { 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 false;
} }
return true; return true;

View File

@ -3,7 +3,7 @@ title: isObject
tags: type,object,beginner 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. - 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. - If the value is `null` or `undefined`, create and return an empty object.

View File

@ -3,7 +3,7 @@ title: isPrimitive
tags: type,intermediate 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). - 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).

View File

@ -3,7 +3,7 @@ title: lcm
tags: math,recursion,intermediate 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. - 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. - The GCD formula uses recursion.

View File

@ -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. - Use `{ once: true }` as options to only run the given callback once.
```js ```js
const listenOnce = (el, evt, fn) => el.addEventListener(evt, fn, { once: true }); const listenOnce = (el, evt, fn) =>
el.addEventListener(evt, fn, { once: true });
``` ```
```js ```js

View File

@ -3,7 +3,7 @@ title: logBase
tags: math,beginner 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. - Use `Math.log()` to get the logarithm from the value and the base and divide them.

View File

@ -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. - Returns `undefined` if no arguments are provided.
```js ```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 ```js

View File

@ -3,7 +3,7 @@ title: median
tags: math,array,intermediate 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. - 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. - Return the number at the midpoint if `Array.prototype.length` is odd, otherwise the average of the two middle numbers.