{ "data": [ { "id": "all", "title": "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.prototype.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.\n\n", "codeBlocks": { "es6": "const all = (arr, fn = Boolean) => arr.every(fn);", "es5": "var all = function all(arr) {\n var fn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Boolean;\n return arr.every(fn);\n};", "example": "all([4, 2, 3], x => x > 1); // true\nall([1, 2, 3]); // true" }, "tags": [ "array", "function", "beginner" ] }, "meta": { "hash": "ba8e5f17500d1e5428f4ca7fcc8095934a7ad3aa496b35465e8f7799f1715aaa", "firstSeen": "1518601575", "lastUpdated": "1565681352", "updateCount": 6, "authorCount": 4 } }, { "id": "allEqual", "title": "allEqual", "type": "snippet", "attributes": { "fileName": "allEqual.md", "text": "Check if all elements in an array are equal.\n\nUse `Array.prototype.every()` to check if all the elements of the array are the same as the first one.\nElements in the array are compared using the strict comparison operator, which does not account for `NaN` self-inequality.\n\n", "codeBlocks": { "es6": "const allEqual = arr => arr.every(val => val === arr[0]);", "es5": "var allEqual = function allEqual(arr) {\n return arr.every(function (val) {\n return val === arr[0];\n });\n};", "example": "allEqual([1, 2, 3, 4, 5, 6]); // false\nallEqual([1, 1, 1, 1]); // true" }, "tags": [ "array", "function", "beginner" ] }, "meta": { "hash": "bda519858588ad61c9200acbb4ea5ce66630eb2ed7ceda96d12518b772b986b9", "firstSeen": "1533243788", "lastUpdated": "1565681352", "updateCount": 6, "authorCount": 4 } }, { "id": "any", "title": "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.prototype.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.\n\n", "codeBlocks": { "es6": "const any = (arr, fn = Boolean) => arr.some(fn);", "es5": "var any = function any(arr) {\n var fn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Boolean;\n return arr.some(fn);\n};", "example": "any([0, 1, 2, 0], x => x >= 2); // true\nany([0, 0, 1, 0]); // true" }, "tags": [ "array", "function", "beginner" ] }, "meta": { "hash": "061b791456507197b9be0ff9b791b830fe0b550823868075bbe04962501f83a3", "firstSeen": "1518601575", "lastUpdated": "1565681352", "updateCount": 6, "authorCount": 4 } }, { "id": "approximatelyEqual", "title": "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`.\n\n", "codeBlocks": { "es6": "const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon;", "es5": "var approximatelyEqual = function approximatelyEqual(v1, v2) {\n var epsilon = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0.001;\n return Math.abs(v1 - v2) < epsilon;\n};", "example": "approximatelyEqual(Math.PI / 2.0, 1.5708); // true" }, "tags": [ "math", "beginner" ] }, "meta": { "hash": "805f11e2f230c3a6b7dc590fcee27b4083b2188b6f1d0a8afb93868891cdba22", "firstSeen": "1518605233", "lastUpdated": "1565681352", "updateCount": 4, "authorCount": 3 } }, { "id": "arrayToCSV", "title": "arrayToCSV", "type": "snippet", "attributes": { "fileName": "arrayToCSV.md", "text": "Converts a 2D array to a comma-separated values (CSV) string.\n\nUse `Array.prototype.map()` and `Array.prototype.join(delimiter)` to combine individual 1D arrays (rows) into strings.\nUse `Array.prototype.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 `,`.\n\n", "codeBlocks": { "es6": "const arrayToCSV = (arr, delimiter = ',') =>\n arr\n .map(v => v.map(x => (isNaN(x) ? `\"${x.replace(/\"/g, '\"\"')}\"` : x)).join(delimiter))\n .join('\\n');", "es5": "var arrayToCSV = function arrayToCSV(arr) {\n var delimiter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ',';\n return arr.map(function (v) {\n return v.map(function (x) {\n return isNaN(x) ? \"\\\"\".concat(x.replace(/\"/g, '\"\"'), \"\\\"\") : x;\n }).join(delimiter);\n }).join('\\n');\n};", "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]]); // '\"a\",\"\"\"b\"\" great\"\\n\"c\",3.1415'" }, "tags": [ "array", "string", "utility", "intermediate" ] }, "meta": { "hash": "aeabb3d1d2be2d44fd8a20da3b069fdd1a8ad963f27e3e1ae9f5e8b40a8908cb", "firstSeen": "1530120403", "lastUpdated": "1565681352", "updateCount": 11, "authorCount": 5 } }, { "id": "arrayToHtmlList", "title": "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.prototype.map()`, `document.querySelector()`, and an anonymous inner closure to create a list of html tags.\n\n", "codeBlocks": { "es6": "const arrayToHtmlList = (arr, listID) =>\n (el => (\n (el = document.querySelector('#' + listID)),\n (el.innerHTML += arr.map(item => `
  • ${item}
  • `).join(''))\n ))();", "es5": "var arrayToHtmlList = function arrayToHtmlList(arr, listID) {\n return function (el) {\n return el = document.querySelector('#' + listID), el.innerHTML += arr.map(function (item) {\n return \"
  • \".concat(item, \"
  • \");\n }).join('');\n }();\n};", "example": "arrayToHtmlList(['item 1', 'item 2'], 'myListID');" }, "tags": [ "browser", "array", "intermediate" ] }, "meta": { "hash": "9d7e2db4a98688ab199ed2f75242bbff40a6083cc3c0ef483ed679c5d3878239", "firstSeen": "1513706585", "lastUpdated": "1565681352", "updateCount": 16, "authorCount": 9 } }, { "id": "ary", "title": "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.prototype.slice(0, n)` and the spread operator (`...`).\n\n", "codeBlocks": { "es6": "const ary = (fn, n) => (...args) => fn(...args.slice(0, n));", "es5": "function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }\n\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance\"); }\n\nfunction _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === \"[object Arguments]\") return Array.from(iter); }\n\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }\n\nvar ary = function ary(fn, n) {\n return function () {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return fn.apply(void 0, _toConsumableArray(args.slice(0, n)));\n };\n};", "example": "const firstTwoMax = ary(Math.max, 2);\n[[2, 6, 'a'], [6, 4, 8], [10]].map(x => firstTwoMax(...x)); // [6, 6, 10]" }, "tags": [ "function", "intermediate" ] }, "meta": { "hash": "533ab7f8259624322b5911b076d8e6fcd08f2fd396e9e0bec85449fc42769d9b", "firstSeen": "1516795194", "lastUpdated": "1578902643", "updateCount": 7, "authorCount": 5 } }, { "id": "atob", "title": "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.\n\n", "codeBlocks": { "es6": "const atob = str => Buffer.from(str, 'base64').toString('binary');", "es5": "var atob = function atob(str) {\n return Buffer.from(str, 'base64').toString('binary');\n};", "example": "atob('Zm9vYmFy'); // 'foobar'" }, "tags": [ "node", "string", "utility", "beginner" ] }, "meta": { "hash": "32988360d63d6d62251314a88d3f4482ec3a265d67154a92a86d4140bd61c54b", "firstSeen": "1516218201", "lastUpdated": "1565681352", "updateCount": 4, "authorCount": 3 } }, { "id": "attempt", "title": "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.\n\n", "codeBlocks": { "es6": "const attempt = (fn, ...args) => {\n try {\n return fn(...args);\n } catch (e) {\n return e instanceof Error ? e : new Error(e);\n }\n};", "es5": "var attempt = function attempt(fn) {\n try {\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n\n return fn.apply(void 0, args);\n } catch (e) {\n return e instanceof Error ? e : new Error(e);\n }\n};", "example": "var elements = attempt(function(selector) {\n return document.querySelectorAll(selector);\n}, '>_>');\nif (elements instanceof Error) elements = []; // elements = []" }, "tags": [ "function", "intermediate" ] }, "meta": { "hash": "a511836ad4a5755d469af2e6a331cbcd85df14b6231bbed6a1b0fe44aee3d2cf", "firstSeen": "1517143480", "lastUpdated": "1565681352", "updateCount": 4, "authorCount": 3 } }, { "id": "average", "title": "average", "type": "snippet", "attributes": { "fileName": "average.md", "text": "Returns the average of two or more numbers.\n\nUse `Array.prototype.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array.\n\n", "codeBlocks": { "es6": "const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length;", "es5": "var average = function average() {\n for (var _len = arguments.length, nums = new Array(_len), _key = 0; _key < _len; _key++) {\n nums[_key] = arguments[_key];\n }\n\n return nums.reduce(function (acc, val) {\n return acc + val;\n }, 0) / nums.length;\n};", "example": "average(...[1, 2, 3]); // 2\naverage(1, 2, 3); // 2" }, "tags": [ "math", "array", "beginner" ] }, "meta": { "hash": "edf5c7f142e59e4467ca7142eaf0ac95957abcb0dad1d439484b2b70fe8be6d3", "firstSeen": "1514546989", "lastUpdated": "1565681352", "updateCount": 8, "authorCount": 6 } }, { "id": "averageBy", "title": "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.prototype.map()` to map each element to the value returned by `fn`, `Array.prototype.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array.\n\n", "codeBlocks": { "es6": "const averageBy = (arr, fn) =>\n arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) /\n arr.length;", "es5": "var averageBy = function averageBy(arr, fn) {\n return arr.map(typeof fn === 'function' ? fn : function (val) {\n return val[fn];\n }).reduce(function (acc, val) {\n return acc + val;\n }, 0) / arr.length;\n};", "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" }, "tags": [ "math", "array", "function", "intermediate" ] }, "meta": { "hash": "7aa2052a6196029116ef9f2f7dda69b7d17344c0acc659ffedf002024b38d8b7", "firstSeen": "1515666354", "lastUpdated": "1565681352", "updateCount": 7, "authorCount": 4 } }, { "id": "bifurcate", "title": "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.prototype.reduce()` and `Array.prototype.push()` to add elements to groups, based on `filter`.\n\n", "codeBlocks": { "es6": "const bifurcate = (arr, filter) =>\n arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]);", "es5": "var bifurcate = function bifurcate(arr, filter) {\n return arr.reduce(function (acc, val, i) {\n return acc[filter[i] ? 0 : 1].push(val), acc;\n }, [[], []]);\n};", "example": "bifurcate(['beep', 'boop', 'foo', 'bar'], [true, true, false, true]); // [ ['beep', 'boop', 'bar'], ['foo'] ]" }, "tags": [ "array", "intermediate" ] }, "meta": { "hash": "a801974915906c11a30deef1baa3994f44f548f1ca1cf599aede4bb730543ec6", "firstSeen": "1518603187", "lastUpdated": "1565681352", "updateCount": 5, "authorCount": 4 } }, { "id": "bifurcateBy", "title": "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.prototype.reduce()` and `Array.prototype.push()` to add elements to groups, based on the value returned by `fn` for each element.\n\n", "codeBlocks": { "es6": "const bifurcateBy = (arr, fn) =>\n arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]);", "es5": "var bifurcateBy = function bifurcateBy(arr, fn) {\n return arr.reduce(function (acc, val, i) {\n return acc[fn(val, i) ? 0 : 1].push(val), acc;\n }, [[], []]);\n};", "example": "bifurcateBy(['beep', 'boop', 'foo', 'bar'], x => x[0] === 'b'); // [ ['beep', 'boop', 'bar'], ['foo'] ]" }, "tags": [ "array", "function", "intermediate" ] }, "meta": { "hash": "db1b8580ab11b6ba05a7d47776b97d700c5a7e945ddc5ad9ca1f37e50f039b54", "firstSeen": "1518603187", "lastUpdated": "1565681352", "updateCount": 5, "authorCount": 4 } }, { "id": "bind", "title": "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.prototype.apply()` to apply the given `context` to `fn`.\nUse `Array.prototype.concat()` to prepend any additional supplied parameters to the arguments.\n\n", "codeBlocks": { "es6": "const bind = (fn, context, ...boundArgs) => (...args) => fn.apply(context, [...boundArgs, ...args]);", "es5": "var bind = function bind(fn, context) {\n for (var _len = arguments.length, boundArgs = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {\n boundArgs[_key - 2] = arguments[_key];\n }\n\n return function () {\n for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n args[_key2] = arguments[_key2];\n }\n\n return fn.apply(context, [].concat(boundArgs, args));\n };\n};", "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!'" }, "tags": [ "function", "object", "intermediate" ] }, "meta": { "hash": "d15851c4e6991e41014768c3f2dd28df71615e44180c732b67eed1d162ea4b95", "firstSeen": "1516796089", "lastUpdated": "1565681352", "updateCount": 6, "authorCount": 5 } }, { "id": "bindAll", "title": "bindAll", "type": "snippet", "attributes": { "fileName": "bindAll.md", "text": "Binds methods of an object to the object itself, overwriting the existing method.\n\nUse `Array.prototype.forEach()` to return a `function` that uses `Function.prototype.apply()` to apply the given context (`obj`) to `fn` for each function specified.\n\n", "codeBlocks": { "es6": "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 );", "es5": "var bindAll = function bindAll(obj) {\n for (var _len = arguments.length, fns = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n fns[_key - 1] = arguments[_key];\n }\n\n return fns.forEach(function (fn) {\n return f = obj[fn], obj[fn] = function () {\n return f.apply(obj);\n };\n });\n};", "example": "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", "intermediate" ] }, "meta": { "hash": "e159b77ba0bde0f38d339348b9a69b4702cf036abd767777507159aa75ce151b", "firstSeen": "1516968893", "lastUpdated": "1565681352", "updateCount": 9, "authorCount": 5 } }, { "id": "bindKey", "title": "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.prototype.apply()` to bind `context[fn]` to `context`.\nUse the spread operator (`...`) to prepend any additional supplied parameters to the arguments.\n\n", "codeBlocks": { "es6": "const bindKey = (context, fn, ...boundArgs) => (...args) =>\n context[fn].apply(context, [...boundArgs, ...args]);", "es5": "var bindKey = function bindKey(context, fn) {\n for (var _len = arguments.length, boundArgs = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {\n boundArgs[_key - 2] = arguments[_key];\n }\n\n return function () {\n for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n args[_key2] = arguments[_key2];\n }\n\n return context[fn].apply(context, [].concat(boundArgs, args));\n };\n};", "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!'" }, "tags": [ "function", "object", "intermediate" ] }, "meta": { "hash": "e854f774dd81cdb291fb57b276a61e5d7f7ab13a6aae490c89c0e00acde820b4", "firstSeen": "1516796563", "lastUpdated": "1565681352", "updateCount": 8, "authorCount": 5 } }, { "id": "binomialCoefficient", "title": "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.\n\n", "codeBlocks": { "es6": "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};", "es5": "var binomialCoefficient = function 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 var res = n;\n\n for (var j = 2; j <= k; j++) {\n res *= (n - j + 1) / j;\n }\n\n return Math.round(res);\n};", "example": "binomialCoefficient(8, 2); // 28" }, "tags": [ "math", "intermediate" ] }, "meta": { "hash": "0f36f6b8c7f803a55d8e888c8794cacba02db79c4d54043a8ddc71249c2f8a9f", "firstSeen": "1518604442", "lastUpdated": "1565681352", "updateCount": 3, "authorCount": 2 } }, { "id": "bottomVisible", "title": "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.\n\n", "codeBlocks": { "es6": "const bottomVisible = () =>\n document.documentElement.clientHeight + window.scrollY >=\n (document.documentElement.scrollHeight || document.documentElement.clientHeight);", "es5": "var bottomVisible = function bottomVisible() {\n return document.documentElement.clientHeight + window.scrollY >= (document.documentElement.scrollHeight || document.documentElement.clientHeight);\n};", "example": "bottomVisible(); // true" }, "tags": [ "browser", "intermediate" ] }, "meta": { "hash": "9c2b4a28ae4f39cc034dc75e98d2f405af6113541f796041f142b85e90e27800", "firstSeen": "1513526151", "lastUpdated": "1565681352", "updateCount": 8, "authorCount": 5 } }, { "id": "btoa", "title": "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.\n\n", "codeBlocks": { "es6": "const btoa = str => Buffer.from(str, 'binary').toString('base64');", "es5": "var btoa = function btoa(str) {\n return Buffer.from(str, 'binary').toString('base64');\n};", "example": "btoa('foobar'); // 'Zm9vYmFy'" }, "tags": [ "node", "string", "utility", "beginner" ] }, "meta": { "hash": "1c7836009987b8b1097b54a84c38144f6cb643477f08f00b1a37e274cf0c9f78", "firstSeen": "1516218201", "lastUpdated": "1565681352", "updateCount": 5, "authorCount": 3 } }, { "id": "byteSize", "title": "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`.\n\n", "codeBlocks": { "es6": "const byteSize = str => new Blob([str]).size;", "es5": "var byteSize = function byteSize(str) {\n return new Blob([str]).size;\n};", "example": "byteSize('😀'); // 4\nbyteSize('Hello World'); // 11" }, "tags": [ "string", "beginner" ] }, "meta": { "hash": "c347c3d7b5fdc40df6d480810318d1ba644a74719bda3708b3ee3290f0ff953f", "firstSeen": "1514550634", "lastUpdated": "1565681352", "updateCount": 8, "authorCount": 5 } }, { "id": "call", "title": "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.\n\nUse a closure to call a stored key with stored arguments.\n\n", "codeBlocks": { "es6": "const call = (key, ...args) => context => context[key](...args);", "es5": "var call = function call(key) {\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n\n return function (context) {\n return context[key].apply(context, args);\n };\n};", "example": "Promise.resolve([1, 2, 3])\r\n .then(call('map', x => 2 * x))\r\n .then(console.log); // [ 2, 4, 6 ]\r\nconst map = call.bind(null, 'map');\r\nPromise.resolve([1, 2, 3])\r\n .then(map(x => 2 * x))\r\n .then(console.log); // [ 2, 4, 6 ]" }, "tags": [ "function", "intermediate" ] }, "meta": { "hash": "8b606a9b76e65d602238eb487d504dda0f1fe8bba9166ae2accbc7984c8d6530", "firstSeen": "1513972470", "lastUpdated": "1578903585", "updateCount": 12, "authorCount": 6 } }, { "id": "capitalize", "title": "capitalize", "type": "snippet", "attributes": { "fileName": "capitalize.md", "text": "Capitalizes the first letter of a string.\n\nUse array destructuring and `String.prototype.toUpperCase()` to capitalize first letter, `...rest` to get array of characters after first letter and then `Array.prototype.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.\n\n", "codeBlocks": { "es6": "const capitalize = ([first, ...rest], lowerRest = false) =>\n first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join(''));", "es5": "function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest(); }\n\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance\"); }\n\nfunction _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === \"[object Arguments]\") return Array.from(iter); }\n\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n\nvar capitalize = function capitalize(_ref) {\n var _ref2 = _toArray(_ref),\n first = _ref2[0],\n rest = _ref2.slice(1);\n\n var lowerRest = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n return first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join(''));\n};", "example": "capitalize('fooBar'); // 'FooBar'\ncapitalize('fooBar', true); // 'Foobar'" }, "tags": [ "string", "array", "intermediate" ] }, "meta": { "hash": "0c94a28b30fdfe112c8981a86868917d24cc5ddd1c84212a29783cec2d3a5ab4", "firstSeen": "1513521691", "lastUpdated": "1565681352", "updateCount": 12, "authorCount": 6 } }, { "id": "capitalizeEveryWord", "title": "capitalizeEveryWord", "type": "snippet", "attributes": { "fileName": "capitalizeEveryWord.md", "text": "Capitalizes the first letter of every word in a string.\n\nUse `String.prototype.replace()` to match the first character of each word and `String.prototype.toUpperCase()` to capitalize it.\n\n", "codeBlocks": { "es6": "const capitalizeEveryWord = str => str.replace(/\\b[a-z]/g, char => char.toUpperCase());", "es5": "var capitalizeEveryWord = function capitalizeEveryWord(str) {\n return str.replace(/\\b[a-z]/g, function (_char) {\n return _char.toUpperCase();\n });\n};", "example": "capitalizeEveryWord('hello world!'); // 'Hello World!'" }, "tags": [ "string", "regexp", "intermediate" ] }, "meta": { "hash": "aaf38afdc8033b2070b0e29ddb380db8570bbed490c6f39f55ff95167cdded8e", "firstSeen": "1513526151", "lastUpdated": "1565681352", "updateCount": 8, "authorCount": 5 } }, { "id": "castArray", "title": "castArray", "type": "snippet", "attributes": { "fileName": "castArray.md", "text": "Casts the provided value as an array if it's not one.\n\nUse `Array.prototype.isArray()` to determine if `val` is an array and return it as-is or encapsulated in an array accordingly.\n\n", "codeBlocks": { "es6": "const castArray = val => (Array.isArray(val) ? val : [val]);", "es5": "var castArray = function castArray(val) {\n return Array.isArray(val) ? val : [val];\n};", "example": "castArray('foo'); // ['foo']\ncastArray([1]); // [1]" }, "tags": [ "utility", "array", "type", "beginner" ] }, "meta": { "hash": "307add91ea4d5c2a122256f799120f580ac235567523dddeeadd6500f1e81e94", "firstSeen": "1516733652", "lastUpdated": "1565681352", "updateCount": 5, "authorCount": 4 } }, { "id": "chainAsync", "title": "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.\n\n", "codeBlocks": { "es6": "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};", "es5": "var chainAsync = function chainAsync(fns) {\n var curr = 0;\n var last = fns[fns.length - 1];\n\n var next = function next() {\n var fn = fns[curr++];\n fn === last ? fn() : fn(next);\n };\n\n next();\n};", "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]);" }, "tags": [ "function", "intermediate" ] }, "meta": { "hash": "cd48981af62f6ba75694f796fc5537e6af53a58045465ebd52f8bdd1a1f892af", "firstSeen": "1513526151", "lastUpdated": "1565681352", "updateCount": 10, "authorCount": 6 } }, { "id": "checkProp", "title": "checkProp", "type": "snippet", "attributes": { "fileName": "checkProp.md", "text": "Given a `predicate` function and a `prop` string, this curried function will then take an `object` to inspect by calling the property and passing it to the predicate.\n\nSummon `prop` on `obj`, pass it to a provided `predicate` function and return a masked boolean.\n\n", "codeBlocks": { "es6": "const checkProp = (predicate, prop) => obj => !!predicate(obj[prop]);", "es5": "var checkProp = function checkProp(predicate, prop) {\n return function (obj) {\n return !!predicate(obj[prop]);\n };\n};", "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" }, "tags": [ "function", "object", "utility", "beginner" ] }, "meta": { "hash": "52eca7b91d4205abe619c672895a773fc7ed7c2e151fd37e83ceda54ee74ad71", "firstSeen": "1552787580", "lastUpdated": "1577784150", "updateCount": 77, "authorCount": 7 } }, { "id": "chunk", "title": "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.prototype.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.\n\n", "codeBlocks": { "es6": "const chunk = (arr, size) =>\n Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>\n arr.slice(i * size, i * size + size)\n );", "es5": "var chunk = function chunk(arr, size) {\n return Array.from({\n length: Math.ceil(arr.length / size)\n }, function (v, i) {\n return arr.slice(i * size, i * size + size);\n });\n};", "example": "chunk([1, 2, 3, 4, 5], 2); // [[1,2],[3,4],[5]]" }, "tags": [ "array", "intermediate" ] }, "meta": { "hash": "4af3783b8b490cdf70853b0a01780244556a18a7398f5bef123e4f39edbadebe", "firstSeen": "1513521691", "lastUpdated": "1565681352", "updateCount": 8, "authorCount": 5 } }, { "id": "clampNumber", "title": "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.\n\n", "codeBlocks": { "es6": "const clampNumber = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b));", "es5": "var clampNumber = function clampNumber(num, a, b) {\n return Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b));\n};", "example": "clampNumber(2, 3, 5); // 3\nclampNumber(1, -1, -5); // -1" }, "tags": [ "math", "beginner" ] }, "meta": { "hash": "32fc5181c38c6d5bb16ac7373b68ad971c6b3cff6b80aee8cb69c296d47d0607", "firstSeen": "1513790358", "lastUpdated": "1565681352", "updateCount": 13, "authorCount": 7 } }, { "id": "cloneRegExp", "title": "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.\n\n", "codeBlocks": { "es6": "const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags);", "es5": "var cloneRegExp = function cloneRegExp(regExp) {\n return new RegExp(regExp.source, regExp.flags);\n};", "example": "const regExp = /lorem ipsum/gi;\nconst regExp2 = cloneRegExp(regExp); // /lorem ipsum/gi" }, "tags": [ "utility", "regexp", "intermediate" ] }, "meta": { "hash": "3b7e9a506c229c792da093336574e3524cd1a8c794d18fc450f469f171ff83cf", "firstSeen": "1514828747", "lastUpdated": "1565681352", "updateCount": 3, "authorCount": 2 } }, { "id": "coalesce", "title": "coalesce", "type": "snippet", "attributes": { "fileName": "coalesce.md", "text": "Returns the first defined, non-null argument.\n\nUse `Array.prototype.find()` and `Array.prototype.includes()` to find the first value that is not equal to `undefined` or `null`.\n\n", "codeBlocks": { "es6": "const coalesce = (...args) => args.find(v => ![undefined, null].includes(v));", "es5": "var coalesce = function coalesce() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return args.find(function (v) {\n return ![undefined, null].includes(v);\n });\n};", "example": "coalesce(null, undefined, '', NaN, 'Waldo'); // ''" }, "tags": [ "utility", "beginner" ] }, "meta": { "hash": "7c0db11447039e7d9bce2ed420ca1f69671b25928d272596587192a84aa78e31", "firstSeen": "1513498135", "lastUpdated": "1583442418", "updateCount": 11, "authorCount": 6 } }, { "id": "coalesceFactory", "title": "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.prototype.find()` to return the first argument that returns `true` from the provided argument validation function.\n\n", "codeBlocks": { "es6": "const coalesceFactory = valid => (...args) => args.find(valid);", "es5": "var coalesceFactory = function coalesceFactory(valid) {\n return function () {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return args.find(valid);\n };\n};", "example": "const customCoalesce = coalesceFactory(_ => ![null, undefined, '', NaN].includes(_));\ncustomCoalesce(undefined, null, NaN, '', 'Waldo'); // \"Waldo\"" }, "tags": [ "utility", "intermediate" ] }, "meta": { "hash": "b85ec57d815ff34ba3906195440fce5d2ad9f33b64d7d96159c0e1125fee283c", "firstSeen": "1513592136", "lastUpdated": "1565681352", "updateCount": 6, "authorCount": 5 } }, { "id": "collectInto", "title": "collectInto", "type": "snippet", "attributes": { "fileName": "collectInto.md", "text": "Changes a function that accepts an array into a variadic function.\n\nGiven a function, return a closure that collects all inputs into an array-accepting function.\n\n", "codeBlocks": { "es6": "const collectInto = fn => (...args) => fn(args);", "es5": "var collectInto = function collectInto(fn) {\n return function () {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return fn(args);\n };\n};", "example": "const Pall = collectInto(Promise.all.bind(Promise));\r\nlet p1 = Promise.resolve(1);\r\nlet p2 = Promise.resolve(2);\r\nlet p3 = new Promise(resolve => setTimeout(resolve, 2000, 3));\r\nPall(p1, p2, p3).then(console.log); // [1, 2, 3] (after about 2 seconds)" }, "tags": [ "function", "array", "intermediate" ] }, "meta": { "hash": "cbf8e15f8c0f47c8e38f6f070ff90ac694aab206cc57ceef7e457d93d794e69c", "firstSeen": "1513912116", "lastUpdated": "1578903585", "updateCount": 14, "authorCount": 6 } }, { "id": "colorize", "title": "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.\n\n", "codeBlocks": { "es6": "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});", "es5": "var colorize = function colorize() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return {\n black: \"\\x1B[30m\".concat(args.join(' ')),\n red: \"\\x1B[31m\".concat(args.join(' ')),\n green: \"\\x1B[32m\".concat(args.join(' ')),\n yellow: \"\\x1B[33m\".concat(args.join(' ')),\n blue: \"\\x1B[34m\".concat(args.join(' ')),\n magenta: \"\\x1B[35m\".concat(args.join(' ')),\n cyan: \"\\x1B[36m\".concat(args.join(' ')),\n white: \"\\x1B[37m\".concat(args.join(' ')),\n bgBlack: \"\\x1B[40m\".concat(args.join(' '), \"\\x1B[0m\"),\n bgRed: \"\\x1B[41m\".concat(args.join(' '), \"\\x1B[0m\"),\n bgGreen: \"\\x1B[42m\".concat(args.join(' '), \"\\x1B[0m\"),\n bgYellow: \"\\x1B[43m\".concat(args.join(' '), \"\\x1B[0m\"),\n bgBlue: \"\\x1B[44m\".concat(args.join(' '), \"\\x1B[0m\"),\n bgMagenta: \"\\x1B[45m\".concat(args.join(' '), \"\\x1B[0m\"),\n bgCyan: \"\\x1B[46m\".concat(args.join(' '), \"\\x1B[0m\"),\n bgWhite: \"\\x1B[47m\".concat(args.join(' '), \"\\x1B[0m\")\n };\n};", "example": "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", "intermediate" ] }, "meta": { "hash": "1ce726b8cbc9f87ff8ff6d68e0678325523b1118fa038b97f53ddad9031dbe23", "firstSeen": "1515843419", "lastUpdated": "1565681352", "updateCount": 4, "authorCount": 3 } }, { "id": "compact", "title": "compact", "type": "snippet", "attributes": { "fileName": "compact.md", "text": "Removes falsy values from an array.\n\nUse `Array.prototype.filter()` to filter out falsy values (`false`, `null`, `0`, `\"\"`, `undefined`, and `NaN`).\n\n", "codeBlocks": { "es6": "const compact = arr => arr.filter(Boolean);", "es5": "var compact = function compact(arr) {\n return arr.filter(Boolean);\n};", "example": "compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); // [ 1, 2, 3, 'a', 's', 34 ]" }, "tags": [ "array", "beginner" ] }, "meta": { "hash": "fdd7fd5631e5c1b541eff445f3388488dc060d435e339d9c0f1f257d5733e2fe", "firstSeen": "1513232355", "lastUpdated": "1565681352", "updateCount": 13, "authorCount": 9 } }, { "id": "compactWhitespace", "title": "compactWhitespace", "type": "snippet", "attributes": { "fileName": "compactWhitespace.md", "text": "Returns a string with whitespaces compacted.\n\nUse `String.prototype.replace()` with a regular expression to replace all occurrences of 2 or more whitespace characters with a single space.\n\n", "codeBlocks": { "es6": "const compactWhitespace = str => str.replace(/\\s{2,}/g, ' ');", "es5": "var compactWhitespace = function compactWhitespace(str) {\n return str.replace(/\\s{2,}/g, ' ');\n};", "example": "compactWhitespace('Lorem Ipsum'); // 'Lorem Ipsum'\ncompactWhitespace('Lorem \\n Ipsum'); // 'Lorem Ipsum'" }, "tags": [ "string", "regexp", "beginner" ] }, "meta": { "hash": "7b6007e94c262a97cfab69ddb111d101103c095dbf2fd7680053d8733e6f2914", "firstSeen": "1544634693", "lastUpdated": "1565681352", "updateCount": 5, "authorCount": 4 } }, { "id": "compose", "title": "compose", "type": "snippet", "attributes": { "fileName": "compose.md", "text": "Performs right-to-left function composition.\n\nUse `Array.prototype.reduce()` to perform right-to-left function composition.\nThe last (rightmost) function can accept one or more arguments; the remaining functions must be unary.\n\n", "codeBlocks": { "es6": "const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)));", "es5": "var compose = function compose() {\n for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) {\n fns[_key] = arguments[_key];\n }\n\n return fns.reduce(function (f, g) {\n return function () {\n return f(g.apply(void 0, arguments));\n };\n });\n};", "example": "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", "intermediate" ] }, "meta": { "hash": "200b26d1e1016c56ba796665b94266e57127b6bcf23bb00b702df01676f95443", "firstSeen": "1513521691", "lastUpdated": "1565681352", "updateCount": 11, "authorCount": 6 } }, { "id": "composeRight", "title": "composeRight", "type": "snippet", "attributes": { "fileName": "composeRight.md", "text": "Performs left-to-right function composition.\n\nUse `Array.prototype.reduce()` to perform left-to-right function composition.\nThe first (leftmost) function can accept one or more arguments; the remaining functions must be unary.\n\n", "codeBlocks": { "es6": "const composeRight = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));", "es5": "var composeRight = function composeRight() {\n for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) {\n fns[_key] = arguments[_key];\n }\n\n return fns.reduce(function (f, g) {\n return function () {\n return g(f.apply(void 0, arguments));\n };\n });\n};", "example": "const add = (x, y) => x + y;\nconst square = x => x * x;\nconst addAndSquare = composeRight(add, square);\naddAndSquare(1, 2); // 9" }, "tags": [ "function", "intermediate" ] }, "meta": { "hash": "90b2780517322e1c847b7e7ae5325f1e69765eb22b72cf3472e1cd7d07f06347", "firstSeen": "1516738376", "lastUpdated": "1565681352", "updateCount": 5, "authorCount": 4 } }, { "id": "containsWhitespace", "title": "containsWhitespace", "type": "snippet", "attributes": { "fileName": "containsWhitespace.md", "text": "Returns `true` if the given string contains any whitespace characters, `false` otherwise.\n\nUse `RegExp.prototype.test()` with an appropriate regular expression to check if the given string contains any whitespace characters.\n\n", "codeBlocks": { "es6": "const containsWhitespace = str => /\\s/.test(str);", "es5": "var containsWhitespace = function containsWhitespace(str) {\n return /\\s/.test(str);\n};", "example": "containsWhitespace('lorem'); // false\ncontainsWhitespace('lorem ipsum'); // true" }, "tags": [ "string", "regexp", "beginner" ] }, "meta": { "hash": "47f23b75a3d6600f5eb67b2a8535e83b6467c5f63e6184c774ddaa2421f198a3", "firstSeen": "1585132633", "lastUpdated": "1585132633", "updateCount": 2, "authorCount": 2 } }, { "id": "converge", "title": "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.prototype.map()` and `Function.prototype.apply()` to apply each function to the given arguments.\nUse the spread operator (`...`) to call `coverger` with the results of all other functions.\n\n", "codeBlocks": { "es6": "const converge = (converger, fns) => (...args) => converger(...fns.map(fn => fn.apply(null, args)));", "es5": "function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }\n\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance\"); }\n\nfunction _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === \"[object Arguments]\") return Array.from(iter); }\n\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }\n\nvar converge = function converge(converger, fns) {\n return function () {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return converger.apply(void 0, _toConsumableArray(fns.map(function (fn) {\n return fn.apply(null, args);\n })));\n };\n};", "example": "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", "intermediate" ] }, "meta": { "hash": "37cf3e2c4a2b41cb94eab31680088761236be2fc817c2c4322a0f9f1a16ae475", "firstSeen": "1517998984", "lastUpdated": "1565681352", "updateCount": 5, "authorCount": 4 } }, { "id": "copyToClipboard", "title": "copyToClipboard", "type": "snippet", "attributes": { "fileName": "copyToClipboard.md", "text": "Copy a string to the clipboard. \nOnly works as a result of user action (i.e. inside a `click` event listener).\n\n⚠️ **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\nCreate a new `