UNPKG

30s

Version:

A command-line application for 30 seconds of code snippets

733 lines 392 kB
[ { "code": "const CSVToArray = (data, delimiter = ',', omitFirstRow = false) =>\n data\n .slice(omitFirstRow ? data.indexOf('\\n') + 1 : 0)\n .split('\\n')\n .map(v => v.split(delimiter));", "description": "Converts a comma-separated values (CSV) string to a 2D array.\n\n- Use `Array.prototype.slice()` and `Array.prototype.indexOf('\\n')` to remove the first row (title row) if `omitFirstRow` is `true`.\n- Use `String.prototype.split('\\n')` to create a string for each row, then `String.prototype.split(delimiter)` to separate the values in each row.\n- Omit the second argument, `delimiter`, to use a default delimiter of `','`.\n- Omit the third argument, `omitFirstRow`, to include the first row (title row) of the CSV string.", "example": "CSVToArray('a,b\\nc,d'); // [['a', 'b'], ['c', 'd']];\nCSVToArray('a;b\\nc;d', ';'); // [['a', 'b'], ['c', 'd']];\nCSVToArray('col1,col2\\na,b\\nc,d', ',', true); // [['a', 'b'], ['c', 'd']];", "id": "CSVToArray", "tags": [ "string", "array", "intermediate" ] }, { "code": "const CSVToJSON = (data, delimiter = ',') => {\n const titles = data.slice(0, data.indexOf('\\n')).split(delimiter);\n return data\n .slice(data.indexOf('\\n') + 1)\n .split('\\n')\n .map(v => {\n const values = v.split(delimiter);\n return titles.reduce(\n (obj, title, index) => ((obj[title] = values[index]), obj),\n {}\n );\n });\n};", "description": "Converts a comma-separated values (CSV) string to a 2D array of objects.\nThe first row of the string is used as the title row.\n\n- Use `Array.prototype.slice()` and `Array.prototype.indexOf('\\n')` and `String.prototype.split(delimiter)` to separate the first row (title row) into values.\n- Use `String.prototype.split('\\n')` to create a string for each row, then `Array.prototype.map()` and `String.prototype.split(delimiter)` to separate the values in each row.\n- Use `Array.prototype.reduce()` to create an object for each row's values, with the keys parsed from the title row.\n- Omit the second argument, `delimiter`, to use a default delimiter of `,`.", "example": "CSVToJSON('col1,col2\\na,b\\nc,d');\n// [{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}];\nCSVToJSON('col1;col2\\na;b\\nc;d', ';');\n// [{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}];", "id": "CSVToJSON", "tags": [ "string", "object", "advanced" ] }, { "code": "const HSBToRGB = (h, s, b) => {\n s /= 100;\n b /= 100;\n const k = (n) => (n + h / 60) % 6;\n const f = (n) => b * (1 - s * Math.max(0, Math.min(k(n), 4 - k(n), 1)));\n return [255 * f(5), 255 * f(3), 255 * f(1)];\n};", "description": "Converts a HSB color tuple to RGB format.\n\n- Use the [HSB to RGB conversion formula](https://en.wikipedia.org/wiki/HSL_and_HSV#HSV_to_RGB) to convert to the appropriate format.\n- The range of the input parameters is H: [0, 360], S: [0, 100], B: [0, 100].\n- The range of all output values is [0, 255].", "example": "HSBToRGB(18, 81, 99); // [252.45, 109.31084999999996, 47.965499999999984]", "id": "HSBToRGB", "tags": [ "math", "intermediate" ] }, { "code": "const HSLToRGB = (h, s, l) => {\n s /= 100;\n l /= 100;\n const k = n => (n + h / 30) % 12;\n const a = s * Math.min(l, 1 - l);\n const f = n =>\n l - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1)));\n return [255 * f(0), 255 * f(8), 255 * f(4)];\n};", "description": "Converts a HSL color tuple to RGB format.\n\n- Use the [HSL to RGB conversion formula](https://en.wikipedia.org/wiki/HSL_and_HSV#HSL_to_RGB) to convert to the appropriate format.\n- The range of the input parameters is H: [0, 360], S: [0, 100], L: [0, 100].\n- The range of all output values is [0, 255].", "example": "HSLToRGB(13, 100, 11); // [56.1, 12.155, 0]", "id": "HSLToRGB", "tags": [ "math", "intermediate" ] }, { "code": "const fs = require('fs');\n\nconst JSONToFile = (obj, filename) =>\n fs.writeFileSync(\\`\\${filename}.json\\`, JSON.stringify(obj, null, 2));", "description": "Writes a JSON object to a file.\n\n- Use `fs.writeFileSync()`, template literals and `JSON.stringify()` to write a `json` object to a `.json` file.", "example": "JSONToFile({ test: 'is passed' }, 'testJsonFile');\n// writes the object to 'testJsonFile.json'", "id": "JSONToFile", "tags": [ "node", "intermediate" ] }, { "code": "const JSONtoCSV = (arr, columns, delimiter = ',') =>\n [\n columns.join(delimiter),\n ...arr.map(obj =>\n columns.reduce(\n (acc, key) =>\n \\`\\${acc}\\${!acc.length ? '' : delimiter}\"\\${!obj[key] ? '' : obj[key]}\"\\`,\n ''\n )\n ),\n ].join('\\n');", "description": "Converts an array of objects to a comma-separated values (CSV) string that contains only the `columns` specified.\n\n- Use `Array.prototype.join(delimiter)` to combine all the names in `columns` to create the first row.\n- Use `Array.prototype.map()` and `Array.prototype.reduce()` to create a row for each object. Substitute non-existent values with empty strings and only mapping values in `columns`.\n- Use `Array.prototype.join('\\n')` to combine all rows into a string.\n- Omit the third argument, `delimiter`, to use a default delimiter of `','`.", "example": "JSONtoCSV(\n [{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }],\n ['a', 'b']\n); // 'a,b\\n\"1\",\"2\"\\n\"3\",\"4\"\\n\"6\",\"\"\\n\"\",\"7\"'\nJSONtoCSV(\n [{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }],\n ['a', 'b'],\n ';'\n); // 'a;b\\n\"1\";\"2\"\\n\"3\";\"4\"\\n\"6\";\"\"\\n\"\";\"7\"'", "id": "JSONtoCSV", "tags": [ "array", "string", "object", "advanced" ] }, { "code": "const RGBToHSB = (r, g, b) => {\n r /= 255;\n g /= 255;\n b /= 255;\n const v = Math.max(r, g, b),\n n = v - Math.min(r, g, b);\n const h =\n n === 0 ? 0 : n && v === r ? (g - b) / n : v === g ? 2 + (b - r) / n : 4 + (r - g) / n;\n return [60 * (h < 0 ? h + 6 : h), v && (n / v) * 100, v * 100];\n};", "description": "Converts a RGB color tuple to HSB format.\n\n- Use the [RGB to HSB conversion formula](https://en.wikipedia.org/wiki/HSL_and_HSV#From_RGB) to convert to the appropriate format.\n- The range of all input parameters is [0, 255].\n- The range of the resulting values is H: [0, 360], S: [0, 100], B: [0, 100].", "example": "RGBToHSB(252, 111, 48);\n// [18.529411764705856, 80.95238095238095, 98.82352941176471]", "id": "RGBToHSB", "tags": [ "math", "intermediate" ] }, { "code": "const RGBToHSL = (r, g, b) => {\n r /= 255;\n g /= 255;\n b /= 255;\n const l = Math.max(r, g, b);\n const s = l - Math.min(r, g, b);\n const h = s\n ? l === r\n ? (g - b) / s\n : l === g\n ? 2 + (b - r) / s\n : 4 + (r - g) / s\n : 0;\n return [\n 60 * h < 0 ? 60 * h + 360 : 60 * h,\n 100 * (s ? (l <= 0.5 ? s / (2 * l - s) : s / (2 - (2 * l - s))) : 0),\n (100 * (2 * l - s)) / 2,\n ];\n};", "description": "Converts a RGB color tuple to HSL format.\n\n- Use the [RGB to HSL conversion formula](https://www.niwa.nu/2013/05/math-behind-colorspace-conversions-rgb-hsl/) to convert to the appropriate format.\n- The range of all input parameters is [0, 255].\n- The range of the resulting values is H: [0, 360], S: [0, 100], L: [0, 100].", "example": "RGBToHSL(45, 23, 11); // [21.17647, 60.71428, 10.98039]", "id": "RGBToHSL", "tags": [ "math", "intermediate" ] }, { "code": "const RGBToHex = (r, g, b) =>\n ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');", "description": "Converts the values of RGB components to a hexadecimal color code.\n\n- Convert given RGB parameters to hexadecimal string using bitwise left-shift operator (`<<`) and `Number.prototype.toString(16)`.\n- Use `String.prototype.padStart(6, '0')` to get a 6-digit hexadecimal value.", "example": "RGBToHex(255, 165, 1); // 'ffa501'", "id": "RGBToHex", "tags": [ "string", "math", "intermediate" ] }, { "code": "const URLJoin = (...args) =>\n args\n .join('/')\n .replace(/[\\/]+/g, '/')\n .replace(/^(.+):\\//, '$1://')\n .replace(/^file:/, 'file:/')\n .replace(/\\/(\\?|&|#[^!])/g, '$1')\n .replace(/\\?/g, '&')\n .replace('&', '?');", "description": "Joins all given URL segments together, then normalizes the resulting URL.\n\n- Use `String.prototype.join('/')` to combine URL segments.\n- Use a series of `String.prototype.replace()` calls with various regexps to normalize the resulting URL (remove double slashes, add proper slashes for protocol, remove slashes before parameters, combine parameters with `'&'` and normalize first parameter delimiter).", "example": "URLJoin('http://www.google.com', 'a', '/b/cd', '?foo=123', '?bar=foo');\n// 'http://www.google.com/a/b/cd?foo=123&bar=foo'", "id": "URLJoin", "tags": [ "string", "regexp", "advanced" ] }, { "code": "const UUIDGeneratorBrowser = () =>\n ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>\n (\n c ^\n (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))\n ).toString(16)\n );", "description": "Generates a UUID in a browser.\n\n- Use `Crypto.getRandomValues()` to generate a UUID, compliant with [RFC4122](https://www.ietf.org/rfc/rfc4122.txt) version 4.\n- Use `Number.prototype.toString(16)` to convert it to a proper UUID.", "example": "UUIDGeneratorBrowser(); // '7982fcfe-5721-4632-bede-6000885be57d'", "id": "UUIDGeneratorBrowser", "tags": [ "browser", "random", "intermediate" ] }, { "code": "const crypto = require('crypto');\n\nconst UUIDGeneratorNode = () =>\n ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>\n (c ^ (crypto.randomBytes(1)[0] & (15 >> (c / 4)))).toString(16)\n );", "description": "Generates a UUID in Node.JS.\n\n- Use `crypto.randomBytes()` to generate a UUID, compliant with [RFC4122](https://www.ietf.org/rfc/rfc4122.txt) version 4.\n- Use `Number.prototype.toString(16)` to convert it to a proper UUID.", "example": "UUIDGeneratorNode(); // '79c7c136-60ee-40a2-beb2-856f1feabefc'", "id": "UUIDGeneratorNode", "tags": [ "node", "random", "intermediate" ] }, { "code": "const accumulate = (...nums) =>\n nums.reduce((acc, n) => [...acc, n + +acc.slice(-1)], []);", "description": "Creates an array of partial sums.\n\n- Use `Array.prototype.reduce()`, initialized with an empty array accumulator to iterate over `nums`.\n- Use `Array.prototype.slice(-1)`, the spread operator (`...`) and the unary `+` operator to add each value to the accumulator array containing the previous sums.", "example": "accumulate(1, 2, 3, 4); // [1, 3, 6, 10]\naccumulate(...[1, 2, 3, 4]); // [1, 3, 6, 10]", "id": "accumulate", "tags": [ "math", "array", "intermediate" ] }, { "code": "const addClass = (el, className) => el.classList.add(className);", "description": "Adds a class to an HTML element.\n\n- Use `Element.classList` and `DOMTokenList.add()` to add the specified class to the element.", "example": "addClass(document.querySelector('p'), 'special');\n// The paragraph will now have the 'special' class", "id": "addClass", "tags": [ "browser", "beginner" ] }, { "code": "const addDaysToDate = (date, n) => {\n const d = new Date(date);\n d.setDate(d.getDate() + n);\n return d.toISOString().split('T')[0];\n};", "description": "Calculates the date of `n` days from the given date, returning its string representation.\n\n- Use `new Date()` to create a date object from the first argument.\n- Use `Date.prototype.getDate()` and `Date.prototype.setDate()` to add `n` days to the given date.\n- Use `Date.prototype.toISOString()` to return a string in `yyyy-mm-dd` format.", "example": "addDaysToDate('2020-10-15', 10); // '2020-10-25'\naddDaysToDate('2020-10-15', -10); // '2020-10-05'", "id": "addDaysToDate", "tags": [ "date", "intermediate" ] }, { "code": "const addEventListenerAll = (targets, type, listener, options, useCapture) => {\n targets.forEach(target =>\n target.addEventListener(type, listener, options, useCapture)\n );\n};", "description": "Attaches an event listener to all the provided targets.\n\n- Use `Array.prototype.forEach()` and `EventTarget.addEventListener()` to attach the provided `listener` for the given event `type` to all `targets`.", "example": "addEventListenerAll(document.querySelectorAll('a'), 'click', () =>\n console.log('Clicked a link')\n);\n// Logs 'Clicked a link' whenever any anchor element is clicked", "id": "addEventListenerAll", "tags": [ "browser", "event", "intermediate" ] }, { "code": "const addMinutesToDate = (date, n) => {\n const d = new Date(date);\n d.setTime(d.getTime() + n * 60000);\n return d.toISOString().split('.')[0].replace('T',' ');\n};", "description": "Calculates the date of `n` minutes from the given date, returning its string representation.\n\n- Use `new Date()` to create a date object from the first argument.\n- Use `Date.prototype.getTime()` and `Date.prototype.setTime()` to add `n` minutes to the given date.\n- Use `Date.prototype.toISOString()`, `String.prototype.split()` and `String.prototype.replace()` to return a string in `yyyy-mm-dd HH:MM:SS` format.", "example": "addMinutesToDate('2020-10-19 12:00:00', 10); // '2020-10-19 12:10:00'\naddMinutesToDate('2020-10-19', -10); // '2020-10-18 23:50:00'", "id": "addMinutesToDate", "tags": [ "date", "intermediate" ] }, { "code": "const addMultipleListeners = (el, types, listener, options, useCapture) => {\n types.forEach(type =>\n el.addEventListener(type, listener, options, useCapture)\n );\n};", "description": "Adds multiple event listeners with the same handler to an element.\n\n- Use `Array.prototype.forEach()` and `EventTarget.addEventListener()` to add multiple event listeners with an assigned callback function to an element.", "example": "addMultipleListeners(\n document.querySelector('.my-element'),\n ['click', 'mousedown'],\n () => { console.log('hello!') }\n);", "id": "addMultipleListeners", "tags": [ "browser", "event", "intermediate" ] }, { "code": "const addStyles = (el, styles) => Object.assign(el.style, styles);", "description": "Adds the provided styles to the given element.\n\n- Use `Object.assign()` and `ElementCSSInlineStyle.style` to merge the provided `styles` object into the style of the given element.", "example": "addStyles(document.getElementById('my-element'), {\n background: 'red',\n color: '#ffff00',\n fontSize: '3rem'\n});", "id": "addStyles", "tags": [ "browser", "beginner" ] }, { "code": "const addWeekDays = (startDate, count) =>\n Array.from({ length: count }).reduce(date => {\n date = new Date(date.setDate(date.getDate() + 1));\n if (date.getDay() % 6 === 0)\n date = new Date(date.setDate(date.getDate() + (date.getDay() / 6 + 1)));\n return date;\n }, startDate);", "description": "Calculates the date after adding the given number of business days.\n\n- Use `Array.from()` to construct an array with `length` equal to the `count` of business days to be added.\n- Use `Array.prototype.reduce()` to iterate over the array, starting from `startDate` and incrementing, using `Date.prototype.getDate()` and `Date.prototype.setDate()`.\n- If the current `date` is on a weekend, update it again by adding either one day or two days to make it a weekday.\n- **NOTE:** Does not take official holidays into account.", "example": "addWeekDays(new Date('Oct 09, 2020'), 5); // 'Oct 16, 2020'\naddWeekDays(new Date('Oct 12, 2020'), 5); // 'Oct 19, 2020'", "id": "addWeekDays", "tags": [ "date", "intermediate" ] }, { "code": "const all = (arr, fn = Boolean) => arr.every(fn);", "description": "Checks if the provided predicate function returns `true` for all elements in a collection.\n\n- Use `Array.prototype.every()` to test if all elements in the collection return `true` based on `fn`.\n- Omit the second argument, `fn`, to use `Boolean` as a default.", "example": "all([4, 2, 3], x => x > 1); // true\nall([1, 2, 3]); // true", "id": "all", "tags": [ "array", "beginner" ] }, { "code": "const allEqual = arr => arr.every(val => val === arr[0]);", "description": "Checks if all elements in an array are equal.\n\n- Use `Array.prototype.every()` to check if all the elements of the array are the same as the first one.\n- Elements in the array are compared using the strict comparison operator, which does not account for `NaN` self-inequality.", "example": "allEqual([1, 2, 3, 4, 5, 6]); // false\nallEqual([1, 1, 1, 1]); // true", "id": "allEqual", "tags": [ "array", "beginner" ] }, { "code": "const allEqualBy = (arr, fn) => {\n const eql = fn(arr[0]);\n return arr.every(val => fn(val) === eql);\n};", "description": "Checks if all elements in an array are equal, based on the provided mapping function.\n\n- Apply `fn` to the first element of `arr`.\n- Use `Array.prototype.every()` to check if `fn` returns the same value for all elements in the array as it did for the first one.\n- Elements in the array are compared using the strict comparison operator, which does not account for `NaN` self-inequality.", "example": "allEqualBy([1.1, 1.2, 1.3], Math.round); // true\nallEqualBy([1.1, 1.3, 1.6], Math.round); // false", "id": "allEqualBy", "tags": [ "array", "intermediate" ] }, { "code": "const allUnique = arr => arr.length === new Set(arr).size;", "description": "Checks if all elements in an array are unique.\n\n- Create a new `Set` from the mapped values to keep only unique occurrences.\n- Use `Array.prototype.length` and `Set.prototype.size` to compare the length of the unique values to the original array.", "example": "allUnique([1, 2, 3, 4]); // true\nallUnique([1, 1, 2, 3]); // false", "id": "allUnique", "tags": [ "array", "beginner" ] }, { "code": "const allUniqueBy = (arr, fn) => arr.length === new Set(arr.map(fn)).size;", "description": "Checks if all elements in an array are unique, based on the provided mapping function.\n\n- Use `Array.prototype.map()` to apply `fn` to all elements in `arr`.\n- Create a new `Set` from the mapped values to keep only unique occurrences.\n- Use `Array.prototype.length` and `Set.prototype.size` to compare the length of the unique mapped values to the original array.", "example": "allUniqueBy([1.2, 2.4, 2.9], Math.round); // true\nallUniqueBy([1.2, 2.3, 2.4], Math.round); // false", "id": "allUniqueBy", "tags": [ "array", "intermediate" ] }, { "code": "const and = (a, b) => a && b;", "description": "Checks if both arguments are `true`.\n\n- Use the logical and (`&&`) operator on the two given values.", "example": "and(true, true); // true\nand(true, false); // false\nand(false, false); // false", "id": "and", "tags": [ "math", "logic", "beginner" ] }, { "code": "const any = (arr, fn = Boolean) => arr.some(fn);", "description": "Checks if the provided predicate function returns `true` for at least one element in a collection.\n\n- Use `Array.prototype.some()` to test if any elements in the collection return `true` based on `fn`.\n- Omit the second argument, `fn`, to use `Boolean` as a default.", "example": "any([0, 1, 2, 0], x => x >= 2); // true\nany([0, 0, 1, 0]); // true", "id": "any", "tags": [ "array", "beginner" ] }, { "code": "const aperture = (n, arr) =>\n n > arr.length\n ? []\n : arr.slice(n - 1).map((v, i) => arr.slice(i, i + n));", "description": "Creates an array of `n`-tuples of consecutive elements.\n\n- Use `Array.prototype.slice()` and `Array.prototype.map()` to create an array of appropriate length.\n- Populate the array with `n`-tuples of consecutive elements from `arr`.\n- If `n` is greater than the length of `arr`, return an empty array.", "example": "aperture(2, [1, 2, 3, 4]); // [[1, 2], [2, 3], [3, 4]]\naperture(3, [1, 2, 3, 4]); // [[1, 2, 3], [2, 3, 4]]\naperture(5, [1, 2, 3, 4]); // []", "id": "aperture", "tags": [ "array", "intermediate" ] }, { "code": "const approximatelyEqual = (v1, v2, epsilon = 0.001) =>\n Math.abs(v1 - v2) < epsilon;", "description": "Checks if two numbers are approximately equal to each other.\n\n- Use `Math.abs()` to compare the absolute difference of the two values to `epsilon`.\n- Omit the third argument, `epsilon`, to use a default value of `0.001`.", "example": "approximatelyEqual(Math.PI / 2.0, 1.5708); // true", "id": "approximatelyEqual", "tags": [ "math", "beginner" ] }, { "code": "const arithmeticProgression = (n, lim) =>\n Array.from({ length: Math.ceil(lim / n) }, (_, i) => (i + 1) * n );", "description": "Creates an array of numbers in the arithmetic progression, starting with the given positive integer and up to the specified limit.\n\n- Use `Array.from()` to create an array of the desired length, `lim/n`. Use a map function to fill it with the desired values in the given range.", "example": "arithmeticProgression(5, 25); // [5, 10, 15, 20, 25]", "id": "arithmeticProgression", "tags": [ "math", "algorithm", "beginner" ] }, { "code": "const arrayToCSV = (arr, delimiter = ',') =>\n arr\n .map(v =>\n v.map(x => (isNaN(x) ? \\`\"\\${x.replace(/\"/g, '\"\"')}\"\\` : x)).join(delimiter)\n )\n .join('\\n');", "description": "Converts a 2D array to a comma-separated values (CSV) string.\n\n- Use `Array.prototype.map()` and `Array.prototype.join(delimiter)` to combine individual 1D arrays (rows) into strings.\n- Use `Array.prototype.join('\\n')` to combine all rows into a CSV string, separating each row with a newline.\n- Omit the second argument, `delimiter`, to use a default delimiter of `,`.", "example": "arrayToCSV([['a', 'b'], ['c', 'd']]); // '\"a\",\"b\"\\n\"c\",\"d\"'\narrayToCSV([['a', 'b'], ['c', 'd']], ';'); // '\"a\";\"b\"\\n\"c\";\"d\"'\narrayToCSV([['a', '\"b\" great'], ['c', 3.1415]]);\n// '\"a\",\"\"\"b\"\" great\"\\n\"c\",3.1415'", "id": "arrayToCSV", "tags": [ "array", "string", "intermediate" ] }, { "code": "const arrayToHTMLList = (arr, listID) => \n document.querySelector(\\`#\\${listID}\\`).innerHTML += arr\n .map(item => \\`<li>\\${item}</li>\\`)\n .join('');", "description": "Converts the given array elements into `<li>` tags and appends them to the list of the given id.\n\n- Use `Array.prototype.map()` and `Document.querySelector()` to create a list of html tags.", "example": "arrayToHTMLList(['item 1', 'item 2'], 'myListID');", "id": "arrayToHTMLList", "tags": [ "browser", "array", "intermediate" ] }, { "code": "const ary = (fn, n) => (...args) => fn(...args.slice(0, n));", "description": "Creates a function that accepts up to `n` arguments, ignoring any additional arguments.\n\n- Call the provided function, `fn`, with up to `n` arguments, using `Array.prototype.slice(0, n)` and the spread operator (`...`).", "example": "const firstTwoMax = ary(Math.max, 2);\n[[2, 6, 'a'], [6, 4, 8], [10]].map(x => firstTwoMax(...x)); // [6, 6, 10]", "id": "ary", "tags": [ "function", "advanced" ] }, { "code": "const assertValidKeys = (obj, keys) =>\n Object.keys(obj).every(key => keys.includes(key));", "description": "Validates all keys in an object match the given `keys`.\n\n- Use `Object.keys()` to get the keys of the given object, `obj`.\n- Use `Array.prototype.every()` and `Array.prototype.includes()` to validate that each key in the object is specified in the `keys` array.", "example": "assertValidKeys({ id: 10, name: 'apple' }, ['id', 'name']); // true\nassertValidKeys({ id: 10, name: 'apple' }, ['id', 'type']); // false", "id": "assertValidKeys", "tags": [ "object", "intermediate" ] }, { "code": "const atob = str => Buffer.from(str, 'base64').toString('binary');", "description": "Decodes a string of data which has been encoded using base-64 encoding.\n\n- Create a `Buffer` for the given string with base-64 encoding and use `Buffer.toString('binary')` to return the decoded string.", "example": "atob('Zm9vYmFy'); // 'foobar'", "id": "atob", "tags": [ "node", "string", "beginner" ] }, { "code": "const attempt = (fn, ...args) => {\n try {\n return fn(...args);\n } catch (e) {\n return e instanceof Error ? e : new Error(e);\n }\n};", "description": "Attempts to invoke a function with the provided arguments, returning either the result or the caught error object.\n\n- Use a `try... catch` block to return either the result of the function or an appropriate error.\n- If the caught object is not an `Error`, use it to create a new `Error`.", "example": "var elements = attempt(function(selector) {\n return document.querySelectorAll(selector);\n}, '>_>');\nif (elements instanceof Error) elements = []; // elements = []", "id": "attempt", "tags": [ "function", "intermediate" ] }, { "code": "const average = (...nums) =>\n nums.reduce((acc, val) => acc + val, 0) / nums.length;", "description": "Calculates the average of two or more numbers.\n\n- Use `Array.prototype.reduce()` to add each value to an accumulator, initialized with a value of `0`.\n- Divide the resulting array by its length.", "example": "average(...[1, 2, 3]); // 2\naverage(1, 2, 3); // 2", "id": "average", "tags": [ "math", "array", "beginner" ] }, { "code": "const averageBy = (arr, fn) =>\n arr\n .map(typeof fn === 'function' ? fn : val => val[fn])\n .reduce((acc, val) => acc + val, 0) / arr.length;", "description": "Calculates the average of an array, after mapping each element to a value using the provided function.\n\n- Use `Array.prototype.map()` to map each element to the value returned by `fn`.\n- Use `Array.prototype.reduce()` to add each value to an accumulator, initialized with a value of `0`.\n- Divide the resulting array by its length.", "example": "averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 5\naverageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 5", "id": "averageBy", "tags": [ "math", "array", "intermediate" ] }, { "code": "const bifurcate = (arr, filter) =>\n arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [\n [],\n [],\n ]);", "description": "Splits values into two groups, based on the result of the given `filter` array. \n\n- Use `Array.prototype.reduce()` and `Array.prototype.push()` to add elements to groups, based on `filter`.\n- If `filter` has a truthy value for any element, add it to the first group, otherwise add it to the second group.", "example": "bifurcate(['beep', 'boop', 'foo', 'bar'], [true, true, false, true]);\n// [ ['beep', 'boop', 'bar'], ['foo'] ]", "id": "bifurcate", "tags": [ "array", "intermediate" ] }, { "code": "const bifurcateBy = (arr, fn) =>\n arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [\n [],\n [],\n ]);", "description": "Splits values into two groups, based on the result of the given filtering function. \n\n- Use `Array.prototype.reduce()` and `Array.prototype.push()` to add elements to groups, based on the value returned by `fn` for each element.\n- If `fn` returns a truthy value for any element, add it to the first group, otherwise add it to the second group.", "example": "bifurcateBy(['beep', 'boop', 'foo', 'bar'], x => x[0] === 'b');\n// [ ['beep', 'boop', 'bar'], ['foo'] ]", "id": "bifurcateBy", "tags": [ "array", "intermediate" ] }, { "code": "const binary = fn => (a, b) => fn(a, b);", "description": "Creates a function that accepts up to two arguments, ignoring any additional arguments.\n\n- Call the provided function, `fn`, with the first two arguments given.", "example": "['2', '1', '0'].map(binary(Math.max)); // [2, 1, 2]", "id": "binary", "tags": [ "function", "intermediate" ] }, { "code": "const binarySearch = (arr, item) => {\n let l = 0,\n r = arr.length - 1;\n while (l <= r) {\n const mid = Math.floor((l + r) / 2);\n const guess = arr[mid];\n if (guess === item) return mid;\n if (guess > item) r = mid - 1;\n else l = mid + 1;\n }\n return -1;\n};", "description": "Finds the index of a given element in a sorted array using the binary search algorithm.\n\n- Declare the left and right search boundaries, `l` and `r`, initialized to `0` and the `length` of the array respectively.\n- Use a `while` loop to repeatedly narrow down the search subarray, using `Math.floor()` to cut it in half.\n- Return the index of the element if found, otherwise return `-1`.\n- **Note:** Does not account for duplicate values in the array.", "example": "binarySearch([1, 2, 3, 4, 5], 1); // 0\nbinarySearch([1, 2, 3, 4, 5], 5); // 4\nbinarySearch([1, 2, 3, 4, 5], 6); // -1", "id": "binarySearch", "tags": [ "algorithm", "array", "beginner" ] }, { "code": "const bind = (fn, context, ...boundArgs) => (...args) =>\n fn.apply(context, [...boundArgs, ...args]);", "description": "Creates a function that invokes `fn` with a given context, optionally prepending any additional supplied parameters to the arguments.\n\n- Return a `function` that uses `Function.prototype.apply()` to apply the given `context` to `fn`.\n- Use the spread operator (`...`) to prepend any additional supplied parameters to the arguments.", "example": "function greet(greeting, punctuation) {\n return greeting + ' ' + this.user + punctuation;\n}\nconst freddy = { user: 'fred' };\nconst freddyBound = bind(greet, freddy);\nconsole.log(freddyBound('hi', '!')); // 'hi fred!'", "id": "bind", "tags": [ "function", "object", "advanced" ] }, { "code": "const bindAll = (obj, ...fns) =>\n fns.forEach(\n fn => (\n (f = obj[fn]),\n (obj[fn] = function() {\n return f.apply(obj);\n })\n )\n );", "description": "Binds methods of an object to the object itself, overwriting the existing method.\n\n- Use `Array.prototype.forEach()` to iterate over the given `fns`.\n- Return a function for each one, using `Function.prototype.apply()` to apply the given context (`obj`) to `fn`.", "example": "var view = {\n label: 'docs',\n click: function() {\n console.log('clicked ' + this.label);\n }\n};\nbindAll(view, 'click');\ndocument.body.addEventListener('click', view.click);\n// Log 'clicked docs' when clicked.", "id": "bindAll", "tags": [ "object", "function", "intermediate" ] }, { "code": "const bindKey = (context, fn, ...boundArgs) => (...args) =>\n context[fn].apply(context, [...boundArgs, ...args]);", "description": "Creates a function that invokes the method at a given key of an object, optionally prepending any additional supplied parameters to the arguments.\n\n- Return a `function` that uses `Function.prototype.apply()` to bind `context[fn]` to `context`.\n- Use the spread operator (`...`) to prepend any additional supplied parameters to the arguments.", "example": "const freddy = {\n user: 'fred',\n greet: function(greeting, punctuation) {\n return greeting + ' ' + this.user + punctuation;\n }\n};\nconst freddyBound = bindKey(freddy, 'greet');\nconsole.log(freddyBound('hi', '!')); // 'hi fred!'", "id": "bindKey", "tags": [ "function", "object", "advanced" ] }, { "code": "const binomialCoefficient = (n, k) => {\n if (Number.isNaN(n) || Number.isNaN(k)) return NaN;\n if (k < 0 || k > n) return 0;\n if (k === 0 || k === n) return 1;\n if (k === 1 || k === n - 1) return n;\n if (n - k < k) k = n - k;\n let res = n;\n for (let j = 2; j <= k; j++) res *= (n - j + 1) / j;\n return Math.round(res);\n};", "description": "Calculates the number of ways to choose `k` items from `n` items without repetition and without order.\n\n- Use `Number.isNaN()` to check if any of the two values is `NaN`.\n- Check if `k` is less than `0`, greater than or equal to `n`, equal to `1` or `n - 1` and return the appropriate result.\n- Check if `n - k` is less than `k` and switch their values accordingly.\n- Loop from `2` through `k` and calculate the binomial coefficient.\n- Use `Math.round()` to account for rounding errors in the calculation.", "example": "binomialCoefficient(8, 2); // 28", "id": "binomialCoefficient", "tags": [ "math", "algorithm", "beginner" ] }, { "code": "const both = (f, g) => (...args) => f(...args) && g(...args);", "description": "Checks if both of the given functions return `true` for a given set of arguments.\n\n- Use the logical and (`&&`) operator on the result of calling the two functions with the supplied `args`.", "example": "const isEven = num => num % 2 === 0;\nconst isPositive = num => num > 0;\nconst isPositiveEven = both(isEven, isPositive);\nisPositiveEven(4); // true\nisPositiveEven(-2); // false", "id": "both", "tags": [ "function", "logic", "beginner" ] }, { "code": "const bottomVisible = () =>\n document.documentElement.clientHeight + window.scrollY >=\n (document.documentElement.scrollHeight ||\n document.documentElement.clientHeight);", "description": "Checks if the bottom of the page is visible.\n\n- Use `scrollY`, `scrollHeight` and `clientHeight` to determine if the bottom of the page is visible.", "example": "bottomVisible(); // true", "id": "bottomVisible", "tags": [ "browser", "beginner" ] }, { "code": "const btoa = str => Buffer.from(str, 'binary').toString('base64');", "description": "Creates a base-64 encoded ASCII string from a String object in which each character in the string is treated as a byte of binary data.\n\n- Create a `Buffer` for the given string with binary encoding and use `Buffer.toString('base64')` to return the encoded string.", "example": "btoa('foobar'); // 'Zm9vYmFy'", "id": "btoa", "tags": [ "node", "string", "beginner" ] }, { "code": "const bubbleSort = arr => {\n let swapped = false;\n const a = [...arr];\n for (let i = 1; i < a.length; i++) {\n swapped = false;\n for (let j = 0; j < a.length - i; j++) {\n if (a[j + 1] < a[j]) {\n [a[j], a[j + 1]] = [a[j + 1], a[j]];\n swapped = true;\n }\n }\n if (!swapped) return a;\n }\n return a;\n};", "description": "Sorts an array of numbers, using the bubble sort algorithm.\n\n- Declare a variable, `swapped`, that indicates if any values were swapped during the current iteration.\n- Use the spread operator (`...`) to clone the original array, `arr`.\n- Use a `for` loop to iterate over the elements of the cloned array, terminating before the last element.\n- Use a nested `for` loop to iterate over the segment of the array between `0` and `i`, swapping any adjacent out of order elements and setting `swapped` to `true`.\n- If `swapped` is `false` after an iteration, no more changes are needed, so the cloned array is returned.", "example": "bubbleSort([2, 1, 4, 3]); // [1, 2, 3, 4]", "id": "bubbleSort", "tags": [ "algorithm", "array", "beginner" ] }, { "code": "const bucketSort = (arr, size = 5) => {\n const min = Math.min(...arr);\n const max = Math.max(...arr);\n const buckets = Array.from(\n { length: Math.floor((max - min) / size) + 1 },\n () => []\n );\n arr.forEach(val => {\n buckets[Math.floor((val - min) / size)].push(val);\n });\n return buckets.reduce((acc, b) => [...acc, ...b.sort((a, b) => a - b)], []);\n};", "description": "Sorts an array of numbers, using the bucket sort algorithm.\n\n- Use `Math.min(),` `Math.max()` and the spread operator (`...`) to find the minimum and maximum values of the given array.\n- Use `Array.from()` and `Math.floor()` to create the appropriate number of `buckets` (empty arrays).\n- Use `Array.prototype.forEach()` to populate each bucket with the appropriate elements from the array.\n- Use `Array.prototype.reduce()`, the spread operator (`...`) and `Array.prototype.sort()` to sort each bucket and append it to the result.", "example": "bucketSort([6, 3, 4, 1]); // [1, 3, 4, 6]", "id": "bucketSort", "tags": [ "algorithm", "array", "intermediate" ] }, { "code": "const byteSize = str => new Blob([str]).size;", "description": "Returns the length of a string in bytes.\n\n- Convert a given string to a [`Blob` Object](https://developer.mozilla.org/en-US/docs/Web/API/Blob).\n- Use `Blob.size` to get the length of the string in bytes.", "example": "byteSize('😀'); // 4\nbyteSize('Hello World'); // 11", "id": "byteSize", "tags": [ "string", "beginner" ] }, { "code": "const caesarCipher = (str, shift, decrypt = false) => {\n const s = decrypt ? (26 - shift) % 26 : shift;\n const n = s > 0 ? s : 26 + (s % 26);\n return [...str]\n .map((l, i) => {\n const c = str.charCodeAt(i);\n if (c >= 65 && c <= 90)\n return String.fromCharCode(((c - 65 + n) % 26) + 65);\n if (c >= 97 && c <= 122)\n return String.fromCharCode(((c - 97 + n) % 26) + 97);\n return l;\n })\n .join('');\n};", "description": "Encrypts or decrypts a given string using the Caesar cipher.\n\n- Use the modulo (`%`) operator and the ternary operator (`?`) to calculate the correct encryption/decryption key.\n- Use the spread operator (`...`) and `Array.prototype.map()` to iterate over the letters of the given string.\n- Use `String.prototype.charCodeAt()` and `String.fromCharCode()` to convert each letter appropriately, ignoring special characters, spaces etc.\n- Use `Array.prototype.join()` to combine all the letters into a string.\n- Pass `true` to the last parameter, `decrypt`, to decrypt an encrypted string.", "example": "caesarCipher('Hello World!', -3); // 'Ebiil Tloia!'\ncaesarCipher('Ebiil Tloia!', 23, true); // 'Hello World!'", "id": "caesarCipher", "tags": [ "algorithm", "string", "beginner" ] }, { "code": "const call = (key, ...args) => context => context[key](...args);", "description": "Given a key and a set of arguments, call them when given a context.\n\n- Use a closure to call `key` with `args` for the given `context`.", "example": "Promise.resolve([1, 2, 3])\n .then(call('map', x => 2 * x))\n .then(console.log); // [ 2, 4, 6 ]\nconst map = call.bind(null, 'map');\nPromise.resolve([1, 2, 3])\n .then(map(x => 2 * x))\n .then(console.log); // [ 2, 4, 6 ]", "id": "call", "tags": [ "function", "advanced" ] }, { "code": "const capitalize = ([first, ...rest], lowerRest = false) =>\n first.toUpperCase() +\n (lowerRest ? rest.join('').toLowerCase() : rest.join(''));", "description": "Capitalizes the first letter of a string.\n\n- Use array destructuring and `String.prototype.toUpperCase()` to capitalize the first letter of the string.\n- Use `Array.prototype.join('')` to combine the capitalized `first` with the `...rest` of the characters.\n- Omit the `lowerRest` argument to keep the rest of the string intact, or set it to `true` to convert to lowercase.", "example": "capitalize('fooBar'); // 'FooBar'\ncapitalize('fooBar', true); // 'Foobar'", "id": "capitalize", "tags": [ "string", "intermediate" ] }, { "code": "const capitalizeEveryWord = str =>\n str.replace(/\\b[a-z]/g, char => char.toUpperCase());", "description": "Capitalizes the first letter of every word in a string.\n\n- Use `String.prototype.replace()` to match the first character of each word and `String.prototype.toUpperCase()` to capitalize it.", "example": "capitalizeEveryWord('hello world!'); // 'Hello World!'", "id": "capitalizeEveryWord", "tags": [ "string", "regexp", "intermediate" ] }, { "code": "const cartesianProduct = (a, b) =>\n a.reduce((p, x) => [...p, ...b.map(y => [x, y])], []);", "description": "Calculates the cartesian product of two arrays.\n\n- Use `Array.prototype.reduce()`, `Array.prototype.map()` and the spread operator (`...`) to generate all possible element pairs from the two arrays.", "example": "cartesianProduct(['x', 'y'], [1, 2]);\n// [['x', 1], ['x', 2], ['y', 1], ['y', 2]]", "id": "cartesianProduct", "tags": [ "math", "array", "beginner" ] }, { "code": "const castArray = val => (Array.isArray(val) ? val : [val]);", "description": "Casts the provided value as an array if it's not one.\n\n- Use `Array.prototype.isArray()` to determine if `val` is an array and return it as-is or encapsulated in an array accordingly.", "example": "castArray('foo'); // ['foo']\ncastArray([1]); // [1]", "id": "castArray", "tags": [ "type", "array", "beginner" ] }, { "code": "const celsiusToFahrenheit = degrees => 1.8 * degrees + 32;", "description": "Converts Celsius to Fahrenheit.\n\n- Follow the conversion formula `F = 1.8 * C + 32`.", "example": "celsiusToFahrenheit(33); // 91.4", "id": "celsiusToFahrenheit", "tags": [ "math", "beginner" ] }, { "code": "const chainAsync = fns => {\n let curr = 0;\n const last = fns[fns.length - 1];\n const next = () => {\n const fn = fns[curr++];\n fn === last ? fn() : fn(next);\n };\n next();\n};", "description": "Chains asynchronous functions.\n\n- Loop through an array of functions containing asynchronous events, calling `next` when each asynchronous event has completed.", "example": "chainAsync([\n next => {\n console.log('0 seconds');\n setTimeout(next, 1000);\n },\n next => {\n console.log('1 second');\n setTimeout(next, 1000);\n },\n () => {\n console.log('2 second');\n }\n]);", "id": "chainAsync", "tags": [ "function", "intermediate" ] }, { "code": "const changeLightness = (delta, hslStr) => {\n const [hue, saturation, lightness] = hslStr.match(/\\d+/g).map(Number);\n\n const newLightness = Math.max(\n 0,\n Math.min(100, lightness + parseFloat(delta))\n );\n\n return \\`hsl(\\${hue}, \\${saturation}%, \\${newLightness}%)\\`;\n};", "description": "Changes the lightness value of an `hsl()` color string.\n\n- Use `String.prototype.match()` to get an array of 3 strings with the numeric values.\n- Use `Array.prototype.map()` in combination with `Number` to convert them into an array of numeric values.\n- Make sure the lightness is within the valid range (between `0` and `100`), using `Math.max()` and `Math.min()`.\n- Use a template literal to create a new `hsl()` string with the updated value.", "example": "changeLightness(10, 'hsl(330, 50%, 50%)'); // 'hsl(330, 50%, 60%)'\nchangeLightness(-10, 'hsl(330, 50%, 50%)'); // 'hsl(330, 50%, 40%)'", "id": "changeLightness", "tags": [ "string", "browser", "regexp", "intermediate" ] }, { "code": "const checkProp = (predicate, prop) => obj => !!predicate(obj[prop]);", "description": "Creates a function that will invoke a predicate function for the specified property on a given object.\n\n- Return a curried function, that will invoke `predicate` for the specified `prop` on `obj` and return a boolean.", "example": "const lengthIs4 = checkProp(l => l === 4, 'length');\nlengthIs4([]); // false\nlengthIs4([1, 2, 3, 4]); // true\nlengthIs4(new Set([1, 2, 3, 4])); // false (Set uses Size, not length)\n\nconst session = { user: {} };\nconst validUserSession = checkProp(u => u.active && !u.disabled, 'user');\n\nvalidUserSession(session); // false\n\nsession.user.active = true;\nvalidUserSession(session); // true\n\nconst noLength = checkProp(l => l === undefined, 'length');\nnoLength([]); // false\nnoLength({}); // true\nnoLength(new Set()); // true", "id": "checkProp", "tags": [ "function", "object", "intermediate" ] }, { "code": "const chunk = (arr, size) =>\n Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>\n arr.slice(i * size, i * size + size)\n );", "description": "Chunks an array into smaller arrays of a specified size.\n\n- Use `Array.from()` to create a new array, that fits the number of chunks that will be produced.\n- Use `Array.prototype.slice()` to map each element of the new array to a chunk the length of `size`.\n- If the original array can't be split evenly, the final chunk will contain the remaining elements.", "example": "chunk([1, 2, 3, 4, 5], 2); // [[1, 2], [3, 4], [5]]", "id": "chunk", "tags": [ "array", "intermediate" ] }, { "code": "const chunkIntoN = (arr, n) => {\n const size = Math.ceil(arr.length / n);\n return Array.from({ length: n }, (v, i) =>\n arr.slice(i * size, i * size + size)\n );\n}", "description": "Chunks an array into `n` smaller arrays.\n\n- Use `Math.ceil()` and `Array.prototype.length` to get the size of each chunk.\n- Use `Array.from()` to create a new array of size `n`.\n- Use `Array.prototype.slice()` to map each element of the new array to a chunk the length of `size`.\n- If the original array can't be split evenly, the final chunk will contain the remaining elements.", "example": "chunkIntoN([1, 2, 3, 4, 5, 6, 7], 4); // [[1, 2], [3, 4], [5, 6], [7]]", "id": "chunkIntoN", "tags": [ "array", "intermediate" ] }, { "code": "const chunkify = function* (itr, size) {\n let chunk = [];\n for (const v of itr) {\n chunk.push(v);\n if (chunk.length === size) {\n yield chunk;\n chunk = [];\n }\n }\n if (chunk.length) yield chunk;\n};", "description": "Chunks an iterable into smaller arrays of a specified size.\n\n- Use a `for...of` loop over the given iterable, using `Array.prototype.push()` to add each new value to the current `chunk`.\n- Use `Array.prototype.length` to check if the current `chunk` is of the desired `size` and `yield` the value if it is.\n- Finally, use `Array.prototype.length` to check the final `chunk` and `yield` it if it's non-empty.", "example": "const x = new Set([1, 2, 1, 3, 4, 1, 2, 5]);\n[...chunkify(x, 2)]; // [[1, 2], [3, 4], [5]]", "id": "chunkify", "tags": [ "function", "generator", "array", "advanced" ] }, { "code": "const clampNumber = (num, a, b) =>\n Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b));", "description": "Clamps `num` within the inclusive range specified by the boundary values `a` and `b`.\n\n- If `num` falls within the range, return `num`.\n- Otherwise, return the nearest number in the range.", "example": "clampNumber(2, 3, 5); // 3\nclampNumber(1, -1, -5); // -1", "id": "clampNumber", "tags": [ "math", "beginner" ] }, { "code": "const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags);", "description": "Clones a regular expression.\n\n- Use `new RegExp()`, `RegExp.prototype.source` and `RegExp.prototype.flags` to clone the given regular expression.", "example": "const regExp = /lorem ipsum/gi;\nconst regExp2 = cloneRegExp(regExp); // regExp !== regExp2", "id": "cloneRegExp", "tags": [ "type", "intermediate" ] }, { "code": "const coalesce = (...args) => args.find(v => ![undefined, null].includes(v));", "description": "Returns the first defined, non-null argument.\n\n- Use `Array.prototype.find()` and `Array.prototype.includes()` to find the first value that is not equal to `undefined` or `null`.", "example": "coalesce(null, undefined, '', NaN, 'Waldo'); // ''", "id": "coalesce", "tags": [ "type", "beginner" ] }, { "code": "const coalesceFactory = valid => (...args) => args.find(valid);", "description": "Customizes a coalesce function that returns the first argument which is true based on the given validator.\n\n- Use `Array.prototype.find()` to return the first argument that returns `true` from the provided argument validation function, `valid`.", "example": "const customCoalesce = coalesceFactory(\n v => ![null, undefined, '', NaN].includes(v)\n);\ncustomCoalesce(undefined, null, NaN, '', 'Waldo'); // 'Waldo'", "id": "coalesceFactory", "tags": [ "function", "type", "intermediate" ] }, { "code": "const collectInto = fn => (...args) => fn(args);", "description": "Changes a function that accepts an array into a variadic function.\n\n- Given a function, return a closure that collects all inputs into an array-accepting function.", "example": "const Pall = collectInto(Promise.all.bind(Promise));\nlet p1 = Promise.resolve(1);\nlet p2 = Promise.resolve(2);\nlet p3 = new Promise(resolve => setTimeout(resolve, 2000, 3));\nPall(p1, p2, p3).then(console.log); // [1, 2, 3] (after about 2 seconds)", "id": "collect