{ "data": [ { "id": "all", "type": "snippet", "attributes": { "fileName": "all.md", "text": "Returns `true` if the provided predicate function returns `true` for all elements in a collection, `false` otherwise.\n\nUse `Array.every()` to test if all elements in the collection return `true` based on `fn`.\nOmit the second argument, `fn`, to use `Boolean` as a default.", "codeBlocks": [ "const all = (arr, fn = Boolean) => arr.every(fn);", "all([4, 2, 3], x => x > 1); // true\nall([1, 2, 3]); // true" ], "tags": [ "array", "function" ] }, "meta": { "archived": false, "hash": "8a036b5ffee127e5456d59e36f3c9abb24f1692f6a398b61c20ebacaae8380e4" } }, { "id": "any", "type": "snippet", "attributes": { "fileName": "any.md", "text": "Returns `true` if the provided predicate function returns `true` for at least one element in a collection, `false` otherwise.\n\nUse `Array.some()` to test if any elements in the collection return `true` based on `fn`.\nOmit the second argument, `fn`, to use `Boolean` as a default.", "codeBlocks": [ "const any = (arr, fn = Boolean) => arr.some(fn);", "any([0, 1, 2, 0], x => x >= 2); // true\nany([0, 0, 1, 0]); // true" ], "tags": [ "array", "function" ] }, "meta": { "archived": false, "hash": "15bee4484e96a2d052368ef9dd743819b30d8d883b52575bee65fdc194dc9e93" } }, { "id": "approximatelyEqual", "type": "snippet", "attributes": { "fileName": "approximatelyEqual.md", "text": "Checks if two numbers are approximately equal to each other.\n\nUse `Math.abs()` to compare the absolute difference of the two values to `epsilon`.\nOmit the third parameter, `epsilon`, to use a default value of `0.001`.", "codeBlocks": [ "const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon;", "approximatelyEqual(Math.PI / 2.0, 1.5708); // true" ], "tags": [ "math" ] }, "meta": { "archived": false, "hash": "4fa8b87ac30ec67afe40c80101a702986dd1e5cab3cd8b9653f1b7c8cbac7540" } }, { "id": "arrayToCSV", "type": "snippet", "attributes": { "fileName": "arrayToCSV.md", "text": "Converts a 2D array to a comma-separated values (CSV) string.\n\nUse `Array.map()` and `Array.join(delimiter)` to combine individual 1D arrays (rows) into strings.\nUse `Array.join('\\n')` to combine all rows into a CSV string, separating each row with a newline.\nOmit the second argument, `delimiter`, to use a default delimiter of `,`.", "codeBlocks": [ "const arrayToCSV = (arr, delimiter = ',') =>\n arr.map(v => v.map(x => `\"${x}\"`).join(delimiter)).join('\\n');", "arrayToCSV([['a', 'b'], ['c', 'd']]); // '\"a\",\"b\"\\n\"c\",\"d\"'\narrayToCSV([['a', 'b'], ['c', 'd']], ';'); // '\"a\";\"b\"\\n\"c\";\"d\"'" ], "tags": [ "array", "string", "utility" ] }, "meta": { "archived": false, "hash": "47f27df615f87cf59e53ae3a618249f8413dd9d9c8939296a8b8f3785697de3d" } }, { "id": "arrayToHtmlList", "type": "snippet", "attributes": { "fileName": "arrayToHtmlList.md", "text": "Converts the given array elements into `
  • ` tags and appends them to the list of the given id.\n\nUse `Array.map()`, `document.querySelector()`, and an anonymous inner closure to create a list of html tags.", "codeBlocks": [ "const arrayToHtmlList = (arr, listID) =>\n (el => (\n (el = document.querySelector('#' + listID)),\n (el.innerHTML += arr.map(item => `
  • ${item}
  • `).join(''))\n ))();", "arrayToHtmlList(['item 1', 'item 2'], 'myListID');" ], "tags": [ "browser", "array" ] }, "meta": { "archived": false, "hash": "71d7b2d9a38cff92cda899e1be04c7995f097781b48ef89e3f766e27d9272fa7" } }, { "id": "ary", "type": "snippet", "attributes": { "fileName": "ary.md", "text": "Creates a function that accepts up to `n` arguments, ignoring any additional arguments.\n\nCall the provided function, `fn`, with up to `n` arguments, using `Array.slice(0,n)` and the spread operator (`...`).", "codeBlocks": [ "const ary = (fn, n) => (...args) => fn(...args.slice(0, n));", "const firstTwoMax = ary(Math.max, 2);\n[[2, 6, 'a'], [8, 4, 6], [10]].map(x => firstTwoMax(...x)); // [6, 8, 10]" ], "tags": [ "adapter", "function" ] }, "meta": { "archived": false, "hash": "41109ef32647c55ece0a9dba06c840250979124e790c944d732683d27ac26f1f" } }, { "id": "atob", "type": "snippet", "attributes": { "fileName": "atob.md", "text": "Decodes a string of data which has been encoded using base-64 encoding.\n\nCreate a `Buffer` for the given string with base-64 encoding and use `Buffer.toString('binary')` to return the decoded string.", "codeBlocks": [ "const atob = str => new Buffer(str, 'base64').toString('binary');", "atob('Zm9vYmFy'); // 'foobar'" ], "tags": [ "node", "string", "utility" ] }, "meta": { "archived": false, "hash": "b0f4a972f1e217c5f558359fa17693140a8b97a04a48ec1261691f10fb0c2a3e" } }, { "id": "attempt", "type": "snippet", "attributes": { "fileName": "attempt.md", "text": "Attempts to invoke a function with the provided arguments, returning either the result or the caught error object.\n\nUse a `try... catch` block to return either the result of the function or an appropriate error.", "codeBlocks": [ "const attempt = (fn, ...args) => {\n try {\n return fn(...args);\n } catch (e) {\n return e instanceof Error ? e : new Error(e);\n }\n};", "var elements = attempt(function(selector) {\n return document.querySelectorAll(selector);\n}, '>_>');\nif (elements instanceof Error) elements = []; // elements = []" ], "tags": [ "function" ] }, "meta": { "archived": false, "hash": "ac8ac4dc2ac7d0e2de1cf9f6afff46350aa530a51275658e8b34072740d10b0f" } }, { "id": "average", "type": "snippet", "attributes": { "fileName": "average.md", "text": "Returns the average of two or more numbers.\n\nUse `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array.", "codeBlocks": [ "const average = (...nums) => [...nums].reduce((acc, val) => acc + val, 0) / nums.length;", "average(...[1, 2, 3]); // 2\naverage(1, 2, 3); // 2" ], "tags": [ "math", "array" ] }, "meta": { "archived": false, "hash": "684bb67aac10990814a49d1d1878d98ec6d2161bd71f769a128e3195f9aeb632" } }, { "id": "averageBy", "type": "snippet", "attributes": { "fileName": "averageBy.md", "text": "Returns the average of an array, after mapping each element to a value using the provided function.\n\nUse `Array.map()` to map each element to the value returned by `fn`, `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array.", "codeBlocks": [ "const averageBy = (arr, fn) =>\n arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) /\n arr.length;", "averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 5\naverageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 5" ], "tags": [ "math", "array", "function" ] }, "meta": { "archived": false, "hash": "0ad10d648c24e0c27cfbb5cf65f18ad3fc7e072e6459c0bfc2d9936a0e497a03" } }, { "id": "bifurcate", "type": "snippet", "attributes": { "fileName": "bifurcate.md", "text": "Splits values into two groups. If an element in `filter` is truthy, the corresponding element in the collection belongs to the first group; otherwise, it belongs to the second group.\n\nUse `Array.reduce()` and `Array.push()` to add elements to groups, based on `filter`.", "codeBlocks": [ "const bifurcate = (arr, filter) =>\n arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]);", "bifurcate(['beep', 'boop', 'foo', 'bar'], [true, true, false, true]); // [ ['beep', 'boop', 'bar'], ['foo'] ]" ], "tags": [ "array" ] }, "meta": { "archived": false, "hash": "dd427f7304a3c161c95f9b1ae11f0adbe0d687076a5ed16ce2404ed29c136067" } }, { "id": "bifurcateBy", "type": "snippet", "attributes": { "fileName": "bifurcateBy.md", "text": "Splits values into two groups according to a predicate function, which specifies which group an element in the input collection belongs to. If the predicate function returns a truthy value, the collection element belongs to the first group; otherwise, it belongs to the second group.\n\nUse `Array.reduce()` and `Array.push()` to add elements to groups, based on the value returned by `fn` for each element.", "codeBlocks": [ "const bifurcateBy = (arr, fn) =>\n arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]);", "bifurcateBy(['beep', 'boop', 'foo', 'bar'], x => x[0] === 'b'); // [ ['beep', 'boop', 'bar'], ['foo'] ]" ], "tags": [ "array", "function" ] }, "meta": { "archived": false, "hash": "65534a8995d70358bf0faeb62cfa1e241147c8142e0bb62dd9015219cf367f9f" } }, { "id": "bind", "type": "snippet", "attributes": { "fileName": "bind.md", "text": "Creates a function that invokes `fn` with a given context, optionally adding any additional supplied parameters to the beginning of the arguments.\n\nReturn a `function` that uses `Function.apply()` to apply the given `context` to `fn`.\nUse `Array.concat()` to prepend any additional supplied parameters to the arguments.", "codeBlocks": [ "const bind = (fn, context, ...args) =>\n function() {\n return fn.apply(context, args.concat(...arguments));\n };", "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!'" ], "tags": [ "function", "object" ] }, "meta": { "archived": false, "hash": "e9d5d908df4751e5765b1e7d5a5f883261bdfad521b01023a81d616cac3b3cc1" } }, { "id": "bindAll", "type": "snippet", "attributes": { "fileName": "bindAll.md", "text": "Binds methods of an object to the object itself, overwriting the existing method.\n\nUse `Array.forEach()` to return a `function` that uses `Function.apply()` to apply the given context (`obj`) to `fn` for each function specified.", "codeBlocks": [ "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 );", "var view = {\n label: 'docs',\n click: function() {\n console.log('clicked ' + this.label);\n }\n};\nbindAll(view, 'click');\njQuery(element).on('click', view.click); // Logs 'clicked docs' when clicked." ], "tags": [ "object", "function" ] }, "meta": { "archived": false, "hash": "791096ce761f35096c86403c6bc290381982d7a9bfc9bda4b70270aaf6ec4df2" } }, { "id": "bindKey", "type": "snippet", "attributes": { "fileName": "bindKey.md", "text": "Creates a function that invokes the method at a given key of an object, optionally adding any additional supplied parameters to the beginning of the arguments.\n\nReturn a `function` that uses `Function.apply()` to bind `context[fn]` to `context`.\nUse `Array.concat()` to prepend any additional supplied parameters to the arguments.", "codeBlocks": [ "const bindKey = (context, fn, ...args) =>\n function() {\n return context[fn].apply(context, args.concat(...arguments));\n };", "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!'" ], "tags": [ "function", "object" ] }, "meta": { "archived": false, "hash": "561c7894f3ca7df0b3874ea749320b7d97eb3118c07c2636f4c4215377697927" } }, { "id": "binomialCoefficient", "type": "snippet", "attributes": { "fileName": "binomialCoefficient.md", "text": "Evaluates the binomial coefficient of two integers `n` and `k`.\n\nUse `Number.isNaN()` to check if any of the two values is `NaN`.\nCheck if `k` is less than `0`, greater than or equal to `n`, equal to `1` or `n - 1` and return the appropriate result.\nCheck if `n - k` is less than `k` and switch their values accordingly.\nLoop from `2` through `k` and calculate the binomial coefficient.\nUse `Math.round()` to account for rounding errors in the calculation.", "codeBlocks": [ "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};", "binomialCoefficient(8, 2); // 28" ], "tags": [ "math" ] }, "meta": { "archived": false, "hash": "0fca1b134c1a13fef45cde62e8f04c70361b477be88222aa7d81ac5d153b3a13" } }, { "id": "bottomVisible", "type": "snippet", "attributes": { "fileName": "bottomVisible.md", "text": "Returns `true` if the bottom of the page is visible, `false` otherwise.\n\nUse `scrollY`, `scrollHeight` and `clientHeight` to determine if the bottom of the page is visible.", "codeBlocks": [ "const bottomVisible = () =>\n document.documentElement.clientHeight + window.scrollY >=\n (document.documentElement.scrollHeight || document.documentElement.clientHeight);", "bottomVisible(); // true" ], "tags": [ "browser" ] }, "meta": { "archived": false, "hash": "a40dc0094d62d44e7d086513bca6afb74734dd1e5e56a0ce66e91517b459f50c" } }, { "id": "btoa", "type": "snippet", "attributes": { "fileName": "btoa.md", "text": "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\nCreate a `Buffer` for the given string with binary encoding and use `Buffer.toString('base64')` to return the encoded string.", "codeBlocks": [ "const btoa = str => new Buffer(str, 'binary').toString('base64');", "btoa('foobar'); // 'Zm9vYmFy'" ], "tags": [ "node", "string", "utility" ] }, "meta": { "archived": false, "hash": "ddbab0e7190004d5240469256d66629aa2fcf3c22348818edc01a8beb64831a6" } }, { "id": "byteSize", "type": "snippet", "attributes": { "fileName": "byteSize.md", "text": "Returns the length of a string in bytes.\n\nConvert a given string to a [`Blob` Object](https://developer.mozilla.org/en-US/docs/Web/API/Blob) and find its `size`.", "codeBlocks": [ "const byteSize = str => new Blob([str]).size;", "byteSize('😀'); // 4\nbyteSize('Hello World'); // 11" ], "tags": [ "string" ] }, "meta": { "archived": false, "hash": "5a7936489c66b541e2e1caf4254540a75557e049d1a10c7da0b38bd3b247f00b" } }, { "id": "call", "type": "snippet", "attributes": { "fileName": "call.md", "text": "Given a key and a set of arguments, call them when given a context. Primarily useful in composition.\r\n\r\nUse a closure to call a stored key with stored arguments.", "codeBlocks": [ "const call = (key, ...args) => context => context[key](...args);", "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 ]" ], "tags": [ "adapter", "function" ] }, "meta": { "archived": false, "hash": "732d63737f940a76c33a42ae3a1dcbf72b93149f57e14e34e301dad7ce245236" } }, { "id": "capitalize", "type": "snippet", "attributes": { "fileName": "capitalize.md", "text": "Capitalizes the first letter of a string.\n\nUse array destructuring and `String.toUpperCase()` to capitalize first letter, `...rest` to get array of characters after first letter and then `Array.join('')` to make it a string again.\nOmit the `lowerRest` parameter to keep the rest of the string intact, or set it to `true` to convert to lowercase.", "codeBlocks": [ "const capitalize = ([first, ...rest], lowerRest = false) =>\n first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join(''));", "capitalize('fooBar'); // 'FooBar'\ncapitalize('fooBar', true); // 'Foobar'" ], "tags": [ "string", "array" ] }, "meta": { "archived": false, "hash": "6f2f03a62a2b6f4a1a79d9864543d87297a1e2550ca5988d23b110fbc5c6a870" } }, { "id": "capitalizeEveryWord", "type": "snippet", "attributes": { "fileName": "capitalizeEveryWord.md", "text": "Capitalizes the first letter of every word in a string.\n\nUse `String.replace()` to match the first character of each word and `String.toUpperCase()` to capitalize it.", "codeBlocks": [ "const capitalizeEveryWord = str => str.replace(/\\b[a-z]/g, char => char.toUpperCase());", "capitalizeEveryWord('hello world!'); // 'Hello World!'" ], "tags": [ "string", "regexp" ] }, "meta": { "archived": false, "hash": "a5d1dd83d8cceafaa3d628655b8595942b549835f90e587202ef972c31e2ca3a" } }, { "id": "castArray", "type": "snippet", "attributes": { "fileName": "castArray.md", "text": "Casts the provided value as an array if it's not one.\n\nUse `Array.isArray()` to determine if `val` is an array and return it as-is or encapsulated in an array accordingly.", "codeBlocks": [ "const castArray = val => (Array.isArray(val) ? val : [val]);", "castArray('foo'); // ['foo']\ncastArray([1]); // [1]" ], "tags": [ "utility", "array", "type" ] }, "meta": { "archived": false, "hash": "b746ad19e2ea713891fb4c625a4c0cbaaad08e2189ecfbb1763ecaf8f2802ec7" } }, { "id": "chainAsync", "type": "snippet", "attributes": { "fileName": "chainAsync.md", "text": "Chains asynchronous functions.\n\nLoop through an array of functions containing asynchronous events, calling `next` when each asynchronous event has completed.", "codeBlocks": [ "const chainAsync = fns => {\n let curr = 0;\n const next = () => fns[curr++](next);\n next();\n};", "chainAsync([\n next => {\n console.log('0 seconds');\n setTimeout(next, 1000);\n },\n next => {\n console.log('1 second');\n }\n]);" ], "tags": [ "function" ] }, "meta": { "archived": false, "hash": "8c245a7fc94edffaf5cae4c28f37ed2e989772a9663a5f5bce98147f708a712e" } }, { "id": "chunk", "type": "snippet", "attributes": { "fileName": "chunk.md", "text": "Chunks an array into smaller arrays of a specified size.\n\nUse `Array.from()` to create a new array, that fits the number of chunks that will be produced.\nUse `Array.slice()` to map each element of the new array to a chunk the length of `size`.\nIf the original array can't be split evenly, the final chunk will contain the remaining elements.", "codeBlocks": [ "const chunk = (arr, size) =>\n Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>\n arr.slice(i * size, i * size + size)\n );", "chunk([1, 2, 3, 4, 5], 2); // [[1,2],[3,4],[5]]" ], "tags": [ "array" ] }, "meta": { "archived": false, "hash": "ae5220ae568a7482ee8f82b1af8816f5be99211ff99d7f290a0408d41ca58014" } }, { "id": "clampNumber", "type": "snippet", "attributes": { "fileName": "clampNumber.md", "text": "Clamps `num` within the inclusive range specified by the boundary values `a` and `b`.\n\nIf `num` falls within the range, return `num`.\nOtherwise, return the nearest number in the range.", "codeBlocks": [ "const clampNumber = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b));", "clampNumber(2, 3, 5); // 3\nclampNumber(1, -1, -5); // -1" ], "tags": [ "math" ] }, "meta": { "archived": false, "hash": "8e63c143d08d73cae1038ca8c6622ddf728b661528b246b55d6eb3b1ae41fe76" } }, { "id": "cloneRegExp", "type": "snippet", "attributes": { "fileName": "cloneRegExp.md", "text": "Clones a regular expression.\n\nUse `new RegExp()`, `RegExp.source` and `RegExp.flags` to clone the given regular expression.", "codeBlocks": [ "const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags);", "const regExp = /lorem ipsum/gi;\nconst regExp2 = cloneRegExp(regExp); // /lorem ipsum/gi" ], "tags": [ "utility", "regexp" ] }, "meta": { "archived": false, "hash": "57532d74214897181db46b09dc0be86d26e9877785ec85c3acd1113d5371fa95" } }, { "id": "coalesce", "type": "snippet", "attributes": { "fileName": "coalesce.md", "text": "Returns the first non-null/undefined argument.\n\nUse `Array.find()` to return the first non `null`/`undefined` argument.", "codeBlocks": [ "const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_));", "coalesce(null, undefined, '', NaN, 'Waldo'); // \"\"" ], "tags": [ "utility" ] }, "meta": { "archived": false, "hash": "9b2c0c5b8dda71c75580f5f7214e93fffddf6ac872f39206fe26793ab60403ce" } }, { "id": "coalesceFactory", "type": "snippet", "attributes": { "fileName": "coalesceFactory.md", "text": "Returns a customized coalesce function that returns the first argument that returns `true` from the provided argument validation function.\n\nUse `Array.find()` to return the first argument that returns `true` from the provided argument validation function.", "codeBlocks": [ "const coalesceFactory = valid => (...args) => args.find(valid);", "const customCoalesce = coalesceFactory(_ => ![null, undefined, '', NaN].includes(_));\ncustomCoalesce(undefined, null, NaN, '', 'Waldo'); // \"Waldo\"" ], "tags": [ "utility" ] }, "meta": { "archived": false, "hash": "3f2182bea1d9f17e2f315f6e8d72b3c31a42ff427e2a90d38fe50d6b86483f2e" } }, { "id": "collectInto", "type": "snippet", "attributes": { "fileName": "collectInto.md", "text": "Changes a function that accepts an array into a variadic function.\r\n\r\nGiven a function, return a closure that collects all inputs into an array-accepting function.", "codeBlocks": [ "const collectInto = fn => (...args) => fn(args);", "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)" ], "tags": [ "adapter", "function", "array" ] }, "meta": { "archived": false, "hash": "6b57cac68ad177d8fbb30e9c586f8f9c088acf755c6c956b5387441ea3850fce" } }, { "id": "colorize", "type": "snippet", "attributes": { "fileName": "colorize.md", "text": "Add special characters to text to print in color in the console (combined with `console.log()`).\n\nUse template literals and special characters to add the appropriate color code to the string output.\nFor background colors, add a special character that resets the background color at the end of the string.", "codeBlocks": [ "const colorize = (...args) => ({\n black: `\\x1b[30m${args.join(' ')}`,\n red: `\\x1b[31m${args.join(' ')}`,\n green: `\\x1b[32m${args.join(' ')}`,\n yellow: `\\x1b[33m${args.join(' ')}`,\n blue: `\\x1b[34m${args.join(' ')}`,\n magenta: `\\x1b[35m${args.join(' ')}`,\n cyan: `\\x1b[36m${args.join(' ')}`,\n white: `\\x1b[37m${args.join(' ')}`,\n bgBlack: `\\x1b[40m${args.join(' ')}\\x1b[0m`,\n bgRed: `\\x1b[41m${args.join(' ')}\\x1b[0m`,\n bgGreen: `\\x1b[42m${args.join(' ')}\\x1b[0m`,\n bgYellow: `\\x1b[43m${args.join(' ')}\\x1b[0m`,\n bgBlue: `\\x1b[44m${args.join(' ')}\\x1b[0m`,\n bgMagenta: `\\x1b[45m${args.join(' ')}\\x1b[0m`,\n bgCyan: `\\x1b[46m${args.join(' ')}\\x1b[0m`,\n bgWhite: `\\x1b[47m${args.join(' ')}\\x1b[0m`\n});", "console.log(colorize('foo').red); // 'foo' (red letters)\nconsole.log(colorize('foo', 'bar').bgBlue); // 'foo bar' (blue background)\nconsole.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)" ], "tags": [ "node", "utility", "string" ] }, "meta": { "archived": false, "hash": "30fc60a8ab8c8005f7d31b82f4386ba17caa9fed690916581b2c18fa0a125215" } }, { "id": "compact", "type": "snippet", "attributes": { "fileName": "compact.md", "text": "Removes falsey values from an array.\n\nUse `Array.filter()` to filter out falsey values (`false`, `null`, `0`, `\"\"`, `undefined`, and `NaN`).", "codeBlocks": [ "const compact = arr => arr.filter(Boolean);", "compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); // [ 1, 2, 3, 'a', 's', 34 ]" ], "tags": [ "array" ] }, "meta": { "archived": false, "hash": "2b349628df5c87359dfe7b113c4002212490693bb1dc1342f25775018764efd7" } }, { "id": "compose", "type": "snippet", "attributes": { "fileName": "compose.md", "text": "Performs right-to-left function composition.\n\nUse `Array.reduce()` to perform right-to-left function composition.\nThe last (rightmost) function can accept one or more arguments; the remaining functions must be unary.", "codeBlocks": [ "const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)));", "const add5 = x => x + 5;\nconst multiply = (x, y) => x * y;\nconst multiplyAndAdd5 = compose(\n add5,\n multiply\n);\nmultiplyAndAdd5(5, 2); // 15" ], "tags": [ "function" ] }, "meta": { "archived": false, "hash": "99383d2b505d6afcd239d6369ab28b319b0ea0b1bcf2cc9176ac5762516e4413" } }, { "id": "composeRight", "type": "snippet", "attributes": { "fileName": "composeRight.md", "text": "Performs left-to-right function composition.\n\nUse `Array.reduce()` to perform left-to-right function composition.\nThe first (leftmost) function can accept one or more arguments; the remaining functions must be unary.", "codeBlocks": [ "const composeRight = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));", "const add = (x, y) => x + y;\nconst square = x => x * x;\nconst addAndSquare = composeRight(add, square);\naddAndSquare(1, 2); // 9" ], "tags": [ "function" ] }, "meta": { "archived": false, "hash": "dd019505c88315f8744dd12bc7a66f5bd2aac07e2bbb3f6b3be100a1c1b96484" } }, { "id": "converge", "type": "snippet", "attributes": { "fileName": "converge.md", "text": "Accepts a converging function and a list of branching functions and returns a function that applies each branching function to the arguments and the results of the branching functions are passed as arguments to the converging function.\n\nUse `Array.map()` and `Function.apply()` to apply each function to the given arguments.\nUse the spread operator (`...`) to call `coverger` with the results of all other functions.", "codeBlocks": [ "const converge = (converger, fns) => (...args) => converger(...fns.map(fn => fn.apply(null, args)));", "const average = converge((a, b) => a / b, [\n arr => arr.reduce((a, v) => a + v, 0),\n arr => arr.length\n]);\naverage([1, 2, 3, 4, 5, 6, 7]); // 4" ], "tags": [ "function" ] }, "meta": { "archived": false, "hash": "12ac9307e4f8d368f6c1fa85caa9a16365fbbbd09ede026992155067f18b20f9" } }, { "id": "copyToClipboard", "type": "snippet", "attributes": { "fileName": "copyToClipboard.md", "text": "⚠️ **NOTICE:** The same functionality can be easily implemented by using the new asynchronous Clipboard API, which is still experimental but should be used in the future instead of this snippet. Find out more about it [here](https://github.com/w3c/clipboard-apis/blob/master/explainer.adoc#writing-to-the-clipboard).\n\nCopy a string to the clipboard. Only works as a result of user action (i.e. inside a `click` event listener).\n\nCreate a new `