{
  "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.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.",
        "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": {
        "archived": false,
        "hash": "2cf407f0e2df6eb320de1906d8cb4f1d252ac189af3a390dda264e8637a44e7e"
      }
    },
    {
      "id": "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.",
        "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": {
        "archived": false,
        "hash": "690147b9d4d90d37d9f42ec6596decc3e99eb8104f51d27a392ee3b50041878e"
      }
    },
    {
      "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.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.",
        "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": {
        "archived": false,
        "hash": "b045bd03ea755493fcab7b7092b0fb01bf8ce24b56e5605ea2d0bb037b91f11e"
      }
    },
    {
      "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": {
          "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": {
        "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.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 `,`.",
        "codeBlocks": {
          "es6": "const arrayToCSV = (arr, delimiter = ',') =>\n  arr.map(v => v.map(x => `\"${x}\"`).join(delimiter)).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 \"\\\"\".concat(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\"'"
        },
        "tags": [
          "array",
          "string",
          "utility",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "3508f9a15d8a0b0541d12373b8ea697773434fbfd946bb63fc4f0246e4f193ea"
      }
    },
    {
      "id": "arrayToHtmlList",
      "type": "snippet",
      "attributes": {
        "fileName": "arrayToHtmlList.md",
        "text": "Converts the given array elements into `<li>` 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.",
        "codeBlocks": {
          "es6": "const arrayToHtmlList = (arr, listID) =>\n  (el => (\n    (el = document.querySelector('#' + listID)),\n    (el.innerHTML += arr.map(item => `<li>${item}</li>`).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 \"<li>\".concat(item, \"</li>\");\n    }).join('');\n  }();\n};",
          "example": "arrayToHtmlList(['item 1', 'item 2'], 'myListID');"
        },
        "tags": [
          "browser",
          "array",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "ca7374613a03d90327f8754747ec14e3234f5df975cb8744da6ead6d7d3d2a83"
      }
    },
    {
      "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.prototype.slice(0,n)` and the spread operator (`...`).",
        "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'], [8, 4, 6], [10]].map(x => firstTwoMax(...x)); // [6, 8, 10]"
        },
        "tags": [
          "adapter",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "9c673d0dc5ea5d1b7c63506253c39e512127c377d349b2df1f847788e67bebf1"
      }
    },
    {
      "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": {
          "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": {
        "archived": false,
        "hash": "a1cdc6db4c91c17ea5f072fa38f40505a7500c1d142c33a9f7e8280fb9357fb5"
      }
    },
    {
      "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": {
          "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": {
        "archived": false,
        "hash": "ac8ac4dc2ac7d0e2de1cf9f6afff46350aa530a51275658e8b34072740d10b0f"
      }
    },
    {
      "id": "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.",
        "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": {
        "archived": false,
        "hash": "1275c6ed1d6ac5e1218831c45cdff88de135f803f45cdbb68dbbad0fbb55e967"
      }
    },
    {
      "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.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.",
        "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": {
        "archived": false,
        "hash": "58c2e46ed0bf8dfb7c3d36c280dff4a64ff056fc1a01b0972db8c81733d8c5dc"
      }
    },
    {
      "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.prototype.reduce()` and `Array.prototype.push()` to add elements to groups, based on `filter`.",
        "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": {
        "archived": false,
        "hash": "5f32ce21c3b3ef31d3281c0700eaca0761742fda556be7002596020947fd37a5"
      }
    },
    {
      "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.prototype.reduce()` and `Array.prototype.push()` to add elements to groups, based on the value returned by `fn` for each element.",
        "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": {
        "archived": false,
        "hash": "e09263bc0fa973e3e2435dfd61a764c0af080b73882f6c32b3534a5c4387fc43"
      }
    },
    {
      "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.prototype.apply()` to apply the given `context` to `fn`.\nUse `Array.prototype.concat()` to prepend any additional supplied parameters to the arguments.",
        "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, boundArgs.concat(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": {
        "archived": false,
        "hash": "8ffda25a0268a6f772c6912d370248c9329561c1ce1ea941e0622136459f7ef5"
      }
    },
    {
      "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.prototype.forEach()` to return a `function` that uses `Function.prototype.apply()` to apply the given context (`obj`) to `fn` for each function specified.",
        "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": {
        "archived": false,
        "hash": "3a8deee8bdc80c3df541ee5a9c31591af4c451362c2d86344ae4c937a04b2d12"
      }
    },
    {
      "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.prototype.apply()` to bind `context[fn]` to `context`.\nUse the spread operator (`...`) to prepend any additional supplied parameters to the arguments.",
        "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, boundArgs.concat(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": {
        "archived": false,
        "hash": "28b9b15af52a4abd2caaba94c5ceeea765ec89982122104cf5dc111c3f56383f"
      }
    },
    {
      "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": {
          "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": {
        "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": {
          "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": {
        "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": {
          "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": {
        "archived": false,
        "hash": "021ec24497f79ba1e18b01f1fc5a7498d21adbb4f556ac026afa817f10d46ae9"
      }
    },
    {
      "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": {
          "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": {
        "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": {
          "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])\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",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "302f71c01eddd94edd597dc50e9f76115c6117d9a06df54bf69813ef2728ba12"
      }
    },
    {
      "id": "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.",
        "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": {
        "archived": false,
        "hash": "b9e5abf13f56d58cb8d7abe800d90956a6b4d1954ac81b08f671ce994319dff6"
      }
    },
    {
      "id": "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.",
        "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": {
        "archived": false,
        "hash": "4ebf63ac48859f5011de39740d2650f7929257c9d1d468d1789e45f6a33b577e"
      }
    },
    {
      "id": "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.",
        "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": {
        "archived": false,
        "hash": "a6add43aea896ec237dfada48cfe67edab4b111e290472da8ff2c0ece70f2320"
      }
    },
    {
      "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": {
          "es6": "const chainAsync = fns => {\n  let curr = 0;\n  const next = () => fns[curr++](next);\n  next();\n};",
          "es5": "var chainAsync = function chainAsync(fns) {\n  var curr = 0;\n\n  var next = function next() {\n    return fns[curr++](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  }\n]);"
        },
        "tags": [
          "function",
          "intermediate"
        ]
      },
      "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.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.",
        "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": {
        "archived": false,
        "hash": "c9c64e0f8c0ec964e32434d873b28d0803a60737eceb19c67ab86edb3f352d48"
      }
    },
    {
      "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": {
          "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": {
        "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": {
          "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": {
        "archived": false,
        "hash": "57532d74214897181db46b09dc0be86d26e9877785ec85c3acd1113d5371fa95"
      }
    },
    {
      "id": "coalesce",
      "type": "snippet",
      "attributes": {
        "fileName": "coalesce.md",
        "text": "Returns the first non-null/undefined argument.\n\nUse `Array.prototype.find()` to return the first non `null`/`undefined` argument.",
        "codeBlocks": {
          "es6": "const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_));",
          "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 (_) {\n    return ![undefined, null].includes(_);\n  });\n};",
          "example": "coalesce(null, undefined, '', NaN, 'Waldo'); // \"\""
        },
        "tags": [
          "utility",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "3928d6f7c78cb72d1fe428be6bbdd5ee3ddcdb360b999d25048f84306e521918"
      }
    },
    {
      "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.prototype.find()` to return the first argument that returns `true` from the provided argument validation function.",
        "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": {
        "archived": false,
        "hash": "f6180d269df84f10e4642d5d52d442be990138b7114aef048f95eabd121c3738"
      }
    },
    {
      "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": {
          "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));\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",
          "intermediate"
        ]
      },
      "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": {
          "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": {
        "archived": false,
        "hash": "30fc60a8ab8c8005f7d31b82f4386ba17caa9fed690916581b2c18fa0a125215"
      }
    },
    {
      "id": "compact",
      "type": "snippet",
      "attributes": {
        "fileName": "compact.md",
        "text": "Removes falsey values from an array.\n\nUse `Array.prototype.filter()` to filter out falsey values (`false`, `null`, `0`, `\"\"`, `undefined`, and `NaN`).",
        "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": {
        "archived": false,
        "hash": "0f631b67b8460ed99917ff1468051e1e075ef02b280838ec14ad3fede2f48c7f"
      }
    },
    {
      "id": "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.",
        "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": {
        "archived": false,
        "hash": "6e9c4e34847a623fbf069fc1d64208178e9f992c7239bc80973512174a9242ff"
      }
    },
    {
      "id": "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.",
        "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": {
        "archived": false,
        "hash": "6e78bb3feef4d2fab6dbfced1c5f617869ea1c9f25b909d96dcfd7619df84aeb"
      }
    },
    {
      "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.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.",
        "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": {
        "archived": false,
        "hash": "5f363fa3bb93198f77488fc587bf8a124a04116348a81585d4b4a45b9fcb9989"
      }
    },
    {
      "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. \nOnly works as a result of user action (i.e. inside a `click` event listener).\n\nCreate a new `<textarea>` element, fill it with the supplied data and add it to the HTML document.\nUse `Selection.getRangeAt()`to store the selected range (if any).\nUse `document.execCommand('copy')` to copy to the clipboard.\nRemove the `<textarea>` element from the HTML document.\nFinally, use `Selection().addRange()` to recover the original selected range (if any).",
        "codeBlocks": {
          "es6": "const copyToClipboard = str => {\n  const el = document.createElement('textarea');\n  el.value = str;\n  el.setAttribute('readonly', '');\n  el.style.position = 'absolute';\n  el.style.left = '-9999px';\n  document.body.appendChild(el);\n  const selected =\n    document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;\n  el.select();\n  document.execCommand('copy');\n  document.body.removeChild(el);\n  if (selected) {\n    document.getSelection().removeAllRanges();\n    document.getSelection().addRange(selected);\n  }\n};",
          "es5": "var copyToClipboard = function copyToClipboard(str) {\n  var el = document.createElement('textarea');\n  el.value = str;\n  el.setAttribute('readonly', '');\n  el.style.position = 'absolute';\n  el.style.left = '-9999px';\n  document.body.appendChild(el);\n  var selected = document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;\n  el.select();\n  document.execCommand('copy');\n  document.body.removeChild(el);\n\n  if (selected) {\n    document.getSelection().removeAllRanges();\n    document.getSelection().addRange(selected);\n  }\n};",
          "example": "copyToClipboard('Lorem ipsum'); // 'Lorem ipsum' copied to clipboard."
        },
        "tags": [
          "browser",
          "string",
          "advanced"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "09ef1e582db77aa67e9f8741636876f27be2b39b67494bb46905181f570fa1aa"
      }
    },
    {
      "id": "countBy",
      "type": "snippet",
      "attributes": {
        "fileName": "countBy.md",
        "text": "Groups the elements of an array based on the given function and returns the count of elements in each group.\n\nUse `Array.prototype.map()` to map the values of an array to a function or property name.\nUse `Array.prototype.reduce()` to create an object, where the keys are produced from the mapped results.",
        "codeBlocks": {
          "es6": "const countBy = (arr, fn) =>\n  arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => {\n    acc[val] = (acc[val] || 0) + 1;\n    return acc;\n  }, {});",
          "es5": "var countBy = function countBy(arr, fn) {\n  return arr.map(typeof fn === 'function' ? fn : function (val) {\n    return val[fn];\n  }).reduce(function (acc, val) {\n    acc[val] = (acc[val] || 0) + 1;\n    return acc;\n  }, {});\n};",
          "example": "countBy([6.1, 4.2, 6.3], Math.floor); // {4: 1, 6: 2}\ncountBy(['one', 'two', 'three'], 'length'); // {3: 2, 5: 1}"
        },
        "tags": [
          "array",
          "object",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "cab7fc0cdd2b41758fb18e17986b0e3cc2b17a5ab79014530c9134a41ada9469"
      }
    },
    {
      "id": "counter",
      "type": "snippet",
      "attributes": {
        "fileName": "counter.md",
        "text": "Creates a counter with the specified range, step and duration for the specified selector.\n\nCheck if `step` has the proper sign and change it accordingly.\nUse `setInterval()` in combination with `Math.abs()` and `Math.floor()` to calculate the time between each new text draw.\nUse `document.querySelector().innerHTML` to update the value of the selected element.\nOmit the fourth parameter, `step`, to use a default step of `1`.\nOmit the fifth parameter, `duration`, to use a default duration of `2000`ms.",
        "codeBlocks": {
          "es6": "const counter = (selector, start, end, step = 1, duration = 2000) => {\n  let current = start,\n    _step = (end - start) * step < 0 ? -step : step,\n    timer = setInterval(() => {\n      current += _step;\n      document.querySelector(selector).innerHTML = current;\n      if (current >= end) document.querySelector(selector).innerHTML = end;\n      if (current >= end) clearInterval(timer);\n    }, Math.abs(Math.floor(duration / (end - start))));\n  return timer;\n};",
          "es5": "var counter = function counter(selector, start, end) {\n  var step = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1;\n  var duration = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 2000;\n\n  var current = start,\n      _step = (end - start) * step < 0 ? -step : step,\n      timer = setInterval(function () {\n    current += _step;\n    document.querySelector(selector).innerHTML = current;\n    if (current >= end) document.querySelector(selector).innerHTML = end;\n    if (current >= end) clearInterval(timer);\n  }, Math.abs(Math.floor(duration / (end - start))));\n\n  return timer;\n};",
          "example": "counter('#my-id', 1, 1000, 5, 2000); // Creates a 2-second timer for the element with id=\"my-id\""
        },
        "tags": [
          "browser",
          "advanced"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "5bf0c865aba5b748d185b9415c3b66ed61c77a0c5c052d44cfb745661f9a5802"
      }
    },
    {
      "id": "countOccurrences",
      "type": "snippet",
      "attributes": {
        "fileName": "countOccurrences.md",
        "text": "Counts the occurrences of a value in an array.\n\nUse `Array.prototype.reduce()` to increment a counter each time you encounter the specific value inside the array.",
        "codeBlocks": {
          "es6": "const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);",
          "es5": "var countOccurrences = function countOccurrences(arr, val) {\n  return arr.reduce(function (a, v) {\n    return v === val ? a + 1 : a;\n  }, 0);\n};",
          "example": "countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3"
        },
        "tags": [
          "array",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "f4471dcfb3a53fe8fd2f9e5566d5cf028aa69f4ddba69d6b5acd94c6e6aee133"
      }
    },
    {
      "id": "createElement",
      "type": "snippet",
      "attributes": {
        "fileName": "createElement.md",
        "text": "Creates an element from a string (without appending it to the document). \nIf the given string contains multiple elements, only the first one will be returned.\n\nUse `document.createElement()` to create a new element.\nSet its `innerHTML` to the string supplied as the argument. \nUse `ParentNode.firstElementChild` to return the element version of the string.",
        "codeBlocks": {
          "es6": "const createElement = str => {\n  const el = document.createElement('div');\n  el.innerHTML = str;\n  return el.firstElementChild;\n};",
          "es5": "var createElement = function createElement(str) {\n  var el = document.createElement('div');\n  el.innerHTML = str;\n  return el.firstElementChild;\n};",
          "example": "const el = createElement(\n  `<div class=\"container\">\n    <p>Hello!</p>\n  </div>`\n);\nconsole.log(el.className); // 'container'"
        },
        "tags": [
          "browser",
          "utility",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "90ce0d4ef6e6fece19d008d21e0201864dafbe48a62dbc7226f31f4b9c834090"
      }
    },
    {
      "id": "createEventHub",
      "type": "snippet",
      "attributes": {
        "fileName": "createEventHub.md",
        "text": "Creates a pub/sub ([publish–subscribe](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern)) event hub with `emit`, `on`, and `off` methods.\n\nUse `Object.create(null)` to create an empty `hub` object that does not inherit properties from `Object.prototype`.\nFor `emit`, resolve the array of handlers based on the `event` argument and then run each one with `Array.prototype.forEach()` by passing in the data as an argument.\nFor `on`, create an array for the event if it does not yet exist, then use `Array.prototype.push()` to add the handler\nto the array.\nFor `off`, use `Array.prototype.findIndex()` to find the index of the handler in the event array and remove it using `Array.prototype.splice()`.",
        "codeBlocks": {
          "es6": "const createEventHub = () => ({\n  hub: Object.create(null),\n  emit(event, data) {\n    (this.hub[event] || []).forEach(handler => handler(data));\n  },\n  on(event, handler) {\n    if (!this.hub[event]) this.hub[event] = [];\n    this.hub[event].push(handler);\n  },\n  off(event, handler) {\n    const i = (this.hub[event] || []).findIndex(h => h === handler);\n    if (i > -1) this.hub[event].splice(i, 1);\n  }\n});",
          "es5": "var createEventHub = function createEventHub() {\n  return {\n    hub: Object.create(null),\n    emit: function emit(event, data) {\n      (this.hub[event] || []).forEach(function (handler) {\n        return handler(data);\n      });\n    },\n    on: function on(event, handler) {\n      if (!this.hub[event]) this.hub[event] = [];\n      this.hub[event].push(handler);\n    },\n    off: function off(event, handler) {\n      var i = (this.hub[event] || []).findIndex(function (h) {\n        return h === handler;\n      });\n      if (i > -1) this.hub[event].splice(i, 1);\n    }\n  };\n};",
          "example": "const handler = data => console.log(data);\nconst hub = createEventHub();\nlet increment = 0;\n\n// Subscribe: listen for different types of events\nhub.on('message', handler);\nhub.on('message', () => console.log('Message event fired'));\nhub.on('increment', () => increment++);\n\n// Publish: emit events to invoke all handlers subscribed to them, passing the data to them as an argument\nhub.emit('message', 'hello world'); // logs 'hello world' and 'Message event fired'\nhub.emit('message', { hello: 'world' }); // logs the object and 'Message event fired'\nhub.emit('increment'); // `increment` variable is now 1\n\n// Unsubscribe: stop a specific handler from listening to the 'message' event\nhub.off('message', handler);"
        },
        "tags": [
          "browser",
          "event",
          "advanced"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "02438b83d413dbd5aede2eed7381f3038c4627135b63130ffdca48fdb6fbbc91"
      }
    },
    {
      "id": "CSVToArray",
      "type": "snippet",
      "attributes": {
        "fileName": "CSVToArray.md",
        "text": "Converts a comma-separated values (CSV) string to a 2D array.\n\nUse `Array.prototype.slice()` and `Array.prototype.indexOf('\\n')` to remove the first row (title row) if `omitFirstRow` is `true`.\nUse `String.prototype.split('\\n')` to create a string for each row, then `String.prototype.split(delimiter)` to separate the values in each row.\nOmit the second argument, `delimiter`, to use a default delimiter of `,`.\nOmit the third argument, `omitFirstRow`, to include the first row (title row) of the CSV string.",
        "codeBlocks": {
          "es6": "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));",
          "es5": "var CSVToArray = function CSVToArray(data) {\n  var delimiter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ',';\n  var omitFirstRow = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n  return data.slice(omitFirstRow ? data.indexOf('\\n') + 1 : 0).split('\\n').map(function (v) {\n    return v.split(delimiter);\n  });\n};",
          "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']];"
        },
        "tags": [
          "string",
          "array",
          "utility",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "c48af79621162e51752aaa5f4a672eda54d60de68cc8ba0b0f6df5cea73b1314"
      }
    },
    {
      "id": "CSVToJSON",
      "type": "snippet",
      "attributes": {
        "fileName": "CSVToJSON.md",
        "text": "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\nUse `Array.prototype.slice()` and `Array.prototype.indexOf('\\n')` and `String.prototype.split(delimiter)` to separate the first row (title row) into values.\nUse `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.\nUse `Array.prototype.reduce()` to create an object for each row's values, with the keys parsed from the title row.\nOmit the second argument, `delimiter`, to use a default delimiter of `,`.",
        "codeBlocks": {
          "es6": "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((obj, title, index) => ((obj[title] = values[index]), obj), {});\n    });\n};",
          "es5": "var CSVToJSON = function CSVToJSON(data) {\n  var delimiter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ',';\n  var titles = data.slice(0, data.indexOf('\\n')).split(delimiter);\n  return data.slice(data.indexOf('\\n') + 1).split('\\n').map(function (v) {\n    var values = v.split(delimiter);\n    return titles.reduce(function (obj, title, index) {\n      return obj[title] = values[index], obj;\n    }, {});\n  });\n};",
          "example": "CSVToJSON('col1,col2\\na,b\\nc,d'); // [{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}];\nCSVToJSON('col1;col2\\na;b\\nc;d', ';'); // [{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}];"
        },
        "tags": [
          "string",
          "array",
          "object",
          "advanced"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "5559217e1be7deb18edbfac311d772041fa7db09e1087551dcdfa945ef855f6a"
      }
    },
    {
      "id": "currentURL",
      "type": "snippet",
      "attributes": {
        "fileName": "currentURL.md",
        "text": "Returns the current URL.\n\nUse `window.location.href` to get current URL.",
        "codeBlocks": {
          "es6": "const currentURL = () => window.location.href;",
          "es5": "var currentURL = function currentURL() {\n  return window.location.href;\n};",
          "example": "currentURL(); // 'https://google.com'"
        },
        "tags": [
          "browser",
          "url",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "965397215e067e73b7c7bbd8f376f5773c79bb82f370747603647b01dee09a28"
      }
    },
    {
      "id": "curry",
      "type": "snippet",
      "attributes": {
        "fileName": "curry.md",
        "text": "Curries a function.\n\nUse recursion.\nIf the number of provided arguments (`args`) is sufficient, call the passed function `fn`.\nOtherwise, return a curried function `fn` that expects the rest of the arguments.\nIf you want to curry a function that accepts a variable number of arguments (a variadic function, e.g. `Math.min()`), you can optionally pass the number of arguments to the second parameter `arity`.",
        "codeBlocks": {
          "es6": "const curry = (fn, arity = fn.length, ...args) =>\n  arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args);",
          "es5": "var curry = function curry(fn) {\n  var arity = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : fn.length;\n\n  for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {\n    args[_key - 2] = arguments[_key];\n  }\n\n  return arity <= args.length ? fn.apply(void 0, args) : curry.bind.apply(curry, [null, fn, arity].concat(args));\n};",
          "example": "curry(Math.pow)(2)(10); // 1024\ncurry(Math.min, 3)(10)(50)(2); // 2"
        },
        "tags": [
          "function",
          "recursion",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "e3b0d5ff10d79034d6ccc448282097089b084ed71c608bc8f3468c0a8533ec14"
      }
    },
    {
      "id": "dayOfYear",
      "type": "snippet",
      "attributes": {
        "fileName": "dayOfYear.md",
        "text": "Gets the day of the year from a `Date` object.\n\nUse `new Date()` and `Date.prototype.getFullYear()` to get the first day of the year as a `Date` object, subtract it from the provided `date` and divide with the milliseconds in each day to get the result.\nUse `Math.floor()` to appropriately round the resulting day count to an integer.",
        "codeBlocks": {
          "es6": "const dayOfYear = date =>\n  Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);",
          "es5": "var dayOfYear = function dayOfYear(date) {\n  return Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);\n};",
          "example": "dayOfYear(new Date()); // 272"
        },
        "tags": [
          "date",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "389ee2f96db160f9ab0ed4aa38c69a1eebf93d785c8baf82afe0ee84c611a57d"
      }
    },
    {
      "id": "debounce",
      "type": "snippet",
      "attributes": {
        "fileName": "debounce.md",
        "text": "Creates a debounced function that delays invoking the provided function until at least `ms` milliseconds have elapsed since the last time it was invoked.\n\nEach time the debounced function is invoked, clear the current pending timeout with `clearTimeout()` and use `setTimeout()` to create a new timeout that delays invoking the function until at least `ms` milliseconds has elapsed. Use `Function.prototype.apply()` to apply the `this` context to the function and provide the necessary arguments.\nOmit the second argument, `ms`, to set the timeout at a default of 0 ms.",
        "codeBlocks": {
          "es6": "const debounce = (fn, ms = 0) => {\n  let timeoutId;\n  return function(...args) {\n    clearTimeout(timeoutId);\n    timeoutId = setTimeout(() => fn.apply(this, args), ms);\n  };\n};",
          "es5": "var debounce = function debounce(fn) {\n  var ms = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n  var timeoutId;\n  return function () {\n    var _this = this;\n\n    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n      args[_key] = arguments[_key];\n    }\n\n    clearTimeout(timeoutId);\n    timeoutId = setTimeout(function () {\n      return fn.apply(_this, args);\n    }, ms);\n  };\n};",
          "example": "window.addEventListener(\n  'resize',\n  debounce(() => {\n    console.log(window.innerWidth);\n    console.log(window.innerHeight);\n  }, 250)\n); // Will log the window dimensions at most every 250ms"
        },
        "tags": [
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "d7b9e0ff472527d78c9056a20a9cae4a9068874fb2ea10bbd6d3b6b66e13796d"
      }
    },
    {
      "id": "decapitalize",
      "type": "snippet",
      "attributes": {
        "fileName": "decapitalize.md",
        "text": "Decapitalizes the first letter of a string.\n\nUse array destructuring and `String.toLowerCase()` to decapitalize first letter, `...rest` to get array of characters after first letter and then `Array.prototype.join('')` to make it a string again.\nOmit the `upperRest` parameter to keep the rest of the string intact, or set it to `true` to convert to uppercase.",
        "codeBlocks": {
          "es6": "const decapitalize = ([first, ...rest], upperRest = false) =>\n  first.toLowerCase() + (upperRest ? rest.join('').toUpperCase() : 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 decapitalize = function decapitalize(_ref) {\n  var _ref2 = _toArray(_ref),\n      first = _ref2[0],\n      rest = _ref2.slice(1);\n\n  var upperRest = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n  return first.toLowerCase() + (upperRest ? rest.join('').toUpperCase() : rest.join(''));\n};",
          "example": "decapitalize('FooBar'); // 'fooBar'\ndecapitalize('FooBar', true); // 'fOOBAR'"
        },
        "tags": [
          "string",
          "array",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "9a23c1de52d2ddc6a014f5ed46a904921bc361eff91f51cfd4883ada4c4125a8"
      }
    },
    {
      "id": "deepClone",
      "type": "snippet",
      "attributes": {
        "fileName": "deepClone.md",
        "text": "Creates a deep clone of an object.\n\nUse recursion.\nUse `Object.assign()` and an empty object (`{}`) to create a shallow clone of the original.\nUse `Object.keys()` and `Array.prototype.forEach()` to determine which key-value pairs need to be deep cloned.",
        "codeBlocks": {
          "es6": "const deepClone = obj => {\n  let clone = Object.assign({}, obj);\n  Object.keys(clone).forEach(\n    key => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key])\n  );\n  return Array.isArray(obj) ? (clone.length = obj.length) && Array.from(clone) : clone;\n};",
          "es5": "function _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nvar deepClone = function deepClone(obj) {\n  var clone = Object.assign({}, obj);\n  Object.keys(clone).forEach(function (key) {\n    return clone[key] = _typeof(obj[key]) === 'object' ? deepClone(obj[key]) : obj[key];\n  });\n  return Array.isArray(obj) ? (clone.length = obj.length) && Array.from(clone) : clone;\n};",
          "example": "const a = { foo: 'bar', obj: { a: 1, b: 2 } };\nconst b = deepClone(a); // a !== b, a.obj !== b.obj"
        },
        "tags": [
          "object",
          "recursion",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "920453d0015cea2810cab4930a98143e76489460ef32d1478564c0db80a02f76"
      }
    },
    {
      "id": "deepFlatten",
      "type": "snippet",
      "attributes": {
        "fileName": "deepFlatten.md",
        "text": "Deep flattens an array.\n\nUse recursion.\nUse `Array.prototype.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array.\nRecursively flatten each element that is an array.",
        "codeBlocks": {
          "es6": "const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));",
          "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 deepFlatten = function deepFlatten(arr) {\n  var _ref;\n\n  return (_ref = []).concat.apply(_ref, _toConsumableArray(arr.map(function (v) {\n    return Array.isArray(v) ? deepFlatten(v) : v;\n  })));\n};",
          "example": "deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5]"
        },
        "tags": [
          "array",
          "recursion",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "701a5d546676f215b52c3386cde017ee68496827808e55dbeda1434ec0a2f79e"
      }
    },
    {
      "id": "deepFreeze",
      "type": "snippet",
      "attributes": {
        "fileName": "deepFreeze.md",
        "text": "Deep freezes an object.\n\nCalls `Object.freeze(obj)` recursively on all unfrozen properties of passed object that are `instanceof` object.",
        "codeBlocks": {
          "es6": "const deepFreeze = obj =>\n  Object.keys(obj).forEach(\n    prop =>\n      !(obj[prop] instanceof Object) || Object.isFrozen(obj[prop]) ? null : deepFreeze(obj[prop])\n  ) || Object.freeze(obj);",
          "es5": "var deepFreeze = function deepFreeze(obj) {\n  return Object.keys(obj).forEach(function (prop) {\n    return !(obj[prop] instanceof Object) || Object.isFrozen(obj[prop]) ? null : deepFreeze(obj[prop]);\n  }) || Object.freeze(obj);\n};",
          "example": "'use strict';\n\nconst o = deepFreeze([1, [2, 3]]);\n\no[0] = 3; // not allowed\no[1][0] = 4; // not allowed as well"
        },
        "tags": [
          "object",
          "recursion",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "9cf10fcda51ff8e1d130b0efa7971549a0d0bb4c24090c5766b82c12e9958604"
      }
    },
    {
      "id": "defaults",
      "type": "snippet",
      "attributes": {
        "fileName": "defaults.md",
        "text": "Assigns default values for all properties in an object that are `undefined`.\n\nUse `Object.assign()` to create a new empty object and copy the original one to maintain key order, use `Array.prototype.reverse()` and the spread operator `...` to combine the default values from left to right, finally use `obj` again to overwrite properties that originally had a value.",
        "codeBlocks": {
          "es6": "const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj);",
          "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 defaults = function defaults(obj) {\n  for (var _len = arguments.length, defs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n    defs[_key - 1] = arguments[_key];\n  }\n\n  return Object.assign.apply(Object, [{}, obj].concat(_toConsumableArray(defs.reverse()), [obj]));\n};",
          "example": "defaults({ a: 1 }, { b: 2 }, { b: 6 }, { a: 3 }); // { a: 1, b: 2 }"
        },
        "tags": [
          "object",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "3d09493a2600221b39194711824b21c9c3f7f04225fe91c913bbd16ed28f56cd"
      }
    },
    {
      "id": "defer",
      "type": "snippet",
      "attributes": {
        "fileName": "defer.md",
        "text": "Defers invoking a function until the current call stack has cleared.\n\nUse `setTimeout()` with a timeout of 1ms to add a new event to the browser event queue and allow the rendering engine to complete its work. Use the spread (`...`) operator to supply the function with an arbitrary number of arguments.",
        "codeBlocks": {
          "es6": "const defer = (fn, ...args) => setTimeout(fn, 1, ...args);",
          "es5": "var defer = function defer(fn) {\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 setTimeout.apply(void 0, [fn, 1].concat(args));\n};",
          "example": "// Example A:\ndefer(console.log, 'a'), console.log('b'); // logs 'b' then 'a'\n\n// Example B:\ndocument.querySelector('#someElement').innerHTML = 'Hello';\nlongRunningFunction(); // Browser will not update the HTML until this has finished\ndefer(longRunningFunction); // Browser will update the HTML then run the function"
        },
        "tags": [
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "a1ccac5c1c24abe79c129563811b536eb2cd5c27a533bd93d967afa54dcad550"
      }
    },
    {
      "id": "degreesToRads",
      "type": "snippet",
      "attributes": {
        "fileName": "degreesToRads.md",
        "text": "Converts an angle from degrees to radians.\n\nUse `Math.PI` and the degree to radian formula to convert the angle from degrees to radians.",
        "codeBlocks": {
          "es6": "const degreesToRads = deg => (deg * Math.PI) / 180.0;",
          "es5": "var degreesToRads = function degreesToRads(deg) {\n  return deg * Math.PI / 180.0;\n};",
          "example": "degreesToRads(90.0); // ~1.5708"
        },
        "tags": [
          "math",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "7f34bce958e51235318edc3a1fba0acf0fa110e533f3e92f87d27e74d7c1532b"
      }
    },
    {
      "id": "delay",
      "type": "snippet",
      "attributes": {
        "fileName": "delay.md",
        "text": "Invokes the provided function after `wait` milliseconds.\n\nUse `setTimeout()` to delay execution of `fn`.\nUse the spread (`...`) operator to supply the function with an arbitrary number of arguments.",
        "codeBlocks": {
          "es6": "const delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args);",
          "es5": "var delay = function delay(fn, wait) {\n  for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {\n    args[_key - 2] = arguments[_key];\n  }\n\n  return setTimeout.apply(void 0, [fn, wait].concat(args));\n};",
          "example": "delay(\n  function(text) {\n    console.log(text);\n  },\n  1000,\n  'later'\n); // Logs 'later' after one second."
        },
        "tags": [
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "818427da43b193ebf9f10dccd7399c405c437cc5d0040add0df40fd25e940218"
      }
    },
    {
      "id": "detectDeviceType",
      "type": "snippet",
      "attributes": {
        "fileName": "detectDeviceType.md",
        "text": "Detects wether the website is being opened in a mobile device or a desktop/laptop.\n\nUse a regular expression to test the `navigator.userAgent` property to figure out if the device is a mobile device or a desktop/laptop.",
        "codeBlocks": {
          "es6": "const detectDeviceType = () =>\n  /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)\n    ? 'Mobile'\n    : 'Desktop';",
          "es5": "var detectDeviceType = function detectDeviceType() {\n  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? 'Mobile' : 'Desktop';\n};",
          "example": "detectDeviceType(); // \"Mobile\" or \"Desktop\""
        },
        "tags": [
          "browser",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "2262275b7adcd7d9b2dd8f31da2a3a2dbcc663584928f46131a0d273b587403b"
      }
    },
    {
      "id": "difference",
      "type": "snippet",
      "attributes": {
        "fileName": "difference.md",
        "text": "Returns the difference between two arrays.\n\nCreate a `Set` from `b`, then use `Array.prototype.filter()` on `a` to only keep values not contained in `b`.",
        "codeBlocks": {
          "es6": "const difference = (a, b) => {\n  const s = new Set(b);\n  return a.filter(x => !s.has(x));\n};",
          "es5": "var difference = function difference(a, b) {\n  var s = new Set(b);\n  return a.filter(function (x) {\n    return !s.has(x);\n  });\n};",
          "example": "difference([1, 2, 3], [1, 2, 4]); // [3]"
        },
        "tags": [
          "array",
          "math",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "db6d2c9f6c8a2b2e4b4030dd1092603d4201df29530105359949b18029963b30"
      }
    },
    {
      "id": "differenceBy",
      "type": "snippet",
      "attributes": {
        "fileName": "differenceBy.md",
        "text": "Returns the difference between two arrays, after applying the provided function to each array element of both.\n\nCreate a `Set` by applying `fn` to each element in `b`, then use `Array.prototype.filter()` in combination with `fn` on `a` to only keep values not contained in the previously created set.",
        "codeBlocks": {
          "es6": "const differenceBy = (a, b, fn) => {\n  const s = new Set(b.map(fn));\n  return a.filter(x => !s.has(fn(x)));\n};",
          "es5": "var differenceBy = function differenceBy(a, b, fn) {\n  var s = new Set(b.map(fn));\n  return a.filter(function (x) {\n    return !s.has(fn(x));\n  });\n};",
          "example": "differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [1.2]\ndifferenceBy([{ x: 2 }, { x: 1 }], [{ x: 1 }], v => v.x); // [ { x: 2 } ]"
        },
        "tags": [
          "array",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "92abc752f5d3a659467e3dde7a3890000f4b72d1fdfd66086092494b688506ae"
      }
    },
    {
      "id": "differenceWith",
      "type": "snippet",
      "attributes": {
        "fileName": "differenceWith.md",
        "text": "Filters out all values from an array for which the comparator function does not return `true`.\n\nUse `Array.prototype.filter()` and `Array.prototype.findIndex()` to find the appropriate values.",
        "codeBlocks": {
          "es6": "const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1);",
          "es5": "var differenceWith = function differenceWith(arr, val, comp) {\n  return arr.filter(function (a) {\n    return val.findIndex(function (b) {\n      return comp(a, b);\n    }) === -1;\n  });\n};",
          "example": "differenceWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0], (a, b) => Math.round(a) === Math.round(b)); // [1, 1.2]"
        },
        "tags": [
          "array",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "197971487205f39337e5fe2bbf01566944a0bfe06347b5bbc7f21e32a67d37c4"
      }
    },
    {
      "id": "dig",
      "type": "snippet",
      "attributes": {
        "fileName": "dig.md",
        "text": "Returns the target value in a nested JSON object, based on the given key.\n\nUse the `in` operator to check if `target` exists in `obj`.\nIf found, return the value of `obj[target]`, otherwise use `Object.values(obj)` and `Array.prototype.reduce()` to recursively call `dig` on each nested object until the first matching key/value pair is found.",
        "codeBlocks": {
          "es6": "const dig = (obj, target) =>\n  target in obj\n    ? obj[target]\n    : Object.values(obj).reduce((acc, val) => {\n      if (acc !== undefined) return acc;\n      if (typeof val === 'object') return dig(val, target);\n    }, undefined);",
          "es5": "function _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nvar dig = function dig(obj, target) {\n  return target in obj ? obj[target] : Object.values(obj).reduce(function (acc, val) {\n    if (acc !== undefined) return acc;\n    if (_typeof(val) === 'object') return dig(val, target);\n  }, undefined);\n};",
          "example": "const data = {\n  level1: {\n    level2: {\n      level3: 'some data'\n    }\n  }\n};\ndig(data, 'level3'); // 'some data'\ndig(data, 'level4'); // undefined"
        },
        "tags": [
          "object",
          "recursion",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "828a6f2f3b94cc537ef0ee30c5ebda28fff688fea65030e47d5721831bdb48ce"
      }
    },
    {
      "id": "digitize",
      "type": "snippet",
      "attributes": {
        "fileName": "digitize.md",
        "text": "Converts a number to an array of digits.\n\nConvert the number to a string, using the spread operator (`...`) to build an array.\nUse `Array.prototype.map()` and `parseInt()` to transform each value to an integer.",
        "codeBlocks": {
          "es6": "const digitize = n => [...`${n}`].map(i => parseInt(i));",
          "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 digitize = function digitize(n) {\n  return _toConsumableArray(\"\".concat(n)).map(function (i) {\n    return parseInt(i);\n  });\n};",
          "example": "digitize(123); // [1, 2, 3]"
        },
        "tags": [
          "math",
          "array",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "306bfe9a8dc6fcedbf4dfa88b7bf2aac511556a1629ddb33f9e301c1e92b4321"
      }
    },
    {
      "id": "distance",
      "type": "snippet",
      "attributes": {
        "fileName": "distance.md",
        "text": "Returns the distance between two points.\n\nUse `Math.hypot()` to calculate the Euclidean distance between two points.",
        "codeBlocks": {
          "es6": "const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);",
          "es5": "var distance = function distance(x0, y0, x1, y1) {\n  return Math.hypot(x1 - x0, y1 - y0);\n};",
          "example": "distance(1, 1, 2, 3); // 2.23606797749979"
        },
        "tags": [
          "math",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "7023fa4063eaa53d06b0efd531455be981b3a14e6e0443cb9a04a639653103cc"
      }
    },
    {
      "id": "drop",
      "type": "snippet",
      "attributes": {
        "fileName": "drop.md",
        "text": "Returns a new array with `n` elements removed from the left.\n\nUse `Array.prototype.slice()` to slice the remove the specified number of elements from the left.",
        "codeBlocks": {
          "es6": "const drop = (arr, n = 1) => arr.slice(n);",
          "es5": "var drop = function drop(arr) {\n  var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;\n  return arr.slice(n);\n};",
          "example": "drop([1, 2, 3]); // [2,3]\ndrop([1, 2, 3], 2); // [3]\ndrop([1, 2, 3], 42); // []"
        },
        "tags": [
          "array",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "6ab35042dbb8b16be8ea108cf5029b34ac9fb166ca331ad2ed6a52188f5b0ba3"
      }
    },
    {
      "id": "dropRight",
      "type": "snippet",
      "attributes": {
        "fileName": "dropRight.md",
        "text": "Returns a new array with `n` elements removed from the right.\n\nUse `Array.prototype.slice()` to slice the remove the specified number of elements from the right.",
        "codeBlocks": {
          "es6": "const dropRight = (arr, n = 1) => arr.slice(0, -n);",
          "es5": "var dropRight = function dropRight(arr) {\n  var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;\n  return arr.slice(0, -n);\n};",
          "example": "dropRight([1, 2, 3]); // [1,2]\ndropRight([1, 2, 3], 2); // [1]\ndropRight([1, 2, 3], 42); // []"
        },
        "tags": [
          "array",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "421ed9a64e720bd3ba5969e067f94a3d0c3f515b9e8af5ed420a9bbce48d75cb"
      }
    },
    {
      "id": "dropRightWhile",
      "type": "snippet",
      "attributes": {
        "fileName": "dropRightWhile.md",
        "text": "Removes elements from the end of an array until the passed function returns `true`. Returns the remaining elements in the array.\n\nLoop through the array, using `Array.prototype.slice()` to drop the last element of the array until the returned value from the function is `true`.\nReturns the remaining elements.",
        "codeBlocks": {
          "es6": "const dropRightWhile = (arr, func) => {\n  while (arr.length > 0 && !func(arr[arr.length - 1])) arr = arr.slice(0, -1);\n  return arr;\n};",
          "es5": "var dropRightWhile = function dropRightWhile(arr, func) {\n  while (arr.length > 0 && !func(arr[arr.length - 1])) {\n    arr = arr.slice(0, -1);\n  }\n\n  return arr;\n};",
          "example": "dropRightWhile([1, 2, 3, 4], n => n < 3); // [1, 2]"
        },
        "tags": [
          "array",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "2ae245946d7c0d704aa1bbadf43afad388c09ac5dba409439b8ea79c1d4ad944"
      }
    },
    {
      "id": "dropWhile",
      "type": "snippet",
      "attributes": {
        "fileName": "dropWhile.md",
        "text": "Removes elements in an array until the passed function returns `true`. Returns the remaining elements in the array.\n\nLoop through the array, using `Array.prototype.slice()` to drop the first element of the array until the returned value from the function is `true`.\nReturns the remaining elements.",
        "codeBlocks": {
          "es6": "const dropWhile = (arr, func) => {\n  while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);\n  return arr;\n};",
          "es5": "var dropWhile = function dropWhile(arr, func) {\n  while (arr.length > 0 && !func(arr[0])) {\n    arr = arr.slice(1);\n  }\n\n  return arr;\n};",
          "example": "dropWhile([1, 2, 3, 4], n => n >= 3); // [3,4]"
        },
        "tags": [
          "array",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "17dd9d9ebf61759b170b90253df1d726e761adead262a1733a0192ba21cd15d1"
      }
    },
    {
      "id": "elementContains",
      "type": "snippet",
      "attributes": {
        "fileName": "elementContains.md",
        "text": "Returns `true` if the `parent` element contains the `child` element, `false` otherwise.\n\nCheck that `parent` is not the same element as `child`, use `parent.contains(child)` to check if the `parent` element contains the `child` element.",
        "codeBlocks": {
          "es6": "const elementContains = (parent, child) => parent !== child && parent.contains(child);",
          "es5": "var elementContains = function elementContains(parent, child) {\n  return parent !== child && parent.contains(child);\n};",
          "example": "elementContains(document.querySelector('head'), document.querySelector('title')); // true\nelementContains(document.querySelector('body'), document.querySelector('body')); // false"
        },
        "tags": [
          "browser",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "2f2c68c3368f5658fd54cb70b6264dce87ee68b23e805a95c62d55eef1854958"
      }
    },
    {
      "id": "elementIsVisibleInViewport",
      "type": "snippet",
      "attributes": {
        "fileName": "elementIsVisibleInViewport.md",
        "text": "Returns `true` if the element specified is visible in the viewport, `false` otherwise.\n\nUse `Element.getBoundingClientRect()` and the `window.inner(Width|Height)` values\nto determine if a given element is visible in the viewport.\nOmit the second argument to determine if the element is entirely visible, or specify `true` to determine if\nit is partially visible.",
        "codeBlocks": {
          "es6": "const elementIsVisibleInViewport = (el, partiallyVisible = false) => {\n  const { top, left, bottom, right } = el.getBoundingClientRect();\n  const { innerHeight, innerWidth } = window;\n  return partiallyVisible\n    ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&\n        ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))\n    : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;\n};",
          "es5": "var elementIsVisibleInViewport = function elementIsVisibleInViewport(el) {\n  var partiallyVisible = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n\n  var _el$getBoundingClient = el.getBoundingClientRect(),\n      top = _el$getBoundingClient.top,\n      left = _el$getBoundingClient.left,\n      bottom = _el$getBoundingClient.bottom,\n      right = _el$getBoundingClient.right;\n\n  var _window = window,\n      innerHeight = _window.innerHeight,\n      innerWidth = _window.innerWidth;\n  return partiallyVisible ? (top > 0 && top < innerHeight || bottom > 0 && bottom < innerHeight) && (left > 0 && left < innerWidth || right > 0 && right < innerWidth) : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;\n};",
          "example": "// e.g. 100x100 viewport and a 10x10px element at position {top: -1, left: 0, bottom: 9, right: 10}\nelementIsVisibleInViewport(el); // false - (not fully visible)\nelementIsVisibleInViewport(el, true); // true - (partially visible)"
        },
        "tags": [
          "browser",
          "advanced"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "d38bc0cd234c57cb95db1e60c47eb11a4d89775a4694acc520a8f113d03e3a39"
      }
    },
    {
      "id": "elo",
      "type": "snippet",
      "attributes": {
        "fileName": "elo.md",
        "text": "Computes the new ratings between two or more opponents using the [Elo rating system](https://en.wikipedia.org/wiki/Elo_rating_system). It takes an array\nof pre-ratings and returns an array containing post-ratings.\nThe array should be ordered from best performer to worst performer (winner -> loser).\n\nUse the exponent `**` operator and math operators to compute the expected score (chance of winning).\nof each opponent and compute the new rating for each.\nLoop through the ratings, using each permutation to compute the post-Elo rating for each player in a pairwise fashion. \nOmit the second argument to use the default `kFactor` of 32.",
        "codeBlocks": {
          "es6": "const elo = ([...ratings], kFactor = 32, selfRating) => {\n  const [a, b] = ratings;\n  const expectedScore = (self, opponent) => 1 / (1 + 10 ** ((opponent - self) / 400));\n  const newRating = (rating, i) =>\n    (selfRating || rating) + kFactor * (i - expectedScore(i ? a : b, i ? b : a));\n  if (ratings.length === 2) return [newRating(a, 1), newRating(b, 0)];\n\n  for (let i = 0, len = ratings.length; i < len; i++) {\n    let j = i;\n    while (j < len - 1) {\n      j++;\n      [ratings[i], ratings[j]] = elo([ratings[i], ratings[j]], kFactor);\n    }\n  }\n  return ratings;\n};",
          "es5": "function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }\n\nfunction _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i[\"return\"] != null) _i[\"return\"](); } finally { if (_d) throw _e; } } return _arr; }\n\nfunction _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 elo = function elo(_ref) {\n  var _ref2 = _toArray(_ref),\n      ratings = _ref2.slice(0);\n\n  var kFactor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 32;\n  var selfRating = arguments.length > 2 ? arguments[2] : undefined;\n\n  var _ratings = _slicedToArray(ratings, 2),\n      a = _ratings[0],\n      b = _ratings[1];\n\n  var expectedScore = function expectedScore(self, opponent) {\n    return 1 / (1 + Math.pow(10, (opponent - self) / 400));\n  };\n\n  var newRating = function newRating(rating, i) {\n    return (selfRating || rating) + kFactor * (i - expectedScore(i ? a : b, i ? b : a));\n  };\n\n  if (ratings.length === 2) return [newRating(a, 1), newRating(b, 0)];\n\n  for (var i = 0, len = ratings.length; i < len; i++) {\n    var j = i;\n\n    while (j < len - 1) {\n      j++;\n\n      var _elo = elo([ratings[i], ratings[j]], kFactor);\n\n      var _elo2 = _slicedToArray(_elo, 2);\n\n      ratings[i] = _elo2[0];\n      ratings[j] = _elo2[1];\n    }\n  }\n\n  return ratings;\n};",
          "example": "// Standard 1v1s\nelo([1200, 1200]); // [1216, 1184]\nelo([1200, 1200], 64); // [1232, 1168]\n// 4 player FFA, all same rank\nelo([1200, 1200, 1200, 1200]).map(Math.round); // [1246, 1215, 1185, 1154]\n/*\nFor teams, each rating can adjusted based on own team's average rating vs.\naverage rating of opposing team, with the score being added to their\nown individual rating by supplying it as the third argument.\n*/"
        },
        "tags": [
          "math",
          "array",
          "advanced"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "905993ba8666f6b76fb806f959dad3f043e875686885fdbf2b6b0a0a080d675c"
      }
    },
    {
      "id": "equals",
      "type": "snippet",
      "attributes": {
        "fileName": "equals.md",
        "text": "Performs a deep comparison between two values to determine if they are equivalent.\n\nCheck if the two values are identical, if they are both `Date` objects with the same time, using `Date.getTime()` or if they are both non-object values with an equivalent value (strict comparison).\nCheck if only one value is `null` or `undefined` or if their prototypes differ.\nIf none of the above conditions are met, use `Object.keys()` to check if both values have the same number of keys, then use `Array.prototype.every()` to check if every key in the first value exists in the second one and if they are equivalent by calling this method recursively.",
        "codeBlocks": {
          "es6": "const equals = (a, b) => {\n  if (a === b) return true;\n  if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();\n  if (!a || !b || (typeof a !== 'object' && typeof b !== 'object')) return a === b;\n  if (a === null || a === undefined || b === null || b === undefined) return false;\n  if (a.prototype !== b.prototype) return false;\n  let keys = Object.keys(a);\n  if (keys.length !== Object.keys(b).length) return false;\n  return keys.every(k => equals(a[k], b[k]));\n};",
          "es5": "function _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nvar equals = function equals(a, b) {\n  if (a === b) return true;\n  if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();\n  if (!a || !b || _typeof(a) !== 'object' && _typeof(b) !== 'object') return a === b;\n  if (a === null || a === undefined || b === null || b === undefined) return false;\n  if (a.prototype !== b.prototype) return false;\n  var keys = Object.keys(a);\n  if (keys.length !== Object.keys(b).length) return false;\n  return keys.every(function (k) {\n    return equals(a[k], b[k]);\n  });\n};",
          "example": "equals({ a: [2, { e: 3 }], b: [4], c: 'foo' }, { a: [2, { e: 3 }], b: [4], c: 'foo' }); // true"
        },
        "tags": [
          "object",
          "array",
          "type",
          "advanced"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "7e9e7d7f802e363947ecaf97defebf01225c8a38d6ca8a4c6584e9837db6ec24"
      }
    },
    {
      "id": "escapeHTML",
      "type": "snippet",
      "attributes": {
        "fileName": "escapeHTML.md",
        "text": "Escapes a string for use in HTML.\n\nUse `String.prototype.replace()` with a regexp that matches the characters that need to be escaped, using a callback function to replace each character instance with its associated escaped character using a dictionary (object).",
        "codeBlocks": {
          "es6": "const escapeHTML = str =>\n  str.replace(\n    /[&<>'\"]/g,\n    tag =>\n      ({\n        '&': '&amp;',\n        '<': '&lt;',\n        '>': '&gt;',\n        \"'\": '&#39;',\n        '\"': '&quot;'\n      }[tag] || tag)\n  );",
          "es5": "var escapeHTML = function escapeHTML(str) {\n  return str.replace(/[&<>'\"]/g, function (tag) {\n    return {\n      '&': '&amp;',\n      '<': '&lt;',\n      '>': '&gt;',\n      \"'\": '&#39;',\n      '\"': '&quot;'\n    }[tag] || tag;\n  });\n};",
          "example": "escapeHTML('<a href=\"#\">Me & you</a>'); // '&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;'"
        },
        "tags": [
          "string",
          "browser",
          "regexp",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "677770bd04bba27f729ea484bfdeff66cc5f0aea6562eb6ec49feaf9339a677c"
      }
    },
    {
      "id": "escapeRegExp",
      "type": "snippet",
      "attributes": {
        "fileName": "escapeRegExp.md",
        "text": "Escapes a string to use in a regular expression.\n\nUse `String.prototype.replace()` to escape special characters.",
        "codeBlocks": {
          "es6": "const escapeRegExp = str => str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');",
          "es5": "var escapeRegExp = function escapeRegExp(str) {\n  return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n};",
          "example": "escapeRegExp('(test)'); // \\\\(test\\\\)"
        },
        "tags": [
          "string",
          "regexp",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "824dc191c0c2cdc20738ba3b53ce77af5d25b3dc6662a78ff0d95609446a211e"
      }
    },
    {
      "id": "everyNth",
      "type": "snippet",
      "attributes": {
        "fileName": "everyNth.md",
        "text": "Returns every nth element in an array.\n\nUse `Array.prototype.filter()` to create a new array that contains every nth element of a given array.",
        "codeBlocks": {
          "es6": "const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);",
          "es5": "var everyNth = function everyNth(arr, nth) {\n  return arr.filter(function (e, i) {\n    return i % nth === nth - 1;\n  });\n};",
          "example": "everyNth([1, 2, 3, 4, 5, 6], 2); // [ 2, 4, 6 ]"
        },
        "tags": [
          "array",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "ed7fda7cda998a02fa4d69483826a834a795e3c5aaacabed229b76247dec6fbf"
      }
    },
    {
      "id": "extendHex",
      "type": "snippet",
      "attributes": {
        "fileName": "extendHex.md",
        "text": "Extends a 3-digit color code to a 6-digit color code.\n\nUse `Array.prototype.map()`, `String.prototype.split()` and `Array.prototype.join()` to join the mapped array for converting a 3-digit RGB notated hexadecimal color-code to the 6-digit form.\n`Array.prototype.slice()` is used to remove `#` from string start since it's added once.",
        "codeBlocks": {
          "es6": "const extendHex = shortHex =>\n  '#' +\n  shortHex\n    .slice(shortHex.startsWith('#') ? 1 : 0)\n    .split('')\n    .map(x => x + x)\n    .join('');",
          "es5": "var extendHex = function extendHex(shortHex) {\n  return '#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split('').map(function (x) {\n    return x + x;\n  }).join('');\n};",
          "example": "extendHex('#03f'); // '#0033ff'\nextendHex('05a'); // '#0055aa'"
        },
        "tags": [
          "utility",
          "string",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "5eba7a884e9f26ee2bb9a51cda8e17777fc3957814a3071013f9d4f9958af102"
      }
    },
    {
      "id": "factorial",
      "type": "snippet",
      "attributes": {
        "fileName": "factorial.md",
        "text": "Calculates the factorial of a number.\n\nUse recursion.\nIf `n` is less than or equal to `1`, return `1`.\nOtherwise, return the product of `n` and the factorial of `n - 1`.\nThrows an exception if `n` is a negative number.",
        "codeBlocks": {
          "es6": "const factorial = n =>\n  n < 0\n    ? (() => {\n      throw new TypeError('Negative numbers are not allowed!');\n    })()\n    : n <= 1\n      ? 1\n      : n * factorial(n - 1);",
          "es5": "var factorial = function factorial(n) {\n  return n < 0 ? function () {\n    throw new TypeError('Negative numbers are not allowed!');\n  }() : n <= 1 ? 1 : n * factorial(n - 1);\n};",
          "example": "factorial(6); // 720"
        },
        "tags": [
          "math",
          "recursion",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "383ed61e69b8f63ae42d0746a1995057f4f65b4af6ca7778d8f1771144802acd"
      }
    },
    {
      "id": "fibonacci",
      "type": "snippet",
      "attributes": {
        "fileName": "fibonacci.md",
        "text": "Generates an array, containing the Fibonacci sequence, up until the nth term.\n\nCreate an empty array of the specific length, initializing the first two values (`0` and `1`).\nUse `Array.prototype.reduce()` to add values into the array, using the sum of the last two values, except for the first two.",
        "codeBlocks": {
          "es6": "const fibonacci = n =>\n  Array.from({ length: n }).reduce(\n    (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),\n    []\n  );",
          "es5": "var fibonacci = function fibonacci(n) {\n  return Array.from({\n    length: n\n  }).reduce(function (acc, val, i) {\n    return acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i);\n  }, []);\n};",
          "example": "fibonacci(6); // [0, 1, 1, 2, 3, 5]"
        },
        "tags": [
          "math",
          "array",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "a6d182258648783ab09e72d4c40ac9de0dd3687a3b82c27715efab34d1836e1c"
      }
    },
    {
      "id": "filterNonUnique",
      "type": "snippet",
      "attributes": {
        "fileName": "filterNonUnique.md",
        "text": "Filters out the non-unique values in an array.\n\nUse `Array.prototype.filter()` for an array containing only the unique values.",
        "codeBlocks": {
          "es6": "const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));",
          "es5": "var filterNonUnique = function filterNonUnique(arr) {\n  return arr.filter(function (i) {\n    return arr.indexOf(i) === arr.lastIndexOf(i);\n  });\n};",
          "example": "filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1, 3, 5]"
        },
        "tags": [
          "array",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "be45889694178d9cb40497b8b5e1815b836b6a069881cf83998abddc242234fc"
      }
    },
    {
      "id": "filterNonUniqueBy",
      "type": "snippet",
      "attributes": {
        "fileName": "filterNonUniqueBy.md",
        "text": "Filters out the non-unique values in an array, based on a provided comparator function.\n\nUse `Array.prototype.filter()` and `Array.prototype.every()` for an array containing only the unique values, based on the comparator function, `fn`.\nThe comparator function takes four arguments: the values of the two elements being compared and their indexes.",
        "codeBlocks": {
          "es6": "const filterNonUniqueBy = (arr, fn) =>\n  arr.filter((v, i) => arr.every((x, j) => (i === j) === fn(v, x, i, j)));",
          "es5": "var filterNonUniqueBy = function filterNonUniqueBy(arr, fn) {\n  return arr.filter(function (v, i) {\n    return arr.every(function (x, j) {\n      return i === j === fn(v, x, i, j);\n    });\n  });\n};",
          "example": "filterNonUniqueBy(\n  [\n    { id: 0, value: 'a' },\n    { id: 1, value: 'b' },\n    { id: 2, value: 'c' },\n    { id: 1, value: 'd' },\n    { id: 0, value: 'e' }\n  ],\n  (a, b) => a.id == b.id\n); // [ { id: 2, value: 'c' } ]"
        },
        "tags": [
          "array",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "06a87242bde67fb030fbebf69effe858a5d30e21ca803937a533ab352d8240fc"
      }
    },
    {
      "id": "findKey",
      "type": "snippet",
      "attributes": {
        "fileName": "findKey.md",
        "text": "Returns the first key that satisfies the provided testing function. Otherwise `undefined` is returned.\n\nUse `Object.keys(obj)` to get all the properties of the object, `Array.prototype.find()` to test the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object.",
        "codeBlocks": {
          "es6": "const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj));",
          "es5": "var findKey = function findKey(obj, fn) {\n  return Object.keys(obj).find(function (key) {\n    return fn(obj[key], key, obj);\n  });\n};",
          "example": "findKey(\n  {\n    barney: { age: 36, active: true },\n    fred: { age: 40, active: false },\n    pebbles: { age: 1, active: true }\n  },\n  o => o['active']\n); // 'barney'"
        },
        "tags": [
          "object",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "a6e1a401f74fecda3805e745a4032b6467d3c4f97d0c810b288b59f441db144d"
      }
    },
    {
      "id": "findLast",
      "type": "snippet",
      "attributes": {
        "fileName": "findLast.md",
        "text": "Returns the last element for which the provided function returns a truthy value.\n\nUse `Array.prototype.filter()` to remove elements for which `fn` returns falsey values, `Array.prototype.pop()` to get the last one.",
        "codeBlocks": {
          "es6": "const findLast = (arr, fn) => arr.filter(fn).pop();",
          "es5": "var findLast = function findLast(arr, fn) {\n  return arr.filter(fn).pop();\n};",
          "example": "findLast([1, 2, 3, 4], n => n % 2 === 1); // 3"
        },
        "tags": [
          "array",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "d9b9b99af0ced3ae231521d4100dc5779436dbd624a2c3b9aa11a3ef9fb2edb6"
      }
    },
    {
      "id": "findLastIndex",
      "type": "snippet",
      "attributes": {
        "fileName": "findLastIndex.md",
        "text": "Returns the index of the last element for which the provided function returns a truthy value.\n\nUse `Array.prototype.map()` to map each element to an array with its index and value.\nUse `Array.prototype.filter()` to remove elements for which `fn` returns falsey values, `Array.prototype.pop()` to get the last one.",
        "codeBlocks": {
          "es6": "const findLastIndex = (arr, fn) =>\n  arr\n    .map((val, i) => [i, val])\n    .filter(([i, val]) => fn(val, i, arr))\n    .pop()[0];",
          "es5": "function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }\n\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance\"); }\n\nfunction _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i[\"return\"] != null) _i[\"return\"](); } finally { if (_d) throw _e; } } return _arr; }\n\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n\nvar findLastIndex = function findLastIndex(arr, fn) {\n  return arr.map(function (val, i) {\n    return [i, val];\n  }).filter(function (_ref) {\n    var _ref2 = _slicedToArray(_ref, 2),\n        i = _ref2[0],\n        val = _ref2[1];\n\n    return fn(val, i, arr);\n  }).pop()[0];\n};",
          "example": "findLastIndex([1, 2, 3, 4], n => n % 2 === 1); // 2 (index of the value 3)"
        },
        "tags": [
          "array",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "99268ad91de24fd7c06a35e0e401603da2087fe4b3ec349d6aebe0ae89a579a8"
      }
    },
    {
      "id": "findLastKey",
      "type": "snippet",
      "attributes": {
        "fileName": "findLastKey.md",
        "text": "Returns the last key that satisfies the provided testing function.\nOtherwise `undefined` is returned.\n\nUse `Object.keys(obj)` to get all the properties of the object, `Array.prototype.reverse()` to reverse their order and `Array.prototype.find()` to test the provided function for each key-value pair.\nThe callback receives three arguments - the value, the key and the object.",
        "codeBlocks": {
          "es6": "const findLastKey = (obj, fn) =>\n  Object.keys(obj)\n    .reverse()\n    .find(key => fn(obj[key], key, obj));",
          "es5": "var findLastKey = function findLastKey(obj, fn) {\n  return Object.keys(obj).reverse().find(function (key) {\n    return fn(obj[key], key, obj);\n  });\n};",
          "example": "findLastKey(\n  {\n    barney: { age: 36, active: true },\n    fred: { age: 40, active: false },\n    pebbles: { age: 1, active: true }\n  },\n  o => o['active']\n); // 'pebbles'"
        },
        "tags": [
          "object",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "736507ed960071c1d5e228e2e2689f480e5dc4bb26c6822e5afac8df9b41e872"
      }
    },
    {
      "id": "flatten",
      "type": "snippet",
      "attributes": {
        "fileName": "flatten.md",
        "text": "Flattens an array up to the specified depth.\n\nUse recursion, decrementing `depth` by 1 for each level of depth.\nUse `Array.prototype.reduce()` and `Array.prototype.concat()` to merge elements or arrays.\nBase case, for `depth` equal to `1` stops recursion.\nOmit the second argument, `depth` to flatten only to a depth of `1` (single flatten).",
        "codeBlocks": {
          "es6": "const flatten = (arr, depth = 1) =>\n  arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []);",
          "es5": "var flatten = function flatten(arr) {\n  var depth = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;\n  return arr.reduce(function (a, v) {\n    return a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v);\n  }, []);\n};",
          "example": "flatten([1, [2], 3, 4]); // [1, 2, 3, 4]\nflatten([1, [2, [3, [4, 5], 6], 7], 8], 2); // [1, 2, 3, [4, 5], 6, 7, 8]"
        },
        "tags": [
          "array",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "986e50245ceb51d4bb3baeae10d6e4d162df5c60811f690f4a5e6b4fd36bc2fa"
      }
    },
    {
      "id": "flattenObject",
      "type": "snippet",
      "attributes": {
        "fileName": "flattenObject.md",
        "text": "Flatten an object with the paths for keys.\n\nUse recursion.\nUse `Object.keys(obj)` combined with `Array.prototype.reduce()` to convert every leaf node to a flattened path node.\nIf the value of a key is an object, the function calls itself with the appropriate `prefix` to create the path using `Object.assign()`.\nOtherwise, it adds the appropriate prefixed key-value pair to the accumulator object.\nYou should always omit the second argument, `prefix`, unless you want every key to have a prefix.",
        "codeBlocks": {
          "es6": "const flattenObject = (obj, prefix = '') =>\n  Object.keys(obj).reduce((acc, k) => {\n    const pre = prefix.length ? prefix + '.' : '';\n    if (typeof obj[k] === 'object') Object.assign(acc, flattenObject(obj[k], pre + k));\n    else acc[pre + k] = obj[k];\n    return acc;\n  }, {});",
          "es5": "function _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nvar flattenObject = function flattenObject(obj) {\n  var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';\n  return Object.keys(obj).reduce(function (acc, k) {\n    var pre = prefix.length ? prefix + '.' : '';\n    if (_typeof(obj[k]) === 'object') Object.assign(acc, flattenObject(obj[k], pre + k));else acc[pre + k] = obj[k];\n    return acc;\n  }, {});\n};",
          "example": "flattenObject({ a: { b: { c: 1 } }, d: 1 }); // { 'a.b.c': 1, d: 1 }"
        },
        "tags": [
          "object",
          "recursion",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "0283161af6234908ed0a3403a8e7fb2f33a576deb745f2902e622eb41584b33a"
      }
    },
    {
      "id": "flip",
      "type": "snippet",
      "attributes": {
        "fileName": "flip.md",
        "text": "Flip takes a function as an argument, then makes the first argument the last.\r\n\r\nReturn a closure that takes variadic inputs, and splices the last argument to make it the first argument before applying the rest.",
        "codeBlocks": {
          "es6": "const flip = fn => (first, ...rest) => fn(...rest, first);",
          "es5": "var flip = function flip(fn) {\n  return function (first) {\n    for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n      rest[_key - 1] = arguments[_key];\n    }\n\n    return fn.apply(void 0, rest.concat([first]));\n  };\n};",
          "example": "let a = { name: 'John Smith' };\nlet b = {};\nconst mergeFrom = flip(Object.assign);\nlet mergePerson = mergeFrom.bind(null, a);\nmergePerson(b); // == b\nb = {};\nObject.assign(b, a); // == b"
        },
        "tags": [
          "adapter",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "57a42eb12cc7d4535c25d9945db9abb115ca9520e298fbaed64549ee22ac76aa"
      }
    },
    {
      "id": "forEachRight",
      "type": "snippet",
      "attributes": {
        "fileName": "forEachRight.md",
        "text": "Executes a provided function once for each array element, starting from the array's last element.\n\nUse `Array.prototype.slice(0)` to clone the given array, `Array.prototype.reverse()` to reverse it and `Array.prototype.forEach()` to iterate over the reversed array.",
        "codeBlocks": {
          "es6": "const forEachRight = (arr, callback) =>\n  arr\n    .slice(0)\n    .reverse()\n    .forEach(callback);",
          "es5": "var forEachRight = function forEachRight(arr, callback) {\n  return arr.slice(0).reverse().forEach(callback);\n};",
          "example": "forEachRight([1, 2, 3, 4], val => console.log(val)); // '4', '3', '2', '1'"
        },
        "tags": [
          "array",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "878603be104f98fed0dca2d7c06ece8c4f6906a79ed0329e60bc9964c7b035ff"
      }
    },
    {
      "id": "formatDuration",
      "type": "snippet",
      "attributes": {
        "fileName": "formatDuration.md",
        "text": "Returns the human readable format of the given number of milliseconds.\n\nDivide `ms` with the appropriate values to obtain the appropriate values for `day`, `hour`, `minute`, `second` and `millisecond`.\nUse `Object.entries()` with `Array.prototype.filter()` to keep only non-zero values.\nUse `Array.prototype.map()` to create the string for each value, pluralizing appropriately.\nUse `String.prototype.join(', ')` to combine the values into a string.",
        "codeBlocks": {
          "es6": "const formatDuration = ms => {\n  if (ms < 0) ms = -ms;\n  const time = {\n    day: Math.floor(ms / 86400000),\n    hour: Math.floor(ms / 3600000) % 24,\n    minute: Math.floor(ms / 60000) % 60,\n    second: Math.floor(ms / 1000) % 60,\n    millisecond: Math.floor(ms) % 1000\n  };\n  return Object.entries(time)\n    .filter(val => val[1] !== 0)\n    .map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`)\n    .join(', ');\n};",
          "es5": "function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }\n\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance\"); }\n\nfunction _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i[\"return\"] != null) _i[\"return\"](); } finally { if (_d) throw _e; } } return _arr; }\n\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n\nvar formatDuration = function formatDuration(ms) {\n  if (ms < 0) ms = -ms;\n  var time = {\n    day: Math.floor(ms / 86400000),\n    hour: Math.floor(ms / 3600000) % 24,\n    minute: Math.floor(ms / 60000) % 60,\n    second: Math.floor(ms / 1000) % 60,\n    millisecond: Math.floor(ms) % 1000\n  };\n  return Object.entries(time).filter(function (val) {\n    return val[1] !== 0;\n  }).map(function (_ref) {\n    var _ref2 = _slicedToArray(_ref, 2),\n        key = _ref2[0],\n        val = _ref2[1];\n\n    return \"\".concat(val, \" \").concat(key).concat(val !== 1 ? 's' : '');\n  }).join(', ');\n};",
          "example": "formatDuration(1001); // '1 second, 1 millisecond'\nformatDuration(34325055574); // '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds'"
        },
        "tags": [
          "date",
          "math",
          "string",
          "utility",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "72c557bd9def493e3a138705f5cb66f993228bd7e51b11fa84f85841bc035524"
      }
    },
    {
      "id": "forOwn",
      "type": "snippet",
      "attributes": {
        "fileName": "forOwn.md",
        "text": "Iterates over all own properties of an object, running a callback for each one.\n\nUse `Object.keys(obj)` to get all the properties of the object, `Array.prototype.forEach()` to run the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object.",
        "codeBlocks": {
          "es6": "const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj));",
          "es5": "var forOwn = function forOwn(obj, fn) {\n  return Object.keys(obj).forEach(function (key) {\n    return fn(obj[key], key, obj);\n  });\n};",
          "example": "forOwn({ foo: 'bar', a: 1 }, v => console.log(v)); // 'bar', 1"
        },
        "tags": [
          "object",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "eaaf3b173bbc54d7e83464bc8c96bc9e48a21bcffe606b05134aec2cf0191995"
      }
    },
    {
      "id": "forOwnRight",
      "type": "snippet",
      "attributes": {
        "fileName": "forOwnRight.md",
        "text": "Iterates over all own properties of an object in reverse, running a callback for each one.\n\nUse `Object.keys(obj)` to get all the properties of the object, `Array.prototype.reverse()` to reverse their order and `Array.prototype.forEach()` to run the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object.",
        "codeBlocks": {
          "es6": "const forOwnRight = (obj, fn) =>\n  Object.keys(obj)\n    .reverse()\n    .forEach(key => fn(obj[key], key, obj));",
          "es5": "var forOwnRight = function forOwnRight(obj, fn) {\n  return Object.keys(obj).reverse().forEach(function (key) {\n    return fn(obj[key], key, obj);\n  });\n};",
          "example": "forOwnRight({ foo: 'bar', a: 1 }, v => console.log(v)); // 1, 'bar'"
        },
        "tags": [
          "object",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "ed80f090fa9c7f999c3a2a296ab6c5bc66d53de16af625ca49455ad00200312d"
      }
    },
    {
      "id": "fromCamelCase",
      "type": "snippet",
      "attributes": {
        "fileName": "fromCamelCase.md",
        "text": "Converts a string from camelcase.\n\nUse `String.prototype.replace()` to remove underscores, hyphens, and spaces and convert words to camelcase.\nOmit the second argument to use a default `separator` of `_`.",
        "codeBlocks": {
          "es6": "const fromCamelCase = (str, separator = '_') =>\n  str\n    .replace(/([a-z\\d])([A-Z])/g, '$1' + separator + '$2')\n    .replace(/([A-Z]+)([A-Z][a-z\\d]+)/g, '$1' + separator + '$2')\n    .toLowerCase();",
          "es5": "var fromCamelCase = function fromCamelCase(str) {\n  var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '_';\n  return str.replace(/([a-z\\d])([A-Z])/g, '$1' + separator + '$2').replace(/([A-Z]+)([A-Z][a-z\\d]+)/g, '$1' + separator + '$2').toLowerCase();\n};",
          "example": "fromCamelCase('someDatabaseFieldName', ' '); // 'some database field name'\nfromCamelCase('someLabelThatNeedsToBeCamelized', '-'); // 'some-label-that-needs-to-be-camelized'\nfromCamelCase('someJavascriptProperty', '_'); // 'some_javascript_property'"
        },
        "tags": [
          "string",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "2093c36c482cf2a34c6c3b095fc6c18dc22693138d66d7527a0fe570156106b8"
      }
    },
    {
      "id": "functionName",
      "type": "snippet",
      "attributes": {
        "fileName": "functionName.md",
        "text": "Logs the name of a function.\n\nUse `console.debug()` and the `name` property of the passed method to log the method's name to the `debug` channel of the console.",
        "codeBlocks": {
          "es6": "const functionName = fn => (console.debug(fn.name), fn);",
          "es5": "var functionName = function functionName(fn) {\n  return console.debug(fn.name), fn;\n};",
          "example": "functionName(Math.max); // max (logged in debug channel of console)"
        },
        "tags": [
          "function",
          "utility",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "66e540b754a02d3deba942aa9854d1051ec54c81f22e0dea859c5d3305b89fec"
      }
    },
    {
      "id": "functions",
      "type": "snippet",
      "attributes": {
        "fileName": "functions.md",
        "text": "Returns an array of function property names from own (and optionally inherited) enumerable properties of an object.\n\nUse `Object.keys(obj)` to iterate over the object's own properties.\nIf `inherited` is `true`, use `Object.get.PrototypeOf(obj)` to also get the object's inherited properties.\nUse `Array.prototype.filter()` to keep only those properties that are functions.\nOmit the second argument, `inherited`, to not include inherited properties by default.",
        "codeBlocks": {
          "es6": "const functions = (obj, inherited = false) =>\n  (inherited\n    ? [...Object.keys(obj), ...Object.keys(Object.getPrototypeOf(obj))]\n    : Object.keys(obj)\n  ).filter(key => typeof obj[key] === 'function');",
          "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 functions = function functions(obj) {\n  var inherited = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n  return (inherited ? _toConsumableArray(Object.keys(obj)).concat(_toConsumableArray(Object.keys(Object.getPrototypeOf(obj)))) : Object.keys(obj)).filter(function (key) {\n    return typeof obj[key] === 'function';\n  });\n};",
          "example": "function Foo() {\n  this.a = () => 1;\n  this.b = () => 2;\n}\nFoo.prototype.c = () => 3;\nfunctions(new Foo()); // ['a', 'b']\nfunctions(new Foo(), true); // ['a', 'b', 'c']"
        },
        "tags": [
          "object",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "61abf38f71e57dad7cf5abef9d19950014819f3775371caab92f4433a07d07de"
      }
    },
    {
      "id": "gcd",
      "type": "snippet",
      "attributes": {
        "fileName": "gcd.md",
        "text": "Calculates the greatest common divisor between two or more numbers/arrays.\n\nThe inner `_gcd` function uses recursion.\nBase case is when `y` equals `0`. In this case, return `x`.\nOtherwise, return the GCD of `y` and the remainder of the division `x/y`.",
        "codeBlocks": {
          "es6": "const gcd = (...arr) => {\n  const _gcd = (x, y) => (!y ? x : gcd(y, x % y));\n  return [...arr].reduce((a, b) => _gcd(a, b));\n};",
          "es5": "var gcd = function gcd() {\n  var _gcd = function _gcd(x, y) {\n    return !y ? x : gcd(y, x % y);\n  };\n\n  for (var _len = arguments.length, arr = new Array(_len), _key = 0; _key < _len; _key++) {\n    arr[_key] = arguments[_key];\n  }\n\n  return arr.concat().reduce(function (a, b) {\n    return _gcd(a, b);\n  });\n};",
          "example": "gcd(8, 36); // 4\ngcd(...[12, 8, 32]); // 4"
        },
        "tags": [
          "math",
          "recursion",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "1e35c8e3f0346e387fd97c25ecd0560270860bae65cc4a2d333b949f8187fa92"
      }
    },
    {
      "id": "geometricProgression",
      "type": "snippet",
      "attributes": {
        "fileName": "geometricProgression.md",
        "text": "Initializes an array containing the numbers in the specified range where `start` and `end` are inclusive and the ratio between two terms is `step`.\nReturns an error if `step` equals `1`.\n\nUse `Array.from()`, `Math.log()` and `Math.floor()` to create an array of the desired length, `Array.prototype.map()` to fill with the desired values in a range.\nOmit the second argument, `start`, to use a default value of `1`.\nOmit the third argument, `step`, to use a default value of `2`.",
        "codeBlocks": {
          "es6": "const geometricProgression = (end, start = 1, step = 2) =>\n  Array.from({ length: Math.floor(Math.log(end / start) / Math.log(step)) + 1 }).map(\n    (v, i) => start * step ** i\n  );",
          "es5": "var geometricProgression = function geometricProgression(end) {\n  var start = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;\n  var step = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 2;\n  return Array.from({\n    length: Math.floor(Math.log(end / start) / Math.log(step)) + 1\n  }).map(function (v, i) {\n    return start * Math.pow(step, i);\n  });\n};",
          "example": "geometricProgression(256); // [1, 2, 4, 8, 16, 32, 64, 128, 256]\ngeometricProgression(256, 3); // [3, 6, 12, 24, 48, 96, 192]\ngeometricProgression(256, 1, 4); // [1, 4, 16, 64, 256]"
        },
        "tags": [
          "math",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "6041519112ff2d31db7b7076bc472cdcdfac0f293f2616b1af53f02313e46938"
      }
    },
    {
      "id": "get",
      "type": "snippet",
      "attributes": {
        "fileName": "get.md",
        "text": "Retrieve a set of properties indicated by the given selectors from an object.\n\nUse `Array.prototype.map()` for each selector, `String.prototype.replace()` to replace square brackets with dots, `String.prototype.split('.')` to split each selector, `Array.prototype.filter()` to remove empty values and `Array.prototype.reduce()` to get the value indicated by it.",
        "codeBlocks": {
          "es6": "const get = (from, ...selectors) =>\n  [...selectors].map(s =>\n    s\n      .replace(/\\[([^\\[\\]]*)\\]/g, '.$1.')\n      .split('.')\n      .filter(t => t !== '')\n      .reduce((prev, cur) => prev && prev[cur], from)\n  );",
          "es5": "var get = function get(from) {\n  for (var _len = arguments.length, selectors = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n    selectors[_key - 1] = arguments[_key];\n  }\n\n  return selectors.concat().map(function (s) {\n    return s.replace(/\\[([^\\[\\]]*)\\]/g, '.$1.').split('.').filter(function (t) {\n      return t !== '';\n    }).reduce(function (prev, cur) {\n      return prev && prev[cur];\n    }, from);\n  });\n};",
          "example": "const obj = { selector: { to: { val: 'val to select' } }, target: [1, 2, { a: 'test' }] };\nget(obj, 'selector.to.val', 'target[0]', 'target[2].a'); // ['val to select', 1, 'test']"
        },
        "tags": [
          "object",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "db5e6f745e0157873ab4c0840da8675d3d20b8fe2ecbbb4e9f24744606b0dde9"
      }
    },
    {
      "id": "getColonTimeFromDate",
      "type": "snippet",
      "attributes": {
        "fileName": "getColonTimeFromDate.md",
        "text": "Returns a string of the form `HH:MM:SS` from a `Date` object.\n\nUse `Date.prototype.toTimeString()` and `String.prototype.slice()` to get the `HH:MM:SS` part of a given `Date` object.",
        "codeBlocks": {
          "es6": "const getColonTimeFromDate = date => date.toTimeString().slice(0, 8);",
          "es5": "var getColonTimeFromDate = function getColonTimeFromDate(date) {\n  return date.toTimeString().slice(0, 8);\n};",
          "example": "getColonTimeFromDate(new Date()); // \"08:38:00\""
        },
        "tags": [
          "date",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "047d7aa6776b48b392054fc0addcffa4485904f6281f277426911f3ef475b079"
      }
    },
    {
      "id": "getDaysDiffBetweenDates",
      "type": "snippet",
      "attributes": {
        "fileName": "getDaysDiffBetweenDates.md",
        "text": "Returns the difference (in days) between two dates.\n\nCalculate the difference (in days) between two `Date` objects.",
        "codeBlocks": {
          "es6": "const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>\n  (dateFinal - dateInitial) / (1000 * 3600 * 24);",
          "es5": "var getDaysDiffBetweenDates = function getDaysDiffBetweenDates(dateInitial, dateFinal) {\n  return (dateFinal - dateInitial) / (1000 * 3600 * 24);\n};",
          "example": "getDaysDiffBetweenDates(new Date('2017-12-13'), new Date('2017-12-22')); // 9"
        },
        "tags": [
          "date",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "baeec5f4220f1e457b11034e29d84277dbdc9fc5c9e69c1a225bb22f13b843ec"
      }
    },
    {
      "id": "getImages",
      "type": "snippet",
      "attributes": {
        "fileName": "getImages.md",
        "text": "Fetches all images from within an element and puts them into an array\n\nUse `Element.prototype.getElementsByTagName()` to fetch all `<img>` elements inside the provided element, `Array.prototype.map()` to map every `src` attribute of their respective `<img>` element, then create a `Set` to eliminate duplicates and return the array.",
        "codeBlocks": {
          "es6": "const getImages = (el, includeDuplicates = false) => {\n  const images = [...el.getElementsByTagName('img')].map(img => img.getAttribute('src'));\n  return includeDuplicates ? images : [...new Set(images)];\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 getImages = function getImages(el) {\n  var includeDuplicates = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n\n  var images = _toConsumableArray(el.getElementsByTagName('img')).map(function (img) {\n    return img.getAttribute('src');\n  });\n\n  return includeDuplicates ? images : _toConsumableArray(new Set(images));\n};",
          "example": "getImages(document, true); // ['image1.jpg', 'image2.png', 'image1.png', '...']\ngetImages(document, false); // ['image1.jpg', 'image2.png', '...']"
        },
        "tags": [
          "browser",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "0f2ba02c6de1e9396abbef584139bea4dc379a6d465f4bebb151ad3b0f77ff6f"
      }
    },
    {
      "id": "getMeridiemSuffixOfInteger",
      "type": "snippet",
      "attributes": {
        "fileName": "getMeridiemSuffixOfInteger.md",
        "text": "Converts an integer to a suffixed string, adding `am` or `pm` based on its value.\n\nUse the modulo operator (`%`) and conditional checks to transform an integer to a stringified 12-hour format with meridiem suffix.",
        "codeBlocks": {
          "es6": "const getMeridiemSuffixOfInteger = num =>\n  num === 0 || num === 24\n    ? 12 + 'am'\n    : num === 12\n      ? 12 + 'pm'\n      : num < 12\n        ? (num % 12) + 'am'\n        : (num % 12) + 'pm';",
          "es5": "var getMeridiemSuffixOfInteger = function getMeridiemSuffixOfInteger(num) {\n  return num === 0 || num === 24 ? 12 + 'am' : num === 12 ? 12 + 'pm' : num < 12 ? num % 12 + 'am' : num % 12 + 'pm';\n};",
          "example": "getMeridiemSuffixOfInteger(0); // \"12am\"\ngetMeridiemSuffixOfInteger(11); // \"11am\"\ngetMeridiemSuffixOfInteger(13); // \"1pm\"\ngetMeridiemSuffixOfInteger(25); // \"1pm\""
        },
        "tags": [
          "date",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "561d55a2f839596b336a04badbd160a3b895e9ebb9c1d392998ecccdbe5fb98d"
      }
    },
    {
      "id": "getScrollPosition",
      "type": "snippet",
      "attributes": {
        "fileName": "getScrollPosition.md",
        "text": "Returns the scroll position of the current page.\n\nUse `pageXOffset` and `pageYOffset` if they are defined, otherwise `scrollLeft` and `scrollTop`.\nYou can omit `el` to use a default value of `window`.",
        "codeBlocks": {
          "es6": "const getScrollPosition = (el = window) => ({\n  x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,\n  y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop\n});",
          "es5": "var getScrollPosition = function getScrollPosition() {\n  var el = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window;\n  return {\n    x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,\n    y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop\n  };\n};",
          "example": "getScrollPosition(); // {x: 0, y: 200}"
        },
        "tags": [
          "browser",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "4033549c80f649c2a9b9b50d1af42410811ff72914c5eb576445219bddfc792f"
      }
    },
    {
      "id": "getStyle",
      "type": "snippet",
      "attributes": {
        "fileName": "getStyle.md",
        "text": "Returns the value of a CSS rule for the specified element.\n\nUse `Window.getComputedStyle()` to get the value of the CSS rule for the specified element.",
        "codeBlocks": {
          "es6": "const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName];",
          "es5": "var getStyle = function getStyle(el, ruleName) {\n  return getComputedStyle(el)[ruleName];\n};",
          "example": "getStyle(document.querySelector('p'), 'font-size'); // '16px'"
        },
        "tags": [
          "browser",
          "css",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "b9668334e0fd077c4e43d616765e4343b3770a0a3bd6b846ecc743ca7d65a804"
      }
    },
    {
      "id": "getType",
      "type": "snippet",
      "attributes": {
        "fileName": "getType.md",
        "text": "Returns the native type of a value.\n\nReturns lowercased constructor name of value, `\"undefined\"` or `\"null\"` if value is `undefined` or `null`.",
        "codeBlocks": {
          "es6": "const getType = v =>\n  v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();",
          "es5": "var getType = function getType(v) {\n  return v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();\n};",
          "example": "getType(new Set([1, 2, 3])); // 'set'"
        },
        "tags": [
          "type",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "7fb09e3f807459959cae5fcb87ac323286e0a36ed4500b699c292c19b709af38"
      }
    },
    {
      "id": "getURLParameters",
      "type": "snippet",
      "attributes": {
        "fileName": "getURLParameters.md",
        "text": "Returns an object containing the parameters of the current URL.\n\nUse `String.match()` with an appropriate regular expression to get all key-value pairs, `Array.prototype.reduce()` to map and combine them into a single object.\nPass `location.search` as the argument to apply to the current `url`.",
        "codeBlocks": {
          "es6": "const getURLParameters = url =>\n  (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(\n    (a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),\n    {}\n  );",
          "es5": "var getURLParameters = function getURLParameters(url) {\n  return (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(function (a, v) {\n    return a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1), a;\n  }, {});\n};",
          "example": "getURLParameters('http://url.com/page?name=Adam&surname=Smith'); // {name: 'Adam', surname: 'Smith'}\ngetURLParameters('google.com'); // {}"
        },
        "tags": [
          "utility",
          "browser",
          "string",
          "url",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "defd32f6b9e8d045213a7cbe4a68686ec229c472e46837afb6c7bd1b3df3ccae"
      }
    },
    {
      "id": "groupBy",
      "type": "snippet",
      "attributes": {
        "fileName": "groupBy.md",
        "text": "Groups the elements of an array based on the given function.\n\nUse `Array.prototype.map()` to map the values of an array to a function or property name.\nUse `Array.prototype.reduce()` to create an object, where the keys are produced from the mapped results.",
        "codeBlocks": {
          "es6": "const groupBy = (arr, fn) =>\n  arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => {\n    acc[val] = (acc[val] || []).concat(arr[i]);\n    return acc;\n  }, {});",
          "es5": "var groupBy = function groupBy(arr, fn) {\n  return arr.map(typeof fn === 'function' ? fn : function (val) {\n    return val[fn];\n  }).reduce(function (acc, val, i) {\n    acc[val] = (acc[val] || []).concat(arr[i]);\n    return acc;\n  }, {});\n};",
          "example": "groupBy([6.1, 4.2, 6.3], Math.floor); // {4: [4.2], 6: [6.1, 6.3]}\ngroupBy(['one', 'two', 'three'], 'length'); // {3: ['one', 'two'], 5: ['three']}"
        },
        "tags": [
          "array",
          "object",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "3d356c5e5780be7b393fe37e2bee159be965aae0ebc4474979e28385ea8af18a"
      }
    },
    {
      "id": "hammingDistance",
      "type": "snippet",
      "attributes": {
        "fileName": "hammingDistance.md",
        "text": "Calculates the Hamming distance between two values.\n\nUse XOR operator (`^`) to find the bit difference between the two numbers, convert to a binary string using `toString(2)`.\nCount and return the number of `1`s in the string, using `match(/1/g)`.",
        "codeBlocks": {
          "es6": "const hammingDistance = (num1, num2) => ((num1 ^ num2).toString(2).match(/1/g) || '').length;",
          "es5": "var hammingDistance = function hammingDistance(num1, num2) {\n  return ((num1 ^ num2).toString(2).match(/1/g) || '').length;\n};",
          "example": "hammingDistance(2, 3); // 1"
        },
        "tags": [
          "math",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "e75b1c53cb28dce1ac4f8e1d1289f96da22e2b24e6c3a28bd5fd5adc5f4ec5de"
      }
    },
    {
      "id": "hasClass",
      "type": "snippet",
      "attributes": {
        "fileName": "hasClass.md",
        "text": "Returns `true` if the element has the specified class, `false` otherwise.\n\nUse `element.classList.contains()` to check if the element has the specified class.",
        "codeBlocks": {
          "es6": "const hasClass = (el, className) => el.classList.contains(className);",
          "es5": "var hasClass = function hasClass(el, className) {\n  return el.classList.contains(className);\n};",
          "example": "hasClass(document.querySelector('p.special'), 'special'); // true"
        },
        "tags": [
          "browser",
          "css",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "edb16de35e0a033f7dece0ff7854b17cb6c5ed0ed68438556ee38b68b219e7fe"
      }
    },
    {
      "id": "hasFlags",
      "type": "snippet",
      "attributes": {
        "fileName": "hasFlags.md",
        "text": "Check if the current process's arguments contain the specified flags.\n\nUse `Array.prototype.every()` and `Array.prototype.includes()` to check if `process.argv` contains all the specified flags.\nUse a regular expression to test if the specified flags are prefixed with `-` or `--` and prefix them accordingly.",
        "codeBlocks": {
          "es6": "const hasFlags = (...flags) =>\n  flags.every(flag => process.argv.includes(/^-{1,2}/.test(flag) ? flag : '--' + flag));",
          "es5": "var hasFlags = function hasFlags() {\n  for (var _len = arguments.length, flags = new Array(_len), _key = 0; _key < _len; _key++) {\n    flags[_key] = arguments[_key];\n  }\n\n  return flags.every(function (flag) {\n    return process.argv.includes(/^-{1,2}/.test(flag) ? flag : '--' + flag);\n  });\n};",
          "example": "// node myScript.js -s --test --cool=true\nhasFlags('-s'); // true\nhasFlags('--test', 'cool=true', '-s'); // true\nhasFlags('special'); // false"
        },
        "tags": [
          "node",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "f045367ac2eab790b4e7783704bdce034b8f750aac38a96b2a6bfac4badec938"
      }
    },
    {
      "id": "hashBrowser",
      "type": "snippet",
      "attributes": {
        "fileName": "hashBrowser.md",
        "text": "Creates a hash for a value using the [SHA-256](https://en.wikipedia.org/wiki/SHA-2) algorithm. Returns a promise.\n\nUse the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) API to create a hash for the given value.",
        "codeBlocks": {
          "es6": "const hashBrowser = val =>\n  crypto.subtle.digest('SHA-256', new TextEncoder('utf-8').encode(val)).then(h => {\n    let hexes = [],\n      view = new DataView(h);\n    for (let i = 0; i < view.byteLength; i += 4)\n      hexes.push(('00000000' + view.getUint32(i).toString(16)).slice(-8));\n    return hexes.join('');\n  });",
          "es5": "var hashBrowser = function hashBrowser(val) {\n  return crypto.subtle.digest('SHA-256', new TextEncoder('utf-8').encode(val)).then(function (h) {\n    var hexes = [],\n        view = new DataView(h);\n\n    for (var i = 0; i < view.byteLength; i += 4) {\n      hexes.push(('00000000' + view.getUint32(i).toString(16)).slice(-8));\n    }\n\n    return hexes.join('');\n  });\n};",
          "example": "hashBrowser(JSON.stringify({ a: 'a', b: [1, 2, 3, 4], foo: { c: 'bar' } })).then(console.log); // '04aa106279f5977f59f9067fa9712afc4aedc6f5862a8defc34552d8c7206393'"
        },
        "tags": [
          "browser",
          "utility",
          "advanced",
          "promise",
          "advanced"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "aa8ba51d9419e05e0d2962221c0a65311ad54b4b38f278a1d4ab546ca5b29bc9"
      }
    },
    {
      "id": "hashNode",
      "type": "snippet",
      "attributes": {
        "fileName": "hashNode.md",
        "text": "Creates a hash for a value using the [SHA-256](https://en.wikipedia.org/wiki/SHA-2) algorithm. Returns a promise.\n\nUse `crypto` API to create a hash for the given value.",
        "codeBlocks": {
          "es6": "const crypto = require('crypto');\nconst hashNode = val =>\n  new Promise(resolve =>\n    setTimeout(\n      () =>\n        resolve(\n          crypto\n            .createHash('sha256')\n            .update(val)\n            .digest('hex')\n        ),\n      0\n    )\n  );",
          "es5": "var crypto = require('crypto');\n\nvar hashNode = function hashNode(val) {\n  return new Promise(function (resolve) {\n    return setTimeout(function () {\n      return resolve(crypto.createHash('sha256').update(val).digest('hex'));\n    }, 0);\n  });\n};",
          "example": "hashNode(JSON.stringify({ a: 'a', b: [1, 2, 3, 4], foo: { c: 'bar' } })).then(console.log); // '04aa106279f5977f59f9067fa9712afc4aedc6f5862a8defc34552d8c7206393'"
        },
        "tags": [
          "node",
          "utility",
          "promise",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "80adea6b33dacdfc5f2d25ce270472f232208fa688794b71ba042ea368e1ad63"
      }
    },
    {
      "id": "head",
      "type": "snippet",
      "attributes": {
        "fileName": "head.md",
        "text": "Returns the head of a list.\n\nUse `arr[0]` to return the first element of the passed array.",
        "codeBlocks": {
          "es6": "const head = arr => arr[0];",
          "es5": "var head = function head(arr) {\n  return arr[0];\n};",
          "example": "head([1, 2, 3]); // 1"
        },
        "tags": [
          "array",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "cd65a1dea363ab1e3773705c33b30afd44fd1ab2ecb57f732c35fd4e737ada11"
      }
    },
    {
      "id": "hexToRGB",
      "type": "snippet",
      "attributes": {
        "fileName": "hexToRGB.md",
        "text": "Converts a color code to a `rgb()` or `rgba()` string if alpha value is provided.\n\nUse bitwise right-shift operator and mask bits with `&` (and) operator to convert a hexadecimal color code (with or without prefixed with `#`) to a string with the RGB values. If it's 3-digit color code, first convert to 6-digit version. If an alpha value is provided alongside 6-digit hex, give `rgba()` string in return.",
        "codeBlocks": {
          "es6": "const hexToRGB = hex => {\n  let alpha = false,\n    h = hex.slice(hex.startsWith('#') ? 1 : 0);\n  if (h.length === 3) h = [...h].map(x => x + x).join('');\n  else if (h.length === 8) alpha = true;\n  h = parseInt(h, 16);\n  return (\n    'rgb' +\n    (alpha ? 'a' : '') +\n    '(' +\n    (h >>> (alpha ? 24 : 16)) +\n    ', ' +\n    ((h & (alpha ? 0x00ff0000 : 0x00ff00)) >>> (alpha ? 16 : 8)) +\n    ', ' +\n    ((h & (alpha ? 0x0000ff00 : 0x0000ff)) >>> (alpha ? 8 : 0)) +\n    (alpha ? `, ${h & 0x000000ff}` : '') +\n    ')'\n  );\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 hexToRGB = function hexToRGB(hex) {\n  var alpha = false,\n      h = hex.slice(hex.startsWith('#') ? 1 : 0);\n  if (h.length === 3) h = _toConsumableArray(h).map(function (x) {\n    return x + x;\n  }).join('');else if (h.length === 8) alpha = true;\n  h = parseInt(h, 16);\n  return 'rgb' + (alpha ? 'a' : '') + '(' + (h >>> (alpha ? 24 : 16)) + ', ' + ((h & (alpha ? 0x00ff0000 : 0x00ff00)) >>> (alpha ? 16 : 8)) + ', ' + ((h & (alpha ? 0x0000ff00 : 0x0000ff)) >>> (alpha ? 8 : 0)) + (alpha ? \", \".concat(h & 0x000000ff) : '') + ')';\n};",
          "example": "hexToRGB('#27ae60ff'); // 'rgba(39, 174, 96, 255)'\nhexToRGB('27ae60'); // 'rgb(39, 174, 96)'\nhexToRGB('#fff'); // 'rgb(255, 255, 255)'"
        },
        "tags": [
          "utility",
          "string",
          "math",
          "advanced"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "181b4df31bcbafebd7960725d19c945925a2dc5ee79ef30668d4becae0c82518"
      }
    },
    {
      "id": "hide",
      "type": "snippet",
      "attributes": {
        "fileName": "hide.md",
        "text": "Hides all the elements specified.\n\nUse `NodeList.prototype.forEach()` to apply `display: none` to each element specified.",
        "codeBlocks": {
          "es6": "const hide = (...el) => [...el].forEach(e => (e.style.display = 'none'));",
          "es5": "var hide = function hide() {\n  for (var _len = arguments.length, el = new Array(_len), _key = 0; _key < _len; _key++) {\n    el[_key] = arguments[_key];\n  }\n\n  return el.concat().forEach(function (e) {\n    return e.style.display = 'none';\n  });\n};",
          "example": "hide(document.querySelectorAll('img')); // Hides all <img> elements on the page"
        },
        "tags": [
          "browser",
          "css",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "40558410bed6e9e2866362dc86898fd28a97073f798d8dd5c566eea2ccec2f8f"
      }
    },
    {
      "id": "httpGet",
      "type": "snippet",
      "attributes": {
        "fileName": "httpGet.md",
        "text": "Makes a `GET` request to the passed URL.\n\nUse [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest) web api to make a `get` request to the given `url`.\nHandle the `onload` event, by calling the given `callback` the `responseText`.\nHandle the `onerror` event, by running the provided `err` function.\nOmit the third argument, `err`, to log errors to the console's `error` stream by default.",
        "codeBlocks": {
          "es6": "const httpGet = (url, callback, err = console.error) => {\n  const request = new XMLHttpRequest();\n  request.open('GET', url, true);\n  request.onload = () => callback(request.responseText);\n  request.onerror = () => err(request);\n  request.send();\n};",
          "es5": "var httpGet = function httpGet(url, callback) {\n  var err = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : console.error;\n  var request = new XMLHttpRequest();\n  request.open('GET', url, true);\n\n  request.onload = function () {\n    return callback(request.responseText);\n  };\n\n  request.onerror = function () {\n    return err(request);\n  };\n\n  request.send();\n};",
          "example": "httpGet(\n  'https://jsonplaceholder.typicode.com/posts/1',\n  console.log\n); /*\nLogs: {\n  \"userId\": 1,\n  \"id\": 1,\n  \"title\": \"sunt aut facere repellat provident occaecati excepturi optio reprehenderit\",\n  \"body\": \"quia et suscipit\\nsuscipit recusandae consequuntur expedita et cum\\nreprehenderit molestiae ut ut quas totam\\nnostrum rerum est autem sunt rem eveniet architecto\"\n}\n*/"
        },
        "tags": [
          "utility",
          "url",
          "browser",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "2ce890e49f107cfefbcd752721c447416c350e8e1fd3ee1befc3f154c5d5adc4"
      }
    },
    {
      "id": "httpPost",
      "type": "snippet",
      "attributes": {
        "fileName": "httpPost.md",
        "text": "Makes a `POST` request to the passed URL.\n\nUse [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest) web api to make a `post` request to the given `url`.\nSet the value of an `HTTP` request header with `setRequestHeader` method.\nHandle the `onload` event, by calling the given `callback` the `responseText`.\nHandle the `onerror` event, by running the provided `err` function.\nOmit the third argument, `data`, to send no data to the provided `url`.\nOmit the fourth argument, `err`, to log errors to the console's `error` stream by default.",
        "codeBlocks": {
          "es6": "const httpPost = (url, data, callback, err = console.error) => {\n  const request = new XMLHttpRequest();\n  request.open('POST', url, true);\n  request.setRequestHeader('Content-type', 'application/json; charset=utf-8');\n  request.onload = () => callback(request.responseText);\n  request.onerror = () => err(request);\n  request.send(data);\n};",
          "es5": "var httpPost = function httpPost(url, data, callback) {\n  var err = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : console.error;\n  var request = new XMLHttpRequest();\n  request.open('POST', url, true);\n  request.setRequestHeader('Content-type', 'application/json; charset=utf-8');\n\n  request.onload = function () {\n    return callback(request.responseText);\n  };\n\n  request.onerror = function () {\n    return err(request);\n  };\n\n  request.send(data);\n};",
          "example": "const newPost = {\n  userId: 1,\n  id: 1337,\n  title: 'Foo',\n  body: 'bar bar bar'\n};\nconst data = JSON.stringify(newPost);\nhttpPost(\n  'https://jsonplaceholder.typicode.com/posts',\n  data,\n  console.log\n); /*\nLogs: {\n  \"userId\": 1,\n  \"id\": 1337,\n  \"title\": \"Foo\",\n  \"body\": \"bar bar bar\"\n}\n*/\nhttpPost(\n  'https://jsonplaceholder.typicode.com/posts',\n  null, // does not send a body\n  console.log\n); /*\nLogs: {\n  \"id\": 101\n}\n*/"
        },
        "tags": [
          "utility",
          "url",
          "browser",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "c243abb2f47bce90c1afdeaab78cacc1a5997e8124d8588f446c2e33ec5166f7"
      }
    },
    {
      "id": "httpsRedirect",
      "type": "snippet",
      "attributes": {
        "fileName": "httpsRedirect.md",
        "text": "Redirects the page to HTTPS if its currently in HTTP. Also, pressing the back button doesn't take it back to the HTTP page as its replaced in the history.\n\nUse `location.protocol` to get the protocol currently being used. If it's not HTTPS, use `location.replace()` to replace the existing page with the HTTPS version of the page. Use `location.href` to get the full address, split it with `String.prototype.split()` and remove the protocol part of the URL.",
        "codeBlocks": {
          "es6": "const httpsRedirect = () => {\n  if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]);\n};",
          "es5": "var httpsRedirect = function httpsRedirect() {\n  if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]);\n};",
          "example": "httpsRedirect(); // If you are on http://mydomain.com, you are redirected to https://mydomain.com"
        },
        "tags": [
          "browser",
          "url",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "a233bf70be2dc7a0696d852561462c21f14974dbf43d888696fb8b7c36d0ca63"
      }
    },
    {
      "id": "hz",
      "type": "snippet",
      "attributes": {
        "fileName": "hz.md",
        "text": "Returns the number of times a function executed per second. \n`hz` is the unit for `hertz`, the unit of frequency defined as one cycle per second.\n\nUse `performance.now()` to get the difference in milliseconds before and after the iteration loop to calculate the time elapsed executing the function `iterations` times. \nReturn the number of cycles per second by converting milliseconds to seconds and dividing it by the time elapsed. \nOmit the second argument, `iterations`, to use the default of 100 iterations.",
        "codeBlocks": {
          "es6": "const hz = (fn, iterations = 100) => {\n  const before = performance.now();\n  for (let i = 0; i < iterations; i++) fn();\n  return (1000 * iterations) / (performance.now() - before);\n};",
          "es5": "var hz = function hz(fn) {\n  var iterations = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100;\n  var before = performance.now();\n\n  for (var i = 0; i < iterations; i++) {\n    fn();\n  }\n\n  return 1000 * iterations / (performance.now() - before);\n};",
          "example": "// 10,000 element array\nconst numbers = Array(10000)\n  .fill()\n  .map((_, i) => i);\n\n// Test functions with the same goal: sum up the elements in the array\nconst sumReduce = () => numbers.reduce((acc, n) => acc + n, 0);\nconst sumForLoop = () => {\n  let sum = 0;\n  for (let i = 0; i < numbers.length; i++) sum += numbers[i];\n  return sum;\n};\n\n// `sumForLoop` is nearly 10 times faster\nMath.round(hz(sumReduce)); // 572\nMath.round(hz(sumForLoop)); // 4784"
        },
        "tags": [
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "4c8c44d8677b7b591d36d043e3c1347b50ad21e2b24aa371ea50b515ee98254f"
      }
    },
    {
      "id": "indentString",
      "type": "snippet",
      "attributes": {
        "fileName": "indentString.md",
        "text": "Indents each line in the provided string.\n\nUse `String.replace` and a regular expression to add the character specified by `indent` `count` times at the start of each line.\nOmit the third parameter, `indent`, to use a default indentation character of `' '`.",
        "codeBlocks": {
          "es6": "const indentString = (str, count, indent = ' ') => str.replace(/^/gm, indent.repeat(count));",
          "es5": "var indentString = function indentString(str, count) {\n  var indent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ' ';\n  return str.replace(/^/gm, indent.repeat(count));\n};",
          "example": "indentString('Lorem\\nIpsum', 2); // '  Lorem\\n  Ipsum'\nindentString('Lorem\\nIpsum', 2, '_'); // '__Lorem\\n__Ipsum'"
        },
        "tags": [
          "string",
          "utility",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "2249bdeaa8327b70492049e43d049bd3a0c6b147cafb80504d59a9199f57d0d2"
      }
    },
    {
      "id": "indexOfAll",
      "type": "snippet",
      "attributes": {
        "fileName": "indexOfAll.md",
        "text": "Returns all indices of `val` in an array.\nIf `val` never occurs, returns `[]`.\n\nUse `Array.prototype.reduce()` to loop over elements and store indices for matching elements.\nReturn the array of indices.",
        "codeBlocks": {
          "es6": "const indexOfAll = (arr, val) => arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []);",
          "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 indexOfAll = function indexOfAll(arr, val) {\n  return arr.reduce(function (acc, el, i) {\n    return el === val ? _toConsumableArray(acc).concat([i]) : acc;\n  }, []);\n};",
          "example": "indexOfAll([1, 2, 3, 1, 2, 3], 1); // [0,3]\nindexOfAll([1, 2, 3], 4); // []"
        },
        "tags": [
          "array",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "c55f08e2dacfc794891f331a8ab6038a6600aa3a27d73b04d6d8e20142ee38e7"
      }
    },
    {
      "id": "initial",
      "type": "snippet",
      "attributes": {
        "fileName": "initial.md",
        "text": "Returns all the elements of an array except the last one.\n\nUse `arr.slice(0,-1)` to return all but the last element of the array.",
        "codeBlocks": {
          "es6": "const initial = arr => arr.slice(0, -1);",
          "es5": "var initial = function initial(arr) {\n  return arr.slice(0, -1);\n};",
          "example": "initial([1, 2, 3]); // [1,2]"
        },
        "tags": [
          "array",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "fbb48fd534c60e0b78ddc84eb7dcdc74e0cb8487545da6a49ca53149915af632"
      }
    },
    {
      "id": "initialize2DArray",
      "type": "snippet",
      "attributes": {
        "fileName": "initialize2DArray.md",
        "text": "Initializes a 2D array of given width and height and value.\n\nUse `Array.prototype.map()` to generate h rows where each is a new array of size w initialize with value. If the value is not provided, default to `null`.",
        "codeBlocks": {
          "es6": "const initialize2DArray = (w, h, val = null) =>\n  Array.from({ length: h }).map(() => Array.from({ length: w }).fill(val));",
          "es5": "var initialize2DArray = function initialize2DArray(w, h) {\n  var val = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;\n  return Array.from({\n    length: h\n  }).map(function () {\n    return Array.from({\n      length: w\n    }).fill(val);\n  });\n};",
          "example": "initialize2DArray(2, 2, 0); // [[0,0], [0,0]]"
        },
        "tags": [
          "array",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "9c91703349f7d2e9ae8806ca1374f893a06389e7caf6b6410cd4edcdc0cdc641"
      }
    },
    {
      "id": "initializeArrayWithRange",
      "type": "snippet",
      "attributes": {
        "fileName": "initializeArrayWithRange.md",
        "text": "Initializes an array containing the numbers in the specified range where `start` and `end` are inclusive with their common difference `step`.\n\nUse `Array.from()` to create an array of the desired length, `(end - start + 1)/step`, and a map function to fill it with the desired values in the given range.\nYou can omit `start` to use a default value of `0`.\nYou can omit `step` to use a default value of `1`.",
        "codeBlocks": {
          "es6": "const initializeArrayWithRange = (end, start = 0, step = 1) =>\n  Array.from({ length: Math.ceil((end - start + 1) / step) }, (v, i) => i * step + start);",
          "es5": "var initializeArrayWithRange = function initializeArrayWithRange(end) {\n  var start = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n  var step = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n  return Array.from({\n    length: Math.ceil((end - start + 1) / step)\n  }, function (v, i) {\n    return i * step + start;\n  });\n};",
          "example": "initializeArrayWithRange(5); // [0,1,2,3,4,5]\ninitializeArrayWithRange(7, 3); // [3,4,5,6,7]\ninitializeArrayWithRange(9, 0, 2); // [0,2,4,6,8]"
        },
        "tags": [
          "array",
          "math",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "f2cb7d6d0d34691affe17f7c06ee5c45944bd9515298560a18543f0798b4fe13"
      }
    },
    {
      "id": "initializeArrayWithRangeRight",
      "type": "snippet",
      "attributes": {
        "fileName": "initializeArrayWithRangeRight.md",
        "text": "Initializes an array containing the numbers in the specified range (in reverse) where `start` and `end` are inclusive with their common difference `step`.\n\nUse `Array.from(Math.ceil((end+1-start)/step))` to create an array of the desired length(the amounts of elements is equal to `(end-start)/step` or `(end+1-start)/step` for inclusive end), `Array.prototype.map()` to fill with the desired values in a range.\nYou can omit `start` to use a default value of `0`.\nYou can omit `step` to use a default value of `1`.",
        "codeBlocks": {
          "es6": "const initializeArrayWithRangeRight = (end, start = 0, step = 1) =>\n  Array.from({ length: Math.ceil((end + 1 - start) / step) }).map(\n    (v, i, arr) => (arr.length - i - 1) * step + start\n  );",
          "es5": "var initializeArrayWithRangeRight = function initializeArrayWithRangeRight(end) {\n  var start = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n  var step = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n  return Array.from({\n    length: Math.ceil((end + 1 - start) / step)\n  }).map(function (v, i, arr) {\n    return (arr.length - i - 1) * step + start;\n  });\n};",
          "example": "initializeArrayWithRangeRight(5); // [5,4,3,2,1,0]\ninitializeArrayWithRangeRight(7, 3); // [7,6,5,4,3]\ninitializeArrayWithRangeRight(9, 0, 2); // [8,6,4,2,0]"
        },
        "tags": [
          "array",
          "math",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "d70f1e3ff938d3aa378038d316bb2d131da5fdd2ea62ef512de3336910e6f342"
      }
    },
    {
      "id": "initializeArrayWithValues",
      "type": "snippet",
      "attributes": {
        "fileName": "initializeArrayWithValues.md",
        "text": "Initializes and fills an array with the specified values.\n\nUse `Array(n)` to create an array of the desired length, `fill(v)` to fill it with the desired values.\nYou can omit `val` to use a default value of `0`.",
        "codeBlocks": {
          "es6": "const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val);",
          "es5": "var initializeArrayWithValues = function initializeArrayWithValues(n) {\n  var val = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n  return Array(n).fill(val);\n};",
          "example": "initializeArrayWithValues(5, 2); // [2, 2, 2, 2, 2]"
        },
        "tags": [
          "array",
          "math",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "67fe7e3ed8f8866b3669541f28a13b5a2b0c3719edcff68a3284884f3f39dca8"
      }
    },
    {
      "id": "initializeNDArray",
      "type": "snippet",
      "attributes": {
        "fileName": "initializeNDArray.md",
        "text": "Create a n-dimensional array with given value.\n\nUse recursion.\nUse `Array.prototype.map()` to generate rows where each is a new array initialized using `initializeNDArray`.",
        "codeBlocks": {
          "es6": "const initializeNDArray = (val, ...args) =>\n  args.length === 0\n    ? val\n    : Array.from({ length: args[0] }).map(() => initializeNDArray(val, ...args.slice(1)));",
          "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 initializeNDArray = function initializeNDArray(val) {\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 args.length === 0 ? val : Array.from({\n    length: args[0]\n  }).map(function () {\n    return initializeNDArray.apply(void 0, [val].concat(_toConsumableArray(args.slice(1))));\n  });\n};",
          "example": "initializeNDArray(1, 3); // [1,1,1]\ninitializeNDArray(5, 2, 2, 2); // [[[5,5],[5,5]],[[5,5],[5,5]]]"
        },
        "tags": [
          "array",
          "recursion",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "029121e79e5690c63a06bab363cd71f0c0b44fc5ac13d442b7e1103efe113cdd"
      }
    },
    {
      "id": "inRange",
      "type": "snippet",
      "attributes": {
        "fileName": "inRange.md",
        "text": "Checks if the given number falls within the given range.\n\nUse arithmetic comparison to check if the given number is in the specified range.\nIf the second parameter, `end`, is not specified, the range is considered to be from `0` to `start`.",
        "codeBlocks": {
          "es6": "const inRange = (n, start, end = null) => {\n  if (end && start > end) [end, start] = [start, end];\n  return end == null ? n >= 0 && n < start : n >= start && n < end;\n};",
          "es5": "var inRange = function inRange(n, start) {\n  var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;\n\n  if (end && start > end) {\n    var _ref = [start, end];\n    end = _ref[0];\n    start = _ref[1];\n  }\n\n  return end == null ? n >= 0 && n < start : n >= start && n < end;\n};",
          "example": "inRange(3, 2, 5); // true\ninRange(3, 4); // true\ninRange(2, 3, 5); // false\ninRange(3, 2); // false"
        },
        "tags": [
          "math",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "cb00d1c23e02506fc968515ce8c18dcec8837d447cd47a99f73777574308fb49"
      }
    },
    {
      "id": "insertAfter",
      "type": "snippet",
      "attributes": {
        "fileName": "insertAfter.md",
        "text": "Inserts an HTML string after the end of the specified element.\n\nUse `el.insertAdjacentHTML()` with a position of `'afterend'` to parse `htmlString` and insert it after the end of `el`.",
        "codeBlocks": {
          "es6": "const insertAfter = (el, htmlString) => el.insertAdjacentHTML('afterend', htmlString);",
          "es5": "var insertAfter = function insertAfter(el, htmlString) {\n  return el.insertAdjacentHTML('afterend', htmlString);\n};",
          "example": "insertAfter(document.getElementById('myId'), '<p>after</p>'); // <div id=\"myId\">...</div> <p>after</p>"
        },
        "tags": [
          "browser",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "6fb50a82d884c18e13fce553a0027ab6816697d3be1dd4c5e22d0c8f833744bf"
      }
    },
    {
      "id": "insertBefore",
      "type": "snippet",
      "attributes": {
        "fileName": "insertBefore.md",
        "text": "Inserts an HTML string before the start of the specified element.\n\nUse `el.insertAdjacentHTML()` with a position of `'beforebegin'` to parse `htmlString` and insert it before the start of `el`.",
        "codeBlocks": {
          "es6": "const insertBefore = (el, htmlString) => el.insertAdjacentHTML('beforebegin', htmlString);",
          "es5": "var insertBefore = function insertBefore(el, htmlString) {\n  return el.insertAdjacentHTML('beforebegin', htmlString);\n};",
          "example": "insertBefore(document.getElementById('myId'), '<p>before</p>'); // <p>before</p> <div id=\"myId\">...</div>"
        },
        "tags": [
          "browser",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "bd45d57d669eeecd55bb507ab12c09839dc35ee90f99bcc182dae0a41649a19d"
      }
    },
    {
      "id": "intersection",
      "type": "snippet",
      "attributes": {
        "fileName": "intersection.md",
        "text": "Returns a list of elements that exist in both arrays.\n\nCreate a `Set` from `b`, then use `Array.prototype.filter()` on `a` to only keep values contained in `b`.",
        "codeBlocks": {
          "es6": "const intersection = (a, b) => {\n  const s = new Set(b);\n  return a.filter(x => s.has(x));\n};",
          "es5": "var intersection = function intersection(a, b) {\n  var s = new Set(b);\n  return a.filter(function (x) {\n    return s.has(x);\n  });\n};",
          "example": "intersection([1, 2, 3], [4, 3, 2]); // [2, 3]"
        },
        "tags": [
          "array",
          "math",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "42ad71d6d0ee0fc1ab7b29ba38f2ecce382f811e44b7557e7cc53f49d61596a0"
      }
    },
    {
      "id": "intersectionBy",
      "type": "snippet",
      "attributes": {
        "fileName": "intersectionBy.md",
        "text": "Returns a list of elements that exist in both arrays, after applying the provided function to each array element of both.\n\nCreate a `Set` by applying `fn` to all elements in `b`, then use `Array.prototype.filter()` on `a` to only keep elements, which produce values contained in `b` when `fn` is applied to them.",
        "codeBlocks": {
          "es6": "const intersectionBy = (a, b, fn) => {\n  const s = new Set(b.map(fn));\n  return a.filter(x => s.has(fn(x)));\n};",
          "es5": "var intersectionBy = function intersectionBy(a, b, fn) {\n  var s = new Set(b.map(fn));\n  return a.filter(function (x) {\n    return s.has(fn(x));\n  });\n};",
          "example": "intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [2.1]"
        },
        "tags": [
          "array",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "9b88b7b1786c6d7b7c2e1de6c89019feb07fea89f8a17f082c18357cac67abc9"
      }
    },
    {
      "id": "intersectionWith",
      "type": "snippet",
      "attributes": {
        "fileName": "intersectionWith.md",
        "text": "Returns a list of elements that exist in both arrays, using a provided comparator function.\n\nUse `Array.prototype.filter()` and `Array.prototype.findIndex()` in combination with the provided comparator to determine intersecting values.",
        "codeBlocks": {
          "es6": "const intersectionWith = (a, b, comp) => a.filter(x => b.findIndex(y => comp(x, y)) !== -1);",
          "es5": "var intersectionWith = function intersectionWith(a, b, comp) {\n  return a.filter(function (x) {\n    return b.findIndex(function (y) {\n      return comp(x, y);\n    }) !== -1;\n  });\n};",
          "example": "intersectionWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0, 3.9], (a, b) => Math.round(a) === Math.round(b)); // [1.5, 3, 0]"
        },
        "tags": [
          "array",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "43f99f032f4c3d1b685d3ca05b76e4c4857168cf7b94f93454421d328bf8aaa2"
      }
    },
    {
      "id": "invertKeyValues",
      "type": "snippet",
      "attributes": {
        "fileName": "invertKeyValues.md",
        "text": "Inverts the key-value pairs of an object, without mutating it. The corresponding inverted value of each inverted key is an array of keys responsible for generating the inverted value. If a function is supplied, it is applied to each inverted key.\n\nUse `Object.keys()` and `Array.prototype.reduce()` to invert the key-value pairs of an object and apply the function provided (if any).\nOmit the second argument, `fn`, to get the inverted keys without applying a function to them.",
        "codeBlocks": {
          "es6": "const invertKeyValues = (obj, fn) =>\n  Object.keys(obj).reduce((acc, key) => {\n    const val = fn ? fn(obj[key]) : obj[key];\n    acc[val] = acc[val] || [];\n    acc[val].push(key);\n    return acc;\n  }, {});",
          "es5": "var invertKeyValues = function invertKeyValues(obj, fn) {\n  return Object.keys(obj).reduce(function (acc, key) {\n    var val = fn ? fn(obj[key]) : obj[key];\n    acc[val] = acc[val] || [];\n    acc[val].push(key);\n    return acc;\n  }, {});\n};",
          "example": "invertKeyValues({ a: 1, b: 2, c: 1 }); // { 1: [ 'a', 'c' ], 2: [ 'b' ] }\ninvertKeyValues({ a: 1, b: 2, c: 1 }, value => 'group' + value); // { group1: [ 'a', 'c' ], group2: [ 'b' ] }"
        },
        "tags": [
          "object",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "ecbcab22d1ee4d676863be930fadc0396b8688def0a782e8fb3fec98aac436a4"
      }
    },
    {
      "id": "is",
      "type": "snippet",
      "attributes": {
        "fileName": "is.md",
        "text": "Checks if the provided value is of the specified type.\n\nEnsure the value is not `undefined` or `null` using `Array.prototype.includes()`, and compare the `constructor` property on the value with `type` to check if the provided value is of the specified `type`.",
        "codeBlocks": {
          "es6": "const is = (type, val) => ![, null].includes(val) && val.constructor === type;",
          "es5": "var is = function is(type, val) {\n  return ![, null].includes(val) && val.constructor === type;\n};",
          "example": "is(Array, [1]); // true\nis(ArrayBuffer, new ArrayBuffer()); // true\nis(Map, new Map()); // true\nis(RegExp, /./g); // true\nis(Set, new Set()); // true\nis(WeakMap, new WeakMap()); // true\nis(WeakSet, new WeakSet()); // true\nis(String, ''); // true\nis(String, new String('')); // true\nis(Number, 1); // true\nis(Number, new Number(1)); // true\nis(Boolean, true); // true\nis(Boolean, new Boolean(true)); // true"
        },
        "tags": [
          "type",
          "array",
          "regexp",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "06baccfa0f48458c6d2eb043960851545f3c358f50c4687c2d570676d73f42a9"
      }
    },
    {
      "id": "isAbsoluteURL",
      "type": "snippet",
      "attributes": {
        "fileName": "isAbsoluteURL.md",
        "text": "Returns `true` if the given string is an absolute URL, `false` otherwise.\n\nUse a regular expression to test if the string is an absolute URL.",
        "codeBlocks": {
          "es6": "const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);",
          "es5": "var isAbsoluteURL = function isAbsoluteURL(str) {\n  return /^[a-z][a-z0-9+.-]*:/.test(str);\n};",
          "example": "isAbsoluteURL('https://google.com'); // true\nisAbsoluteURL('ftp://www.myserver.net'); // true\nisAbsoluteURL('/foo/bar'); // false"
        },
        "tags": [
          "string",
          "utility",
          "browser",
          "url",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "74e18a4c018b09d172b04daec6aeab29297b83986bb846028fc20ab1300c84a5"
      }
    },
    {
      "id": "isAfterDate",
      "type": "snippet",
      "attributes": {
        "fileName": "isAfterDate.md",
        "text": "Check if a date is after another date.\n\nUse the greater than operator (`>`) to check if the first date comes after the second one.",
        "codeBlocks": {
          "es6": "const isAfterDate = (dateA, dateB) => dateA > dateB;",
          "es5": "var isAfterDate = function isAfterDate(dateA, dateB) {\n  return dateA > dateB;\n};",
          "example": "isAfterDate(new Date(2010, 10, 21), new Date(2010, 10, 20)); // true"
        },
        "tags": [
          "date",
          "utility",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "78974cc479b0d3a51b7795c5679cbab9601cdd90716a69947799ebe302a7d515"
      }
    },
    {
      "id": "isAnagram",
      "type": "snippet",
      "attributes": {
        "fileName": "isAnagram.md",
        "text": "Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters).\n\nUse `String.toLowerCase()`, `String.prototype.replace()` with an appropriate regular expression to remove unnecessary characters, `String.prototype.split('')`, `Array.prototype.sort()` and `Array.prototype.join('')` on both strings to normalize them, then check if their normalized forms are equal.",
        "codeBlocks": {
          "es6": "const isAnagram = (str1, str2) => {\n  const normalize = str =>\n    str\n      .toLowerCase()\n      .replace(/[^a-z0-9]/gi, '')\n      .split('')\n      .sort()\n      .join('');\n  return normalize(str1) === normalize(str2);\n};",
          "es5": "var isAnagram = function isAnagram(str1, str2) {\n  var normalize = function normalize(str) {\n    return str.toLowerCase().replace(/[^a-z0-9]/gi, '').split('').sort().join('');\n  };\n\n  return normalize(str1) === normalize(str2);\n};",
          "example": "isAnagram('iceman', 'cinema'); // true"
        },
        "tags": [
          "string",
          "regexp",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "9404ec22658a648e7b7bcf314b764e4be17e235b14ffdf03654325844fb51005"
      }
    },
    {
      "id": "isArrayLike",
      "type": "snippet",
      "attributes": {
        "fileName": "isArrayLike.md",
        "text": "Checks if the provided argument is array-like (i.e. is iterable).\n\nCheck if the provided argument is not `null` and that its `Symbol.iterator` property is a function.",
        "codeBlocks": {
          "es6": "const isArrayLike = obj => obj != null && typeof obj[Symbol.iterator] === 'function';",
          "es5": "var isArrayLike = function isArrayLike(obj) {\n  return obj != null && typeof obj[Symbol.iterator] === 'function';\n};",
          "example": "isArrayLike(document.querySelectorAll('.className')); // true\nisArrayLike('abc'); // true\nisArrayLike(null); // false"
        },
        "tags": [
          "type",
          "array",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "00b43a2b430d5d9205046ad6fbf7442f0d4507895c82545753253b5b5f97fa3a"
      }
    },
    {
      "id": "isBeforeDate",
      "type": "snippet",
      "attributes": {
        "fileName": "isBeforeDate.md",
        "text": "Check if a date is before another date.\n\nUse the less than operator (`<`) to check if the first date comes before the second one.",
        "codeBlocks": {
          "es6": "const isBeforeDate = (dateA, dateB) => dateA < dateB;",
          "es5": "var isBeforeDate = function isBeforeDate(dateA, dateB) {\n  return dateA < dateB;\n};",
          "example": "isBeforeDate(new Date(2010, 10, 20), new Date(2010, 10, 21)); // true"
        },
        "tags": [
          "date",
          "utility",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "947340a879922379186ddecda22c625bc4db21948dc619e445abd95da21d0a1c"
      }
    },
    {
      "id": "isBoolean",
      "type": "snippet",
      "attributes": {
        "fileName": "isBoolean.md",
        "text": "Checks if the given argument is a native boolean element.\n\nUse `typeof` to check if a value is classified as a boolean primitive.",
        "codeBlocks": {
          "es6": "const isBoolean = val => typeof val === 'boolean';",
          "es5": "var isBoolean = function isBoolean(val) {\n  return typeof val === 'boolean';\n};",
          "example": "isBoolean(null); // false\nisBoolean(false); // true"
        },
        "tags": [
          "type",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "e1adac3af11702cb65c30ecaf573659d215b3e2c2b5825e9993d36d889c5fd52"
      }
    },
    {
      "id": "isBrowser",
      "type": "snippet",
      "attributes": {
        "fileName": "isBrowser.md",
        "text": "Determines if the current runtime environment is a browser so that front-end modules can run on the server (Node) without throwing errors.\n\nUse `Array.prototype.includes()` on the `typeof` values of both `window` and `document` (globals usually only available in a browser environment unless they were explicitly defined), which will return `true` if one of them is `undefined`.\n`typeof` allows globals to be checked for existence without throwing a `ReferenceError`.\nIf both of them are not `undefined`, then the current environment is assumed to be a browser.",
        "codeBlocks": {
          "es6": "const isBrowser = () => ![typeof window, typeof document].includes('undefined');",
          "es5": "function _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nvar isBrowser = function isBrowser() {\n  return ![typeof window === \"undefined\" ? \"undefined\" : _typeof(window), typeof document === \"undefined\" ? \"undefined\" : _typeof(document)].includes('undefined');\n};",
          "example": "isBrowser(); // true (browser)\nisBrowser(); // false (Node)"
        },
        "tags": [
          "utility",
          "browser",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "0f9f606715fd96c8dc80df73bf8f19ae808ae0318b6c332f09ccd01cfb37fef9"
      }
    },
    {
      "id": "isBrowserTabFocused",
      "type": "snippet",
      "attributes": {
        "fileName": "isBrowserTabFocused.md",
        "text": "Returns `true` if the browser tab of the page is focused, `false` otherwise.\n\nUse the `Document.hidden` property, introduced by the Page Visibility API to check if the browser tab of the page is visible or hidden.",
        "codeBlocks": {
          "es6": "const isBrowserTabFocused = () => !document.hidden;",
          "es5": "var isBrowserTabFocused = function isBrowserTabFocused() {\n  return !document.hidden;\n};",
          "example": "isBrowserTabFocused(); // true"
        },
        "tags": [
          "browser",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "af819966e11f4832bfc0129d1d0e148fa0157775d9a07d26f4c17f7096c6a176"
      }
    },
    {
      "id": "isDivisible",
      "type": "snippet",
      "attributes": {
        "fileName": "isDivisible.md",
        "text": "Checks if the first numeric argument is divisible by the second one.\n\nUse the modulo operator (`%`) to check if the remainder is equal to `0`.",
        "codeBlocks": {
          "es6": "const isDivisible = (dividend, divisor) => dividend % divisor === 0;",
          "es5": "var isDivisible = function isDivisible(dividend, divisor) {\n  return dividend % divisor === 0;\n};",
          "example": "isDivisible(6, 3); // true"
        },
        "tags": [
          "math",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "660aff9a5f540384603a2ab18d24e933b37e71972bd6bbc708b7bfb77ac13a50"
      }
    },
    {
      "id": "isDuplexStream",
      "type": "snippet",
      "attributes": {
        "fileName": "isDuplexStream.md",
        "text": "Checks if the given argument is a duplex (readable and writable) stream.\n\nCheck if the value is different from `null`, use `typeof` to check if a value is of type `object` and the `pipe` property is of type `function`.\nAdditionally check if the `typeof` the `_read`, `_write` and `_readableState`, `_writableState` properties are `function` and `object` respectively.",
        "codeBlocks": {
          "es6": "const isDuplexStream = val =>\n  val !== null &&\n  typeof val === 'object' &&\n  typeof val.pipe === 'function' &&\n  typeof val._read === 'function' &&\n  typeof val._readableState === 'object' &&\n  typeof val._write === 'function' &&\n  typeof val._writableState === 'object';",
          "es5": "function _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nvar isDuplexStream = function isDuplexStream(val) {\n  return val !== null && _typeof(val) === 'object' && typeof val.pipe === 'function' && typeof val._read === 'function' && _typeof(val._readableState) === 'object' && typeof val._write === 'function' && _typeof(val._writableState) === 'object';\n};",
          "example": "const Stream = require('stream');\nisDuplexStream(new Stream.Duplex()); // true"
        },
        "tags": [
          "node",
          "type",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "b774dbb0eb7647839be1b680627c1890fa4e1dee70b1a627fc6a1c9c0e9f3415"
      }
    },
    {
      "id": "isEmpty",
      "type": "snippet",
      "attributes": {
        "fileName": "isEmpty.md",
        "text": "Returns true if the a value is an empty object, collection, map or set, has no enumerable properties or is any type that is not considered a collection.\n\nCheck if the provided value is `null` or if its `length` is equal to `0`.",
        "codeBlocks": {
          "es6": "const isEmpty = val => val == null || !(Object.keys(val) || val).length;",
          "es5": "var isEmpty = function isEmpty(val) {\n  return val == null || !(Object.keys(val) || val).length;\n};",
          "example": "isEmpty(new Map()); // true\nisEmpty(new Set()); // true\nisEmpty([]); // true\nisEmpty({}); // true\nisEmpty(''); // true\nisEmpty([1, 2]); // false\nisEmpty({ a: 1, b: 2 }); // false\nisEmpty('text'); // false\nisEmpty(123); // true - type is not considered a collection\nisEmpty(true); // true - type is not considered a collection"
        },
        "tags": [
          "type",
          "array",
          "object",
          "string",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "55954fcfb879542225f7d1861ae7de6faac288e28ca857367b6a2eeba9a54786"
      }
    },
    {
      "id": "isEven",
      "type": "snippet",
      "attributes": {
        "fileName": "isEven.md",
        "text": "Returns `true` if the given number is even, `false` otherwise.\n\nChecks whether a number is odd or even using the modulo (`%`) operator.\nReturns `true` if the number is even, `false` if the number is odd.",
        "codeBlocks": {
          "es6": "const isEven = num => num % 2 === 0;",
          "es5": "var isEven = function isEven(num) {\n  return num % 2 === 0;\n};",
          "example": "isEven(3); // false"
        },
        "tags": [
          "math",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "1c88249edc75925e83e8a4abc28f300c27bf9be1440bcc30b1b798b7d7ea8596"
      }
    },
    {
      "id": "isFunction",
      "type": "snippet",
      "attributes": {
        "fileName": "isFunction.md",
        "text": "Checks if the given argument is a function.\n\nUse `typeof` to check if a value is classified as a function primitive.",
        "codeBlocks": {
          "es6": "const isFunction = val => typeof val === 'function';",
          "es5": "var isFunction = function isFunction(val) {\n  return typeof val === 'function';\n};",
          "example": "isFunction('x'); // false\nisFunction(x => x); // true"
        },
        "tags": [
          "type",
          "function",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "22009c1df55cca53bc9b227d4f8f2e3d475abe5f5eecfbf9ab3cb30948c9d783"
      }
    },
    {
      "id": "isLowerCase",
      "type": "snippet",
      "attributes": {
        "fileName": "isLowerCase.md",
        "text": "Checks if a string is lower case.\n\nConvert the given string to lower case, using `String.toLowerCase()` and compare it to the original.",
        "codeBlocks": {
          "es6": "const isLowerCase = str => str === str.toLowerCase();",
          "es5": "var isLowerCase = function isLowerCase(str) {\n  return str === str.toLowerCase();\n};",
          "example": "isLowerCase('abc'); // true\nisLowerCase('a3@$'); // true\nisLowerCase('Ab4'); // false"
        },
        "tags": [
          "string",
          "utility",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "e23c295c6c1d85cbeae2cfad15be98d3d8093ba59266f14af7dc47d19a68f43b"
      }
    },
    {
      "id": "isNil",
      "type": "snippet",
      "attributes": {
        "fileName": "isNil.md",
        "text": "Returns `true` if the specified value is `null` or `undefined`, `false` otherwise.\n\nUse the strict equality operator to check if the value and of `val` are equal to `null` or `undefined`.",
        "codeBlocks": {
          "es6": "const isNil = val => val === undefined || val === null;",
          "es5": "var isNil = function isNil(val) {\n  return val === undefined || val === null;\n};",
          "example": "isNil(null); // true\nisNil(undefined); // true"
        },
        "tags": [
          "type",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "8a0c679926f99b1f710ad093e3ca2ae845eea383740b4aa655e2e3beb99472ca"
      }
    },
    {
      "id": "isNull",
      "type": "snippet",
      "attributes": {
        "fileName": "isNull.md",
        "text": "Returns `true` if the specified value is `null`, `false` otherwise.\n\nUse the strict equality operator to check if the value and of `val` are equal to `null`.",
        "codeBlocks": {
          "es6": "const isNull = val => val === null;",
          "es5": "var isNull = function isNull(val) {\n  return val === null;\n};",
          "example": "isNull(null); // true"
        },
        "tags": [
          "type",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "e38f39701757feb6e2515736d446b2de580f19c77f9eaacb5d0d5b3e787209f8"
      }
    },
    {
      "id": "isNumber",
      "type": "snippet",
      "attributes": {
        "fileName": "isNumber.md",
        "text": "Checks if the given argument is a number.\n\nUse `typeof` to check if a value is classified as a number primitive.",
        "codeBlocks": {
          "es6": "const isNumber = val => typeof val === 'number';",
          "es5": "var isNumber = function isNumber(val) {\n  return typeof val === 'number';\n};",
          "example": "isNumber('1'); // false\nisNumber(1); // true"
        },
        "tags": [
          "type",
          "math",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "446ed50e100f18a606c8443be196992b74b235ed98646632463fdc3d01f9eb04"
      }
    },
    {
      "id": "isObject",
      "type": "snippet",
      "attributes": {
        "fileName": "isObject.md",
        "text": "Returns a boolean determining if the passed value is an object or not.\n\nUses the  `Object` constructor to create an object wrapper for the given value. \nIf the value is `null` or `undefined`, create and return an empty object. Οtherwise, return an object of a type that corresponds to the given value.",
        "codeBlocks": {
          "es6": "const isObject = obj => obj === Object(obj);",
          "es5": "var isObject = function isObject(obj) {\n  return obj === Object(obj);\n};",
          "example": "isObject([1, 2, 3, 4]); // true\nisObject([]); // true\nisObject(['Hello!']); // true\nisObject({ a: 1 }); // true\nisObject({}); // true\nisObject(true); // false"
        },
        "tags": [
          "type",
          "object",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "64de55a580b3db52f79f2bc3168e312d4087891216853e51f8585e30c6eb3d3d"
      }
    },
    {
      "id": "isObjectLike",
      "type": "snippet",
      "attributes": {
        "fileName": "isObjectLike.md",
        "text": "Checks if a value is object-like.\n\nCheck if the provided value is not `null` and its `typeof` is equal to `'object'`.",
        "codeBlocks": {
          "es6": "const isObjectLike = val => val !== null && typeof val === 'object';",
          "es5": "function _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nvar isObjectLike = function isObjectLike(val) {\n  return val !== null && _typeof(val) === 'object';\n};",
          "example": "isObjectLike({}); // true\nisObjectLike([1, 2, 3]); // true\nisObjectLike(x => x); // false\nisObjectLike(null); // false"
        },
        "tags": [
          "type",
          "object",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "5388bdd5320b8b68511c1a6b77683e8320177a9c6561e5e952a60193c1b73844"
      }
    },
    {
      "id": "isPlainObject",
      "type": "snippet",
      "attributes": {
        "fileName": "isPlainObject.md",
        "text": "Checks if the provided value is an object created by the Object constructor.\n\nCheck if the provided value is truthy, use `typeof` to check if it is an object and `Object.constructor` to make sure the constructor is equal to `Object`.",
        "codeBlocks": {
          "es6": "const isPlainObject = val => !!val && typeof val === 'object' && val.constructor === Object;",
          "es5": "function _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nvar isPlainObject = function isPlainObject(val) {\n  return !!val && _typeof(val) === 'object' && val.constructor === Object;\n};",
          "example": "isPlainObject({ a: 1 }); // true\nisPlainObject(new Map()); // false"
        },
        "tags": [
          "type",
          "object",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "f57c53ec6964e15510cd9bf9ad53429721c6a6547b59bd302ebcbc4cd19557ea"
      }
    },
    {
      "id": "isPrime",
      "type": "snippet",
      "attributes": {
        "fileName": "isPrime.md",
        "text": "Checks if the provided integer is a prime number.\n\nCheck numbers from `2` to the square root of the given number.\nReturn `false` if any of them divides the given number, else return `true`, unless the number is less than `2`.",
        "codeBlocks": {
          "es6": "const isPrime = num => {\n  const boundary = Math.floor(Math.sqrt(num));\n  for (var i = 2; i <= boundary; i++) if (num % i === 0) return false;\n  return num >= 2;\n};",
          "es5": "var isPrime = function isPrime(num) {\n  var boundary = Math.floor(Math.sqrt(num));\n\n  for (var i = 2; i <= boundary; i++) {\n    if (num % i === 0) return false;\n  }\n\n  return num >= 2;\n};",
          "example": "isPrime(11); // true"
        },
        "tags": [
          "math",
          "beginner",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "023b7e9fded22fad9cd776f01c60c8238236cb2921523d7d612034bb465cba7d"
      }
    },
    {
      "id": "isPrimitive",
      "type": "snippet",
      "attributes": {
        "fileName": "isPrimitive.md",
        "text": "Returns a boolean determining if the passed value is primitive or not.\n\nCreate an object from `val` and compare it with `val` to determine if the passed value is primitive (i.e. not equal to the created object).",
        "codeBlocks": {
          "es6": "const isPrimitive = val => Object(val) !== val;",
          "es5": "var isPrimitive = function isPrimitive(val) {\n  return Object(val) !== val;\n};",
          "example": "isPrimitive(null); // true\nisPrimitive(50); // true\nisPrimitive('Hello!'); // true\nisPrimitive(false); // true\nisPrimitive(Symbol()); // true\nisPrimitive([]); // false"
        },
        "tags": [
          "type",
          "function",
          "array",
          "string",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "c7d8ae1c152c6e7aa21c893d9bc3b581007004e88e4a77df0695a3b957c3d2a0"
      }
    },
    {
      "id": "isPromiseLike",
      "type": "snippet",
      "attributes": {
        "fileName": "isPromiseLike.md",
        "text": "Returns `true` if an object looks like a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), `false` otherwise.\n\nCheck if the object is not `null`, its `typeof` matches either `object` or `function` and if it has a `.then` property, which is also a `function`.",
        "codeBlocks": {
          "es6": "const isPromiseLike = obj =>\n  obj !== null &&\n  (typeof obj === 'object' || typeof obj === 'function') &&\n  typeof obj.then === 'function';",
          "es5": "function _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nvar isPromiseLike = function isPromiseLike(obj) {\n  return obj !== null && (_typeof(obj) === 'object' || typeof obj === 'function') && typeof obj.then === 'function';\n};",
          "example": "isPromiseLike({\n  then: function() {\n    return '';\n  }\n}); // true\nisPromiseLike(null); // false\nisPromiseLike({}); // false"
        },
        "tags": [
          "type",
          "function",
          "promise",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "fa8bfc91bfa09eb76f7131c3cc7b890598f8a30ec9e9872f7ffd9c282d37ba72"
      }
    },
    {
      "id": "isReadableStream",
      "type": "snippet",
      "attributes": {
        "fileName": "isReadableStream.md",
        "text": "Checks if the given argument is a readable stream.\n\nCheck if the value is different from `null`, use `typeof` to check if the value is of type `object` and the `pipe` property is of type `function`.\nAdditionally check if the `typeof` the `_read` and `_readableState` properties are `function` and `object` respectively.",
        "codeBlocks": {
          "es6": "const isReadableStream = val =>\n  val !== null &&\n  typeof val === 'object' &&\n  typeof val.pipe === 'function' &&\n  typeof val._read === 'function' &&\n  typeof val._readableState === 'object';",
          "es5": "function _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nvar isReadableStream = function isReadableStream(val) {\n  return val !== null && _typeof(val) === 'object' && typeof val.pipe === 'function' && typeof val._read === 'function' && _typeof(val._readableState) === 'object';\n};",
          "example": "const fs = require('fs');\nisReadableStream(fs.createReadStream('test.txt')); // true"
        },
        "tags": [
          "node",
          "type",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "80e8196a7d4a8b335b30d050608b3d901178ba931ce1e51b7f44a9991a53b825"
      }
    },
    {
      "id": "isSameDate",
      "type": "snippet",
      "attributes": {
        "fileName": "isSameDate.md",
        "text": "Check if a date is the same as another date.\n\nUse `Date.prototype.toISOString()` and strict equality checking (`===`) to check if the first date is the same as the second one.",
        "codeBlocks": {
          "es6": "const isSameDate = (dateA, dateB) => dateA.toISOString() === dateB.toISOString();",
          "es5": "var isSameDate = function isSameDate(dateA, dateB) {\n  return dateA.toISOString() === dateB.toISOString();\n};",
          "example": "isSameDate(new Date(2010, 10, 20), new Date(2010, 10, 20)); // true"
        },
        "tags": [
          "date",
          "utility",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "a57a8fe6a89b45bd11bcfeb71321839b5ae9c6a3789dfc6670be4a71d705f703"
      }
    },
    {
      "id": "isSorted",
      "type": "snippet",
      "attributes": {
        "fileName": "isSorted.md",
        "text": "Returns `1` if the array is sorted in ascending order, `-1` if it is sorted in descending order or `0` if it is not sorted.\n\nCalculate the ordering `direction` for the first two elements.\nUse `Object.entries()` to loop over array objects and compare them in pairs.\nReturn `0` if the `direction` changes or the `direction` if the last element is reached.",
        "codeBlocks": {
          "es6": "const isSorted = arr => {\n  let direction = -(arr[0] - arr[1]);\n  for (let [i, val] of arr.entries()) {\n    direction = !direction ? -(arr[i - 1] - arr[i]) : direction;\n    if (i === arr.length - 1) return !direction ? 0 : direction;\n    else if ((val - arr[i + 1]) * direction > 0) return 0;\n  }\n};",
          "es5": "function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }\n\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance\"); }\n\nfunction _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i[\"return\"] != null) _i[\"return\"](); } finally { if (_d) throw _e; } } return _arr; }\n\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n\nvar isSorted = function isSorted(arr) {\n  var direction = -(arr[0] - arr[1]);\n  var _iteratorNormalCompletion = true;\n  var _didIteratorError = false;\n  var _iteratorError = undefined;\n\n  try {\n    for (var _iterator = arr.entries()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n      var _step$value = _slicedToArray(_step.value, 2),\n          i = _step$value[0],\n          val = _step$value[1];\n\n      direction = !direction ? -(arr[i - 1] - arr[i]) : direction;\n      if (i === arr.length - 1) return !direction ? 0 : direction;else if ((val - arr[i + 1]) * direction > 0) return 0;\n    }\n  } catch (err) {\n    _didIteratorError = true;\n    _iteratorError = err;\n  } finally {\n    try {\n      if (!_iteratorNormalCompletion && _iterator.return != null) {\n        _iterator.return();\n      }\n    } finally {\n      if (_didIteratorError) {\n        throw _iteratorError;\n      }\n    }\n  }\n};",
          "example": "isSorted([0, 1, 2, 2]); // 1\nisSorted([4, 3, 2]); // -1\nisSorted([4, 3, 5]); // 0"
        },
        "tags": [
          "array",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "2dfe9101a9ab2945ffddb46ecbca0fdd5dea384683d310e8adb852ac9c51970f"
      }
    },
    {
      "id": "isStream",
      "type": "snippet",
      "attributes": {
        "fileName": "isStream.md",
        "text": "Checks if the given argument is a stream.\n\nCheck if the value is different from `null`, use `typeof` to check if the value is of type `object` and the `pipe` property is of type `function`.",
        "codeBlocks": {
          "es6": "const isStream = val => val !== null && typeof val === 'object' && typeof val.pipe === 'function';",
          "es5": "function _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nvar isStream = function isStream(val) {\n  return val !== null && _typeof(val) === 'object' && typeof val.pipe === 'function';\n};",
          "example": "const fs = require('fs');\nisStream(fs.createReadStream('test.txt')); // true"
        },
        "tags": [
          "node",
          "type",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "926ac2fcee035747468a7dd0bbb57074b33242a2b65eff839b5b4ed47c6341e3"
      }
    },
    {
      "id": "isString",
      "type": "snippet",
      "attributes": {
        "fileName": "isString.md",
        "text": "Checks if the given argument is a string. Only works for string primitives.\n\nUse `typeof` to check if a value is classified as a string primitive.",
        "codeBlocks": {
          "es6": "const isString = val => typeof val === 'string';",
          "es5": "var isString = function isString(val) {\n  return typeof val === 'string';\n};",
          "example": "isString('10'); // true"
        },
        "tags": [
          "type",
          "string",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "8cb7af2bd0a103563eee4e09266219630bf50c22048ad243d9456a24277ba615"
      }
    },
    {
      "id": "isSymbol",
      "type": "snippet",
      "attributes": {
        "fileName": "isSymbol.md",
        "text": "Checks if the given argument is a symbol.\n\nUse `typeof` to check if a value is classified as a symbol primitive.",
        "codeBlocks": {
          "es6": "const isSymbol = val => typeof val === 'symbol';",
          "es5": "function _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nvar isSymbol = function isSymbol(val) {\n  return _typeof(val) === 'symbol';\n};",
          "example": "isSymbol(Symbol('x')); // true"
        },
        "tags": [
          "type",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "680fe44539f63a13c6586153e9ffdddd2a9a9b83c2736a69eaf5fe24080675e3"
      }
    },
    {
      "id": "isTravisCI",
      "type": "snippet",
      "attributes": {
        "fileName": "isTravisCI.md",
        "text": "Checks if the current environment is [Travis CI](https://travis-ci.org/).\n\nChecks if the current environment has the `TRAVIS` and `CI` environment variables ([reference](https://docs.travis-ci.com/user/environment-variables/#Default-Environment-Variables)).",
        "codeBlocks": {
          "es6": "const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env;",
          "es5": "var isTravisCI = function isTravisCI() {\n  return 'TRAVIS' in process.env && 'CI' in process.env;\n};",
          "example": "isTravisCI(); // true (if code is running on Travis CI)"
        },
        "tags": [
          "node",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "1528bcadc4afcb7240a9f5d53b49243d512d8c98814b3fe841889d0772ad2030"
      }
    },
    {
      "id": "isUndefined",
      "type": "snippet",
      "attributes": {
        "fileName": "isUndefined.md",
        "text": "Returns `true` if the specified value is `undefined`, `false` otherwise.\n\nUse the strict equality operator to check if the value and of `val` are equal to `undefined`.",
        "codeBlocks": {
          "es6": "const isUndefined = val => val === undefined;",
          "es5": "var isUndefined = function isUndefined(val) {\n  return val === undefined;\n};",
          "example": "isUndefined(undefined); // true"
        },
        "tags": [
          "type",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "00eca9d29a66b8b8cee4b059a88bdae8f60cdc557cdff52817edd811cde5281b"
      }
    },
    {
      "id": "isUpperCase",
      "type": "snippet",
      "attributes": {
        "fileName": "isUpperCase.md",
        "text": "Checks if a string is upper case.\n\nConvert the given string to upper case, using `String.prototype.toUpperCase()` and compare it to the original.",
        "codeBlocks": {
          "es6": "const isUpperCase = str => str === str.toUpperCase();",
          "es5": "var isUpperCase = function isUpperCase(str) {\n  return str === str.toUpperCase();\n};",
          "example": "isUpperCase('ABC'); // true\nisLowerCase('A3@$'); // true\nisLowerCase('aB4'); // false"
        },
        "tags": [
          "string",
          "utility",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "626f56d793d107522067c92edce730bca0d33fb5a8095ac9396b4eb374fddd29"
      }
    },
    {
      "id": "isValidJSON",
      "type": "snippet",
      "attributes": {
        "fileName": "isValidJSON.md",
        "text": "Checks if the provided argument is a valid JSON.\n\nUse `JSON.parse()` and a `try... catch` block to check if the provided argument is a valid JSON.",
        "codeBlocks": {
          "es6": "const isValidJSON = obj => {\n  try {\n    JSON.parse(obj);\n    return true;\n  } catch (e) {\n    return false;\n  }\n};",
          "es5": "var isValidJSON = function isValidJSON(obj) {\n  try {\n    JSON.parse(obj);\n    return true;\n  } catch (e) {\n    return false;\n  }\n};",
          "example": "isValidJSON('{\"name\":\"Adam\",\"age\":20}'); // true\nisValidJSON('{\"name\":\"Adam\",age:\"20\"}'); // false\nisValidJSON(null); // true"
        },
        "tags": [
          "type",
          "json",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "b4417a972f391836241e88587797a8cd995f32ee71fbfcfe9e590c8fa8675558"
      }
    },
    {
      "id": "isWritableStream",
      "type": "snippet",
      "attributes": {
        "fileName": "isWritableStream.md",
        "text": "Checks if the given argument is a writable stream.\n\nCheck if the value is different from `null`, use `typeof` to check if the value is of type `object` and the `pipe` property is of type `function`.\nAdditionally check if the `typeof` the `_write` and `_writableState` properties are `function` and `object` respectively.",
        "codeBlocks": {
          "es6": "const isWritableStream = val =>\n  val !== null &&\n  typeof val === 'object' &&\n  typeof val.pipe === 'function' &&\n  typeof val._write === 'function' &&\n  typeof val._writableState === 'object';",
          "es5": "function _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nvar isWritableStream = function isWritableStream(val) {\n  return val !== null && _typeof(val) === 'object' && typeof val.pipe === 'function' && typeof val._write === 'function' && _typeof(val._writableState) === 'object';\n};",
          "example": "const fs = require('fs');\nisWritableStream(fs.createWriteStream('test.txt')); // true"
        },
        "tags": [
          "node",
          "type",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "8334e570a144bb5cb8cf971d734b15c70b0912c32c3103ff05b0c1ee60e0c353"
      }
    },
    {
      "id": "join",
      "type": "snippet",
      "attributes": {
        "fileName": "join.md",
        "text": "Joins all elements of an array into a string and returns this string.\nUses a separator and an end separator.\n\nUse `Array.prototype.reduce()` to combine elements into a string.\nOmit the second argument, `separator`, to use a default separator of `','`.\nOmit the third argument, `end`, to use the same value as `separator` by default.",
        "codeBlocks": {
          "es6": "const join = (arr, separator = ',', end = separator) =>\n  arr.reduce(\n    (acc, val, i) =>\n      i === arr.length - 2\n        ? acc + val + end\n        : i === arr.length - 1\n          ? acc + val\n          : acc + val + separator,\n    ''\n  );",
          "es5": "var join = function join(arr) {\n  var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ',';\n  var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : separator;\n  return arr.reduce(function (acc, val, i) {\n    return i === arr.length - 2 ? acc + val + end : i === arr.length - 1 ? acc + val : acc + val + separator;\n  }, '');\n};",
          "example": "join(['pen', 'pineapple', 'apple', 'pen'], ',', '&'); // \"pen,pineapple,apple&pen\"\njoin(['pen', 'pineapple', 'apple', 'pen'], ','); // \"pen,pineapple,apple,pen\"\njoin(['pen', 'pineapple', 'apple', 'pen']); // \"pen,pineapple,apple,pen\""
        },
        "tags": [
          "array",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "84003bdeb9bfbac104ba97b07bebb29ed82a84a2e05e1931dc5f5d4c1d336be4"
      }
    },
    {
      "id": "JSONtoCSV",
      "type": "snippet",
      "attributes": {
        "fileName": "JSONtoCSV.md",
        "text": "Converts an array of objects to a comma-separated values (CSV) string that contains only the `columns` specified.\n\nUse `Array.prototype.join(delimiter)` to combine all the names in `columns` to create the first row.\nUse `Array.prototype.map()` and `Array.prototype.reduce()` to create a row for each object, substituting non-existent values with empty strings and only mapping values in `columns`.\nUse `Array.prototype.join('\\n')` to combine all rows into a string.\nOmit the third argument, `delimiter`, to use a default delimiter of `,`.",
        "codeBlocks": {
          "es6": "const JSONtoCSV = (arr, columns, delimiter = ',') =>\n  [\n    columns.join(delimiter),\n    ...arr.map(obj =>\n      columns.reduce(\n        (acc, key) => `${acc}${!acc.length ? '' : delimiter}\"${!obj[key] ? '' : obj[key]}\"`,\n        ''\n      )\n    )\n  ].join('\\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 JSONtoCSV = function JSONtoCSV(arr, columns) {\n  var delimiter = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ',';\n  return [columns.join(delimiter)].concat(_toConsumableArray(arr.map(function (obj) {\n    return columns.reduce(function (acc, key) {\n      return \"\".concat(acc).concat(!acc.length ? '' : delimiter, \"\\\"\").concat(!obj[key] ? '' : obj[key], \"\\\"\");\n    }, '');\n  }))).join('\\n');\n};",
          "example": "JSONtoCSV([{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }], ['a', 'b']); // 'a,b\\n\"1\",\"2\"\\n\"3\",\"4\"\\n\"6\",\"\"\\n\"\",\"7\"'\nJSONtoCSV([{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }], ['a', 'b'], ';'); // 'a;b\\n\"1\";\"2\"\\n\"3\";\"4\"\\n\"6\";\"\"\\n\"\";\"7\"'"
        },
        "tags": [
          "array",
          "string",
          "object",
          "advanced"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "8a9b52f4f29b9c52572e2577cffdf93d00278aa7eb661f8af62625c7652c663c"
      }
    },
    {
      "id": "JSONToFile",
      "type": "snippet",
      "attributes": {
        "fileName": "JSONToFile.md",
        "text": "Writes a JSON object to a file.\n\nUse `fs.writeFile()`, template literals and `JSON.stringify()` to write a `json` object to a `.json` file.",
        "codeBlocks": {
          "es6": "const fs = require('fs');\nconst JSONToFile = (obj, filename) =>\n  fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2));",
          "es5": "var fs = require('fs');\n\nvar JSONToFile = function JSONToFile(obj, filename) {\n  return fs.writeFile(\"\".concat(filename, \".json\"), JSON.stringify(obj, null, 2));\n};",
          "example": "JSONToFile({ test: 'is passed' }, 'testJsonFile'); // writes the object to 'testJsonFile.json'"
        },
        "tags": [
          "node",
          "json",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "1428086b630fa917dbb5a4ecd2854e9371b07244b3968bc3eb3184b4b589ea0c"
      }
    },
    {
      "id": "last",
      "type": "snippet",
      "attributes": {
        "fileName": "last.md",
        "text": "Returns the last element in an array.\n\nUse `arr.length - 1` to compute the index of the last element of the given array and returning it.",
        "codeBlocks": {
          "es6": "const last = arr => arr[arr.length - 1];",
          "es5": "var last = function last(arr) {\n  return arr[arr.length - 1];\n};",
          "example": "last([1, 2, 3]); // 3"
        },
        "tags": [
          "array",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "49eb0b667109a372349e32fbcb809894ed62b5a1a3dab305876b810f8adfef29"
      }
    },
    {
      "id": "lcm",
      "type": "snippet",
      "attributes": {
        "fileName": "lcm.md",
        "text": "Returns the least common multiple of two or more numbers.\n\nUse the greatest common divisor (GCD) formula and the fact that `lcm(x,y) = x * y / gcd(x,y)` to determine the least common multiple.\nThe GCD formula uses recursion.",
        "codeBlocks": {
          "es6": "const lcm = (...arr) => {\n  const gcd = (x, y) => (!y ? x : gcd(y, x % y));\n  const _lcm = (x, y) => (x * y) / gcd(x, y);\n  return [...arr].reduce((a, b) => _lcm(a, b));\n};",
          "es5": "var lcm = function lcm() {\n  var gcd = function gcd(x, y) {\n    return !y ? x : gcd(y, x % y);\n  };\n\n  var _lcm = function _lcm(x, y) {\n    return x * y / gcd(x, y);\n  };\n\n  for (var _len = arguments.length, arr = new Array(_len), _key = 0; _key < _len; _key++) {\n    arr[_key] = arguments[_key];\n  }\n\n  return arr.concat().reduce(function (a, b) {\n    return _lcm(a, b);\n  });\n};",
          "example": "lcm(12, 7); // 84\nlcm(...[1, 3, 4, 5]); // 60"
        },
        "tags": [
          "math",
          "recursion",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "ac4ec1ff763b005ddd65e6ed5bdb49b18a4ce53f8b7ccf79536fa49ebeb6efa8"
      }
    },
    {
      "id": "longestItem",
      "type": "snippet",
      "attributes": {
        "fileName": "longestItem.md",
        "text": "Takes any number of iterable objects or objects with a `length` property and returns the longest one.\nIf multiple objects have the same length, the first one will be returned.\nReturns `undefined` if no arguments are provided.\n\nUse `Array.prototype.reduce()`, comparing the `length` of objects to find the longest one.",
        "codeBlocks": {
          "es6": "const longestItem = (...vals) => vals.reduce((a, x) => (x.length > a.length ? x : a));",
          "es5": "var longestItem = function longestItem() {\n  for (var _len = arguments.length, vals = new Array(_len), _key = 0; _key < _len; _key++) {\n    vals[_key] = arguments[_key];\n  }\n\n  return vals.reduce(function (a, x) {\n    return x.length > a.length ? x : a;\n  });\n};",
          "example": "longestItem('this', 'is', 'a', 'testcase'); // 'testcase'\nlongestItem(...['a', 'ab', 'abc']); // 'abc'\nlongestItem(...['a', 'ab', 'abc'], 'abcd'); // 'abcd'\nlongestItem([1, 2, 3], [1, 2], [1, 2, 3, 4, 5]); // [1, 2, 3, 4, 5]\nlongestItem([1, 2, 3], 'foobar'); // 'foobar'"
        },
        "tags": [
          "array",
          "string",
          "utility",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "0d9421bc8c9374fdb7a62df1212bccf8c5bd1cb4a99cce1ddc87ba7391e66c18"
      }
    },
    {
      "id": "lowercaseKeys",
      "type": "snippet",
      "attributes": {
        "fileName": "lowercaseKeys.md",
        "text": "Creates a new object from the specified object, where all the keys are in lowercase.\n\nUse `Object.keys()` and `Array.prototype.reduce()` to create a new object from the specified object.\nConvert each key in the original object to lowercase, using `String.toLowerCase()`.",
        "codeBlocks": {
          "es6": "const lowercaseKeys = obj =>\n  Object.keys(obj).reduce((acc, key) => {\n    acc[key.toLowerCase()] = obj[key];\n    return acc;\n  }, {});",
          "es5": "var lowercaseKeys = function lowercaseKeys(obj) {\n  return Object.keys(obj).reduce(function (acc, key) {\n    acc[key.toLowerCase()] = obj[key];\n    return acc;\n  }, {});\n};",
          "example": "const myObj = { Name: 'Adam', sUrnAME: 'Smith' };\nconst myObjLower = lowercaseKeys(myObj); // {name: 'Adam', surname: 'Smith'};"
        },
        "tags": [
          "object",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "a9ecbb1256234991b339b6701ca0d45eb02c4698f00f5b6855005751d7a30bd7"
      }
    },
    {
      "id": "luhnCheck",
      "type": "snippet",
      "attributes": {
        "fileName": "luhnCheck.md",
        "text": "Implementation of the [Luhn Algorithm](https://en.wikipedia.org/wiki/Luhn_algorithm) used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers etc.\n\nUse `String.prototype.split('')`, `Array.prototype.reverse()` and `Array.prototype.map()` in combination with `parseInt()` to obtain an array of digits.\nUse `Array.prototype.splice(0,1)` to obtain the last digit.\nUse `Array.prototype.reduce()` to implement the Luhn Algorithm.\nReturn `true` if `sum` is divisible by `10`, `false` otherwise.",
        "codeBlocks": {
          "es6": "const luhnCheck = num => {\n  let arr = (num + '')\n    .split('')\n    .reverse()\n    .map(x => parseInt(x));\n  let lastDigit = arr.splice(0, 1)[0];\n  let sum = arr.reduce((acc, val, i) => (i % 2 !== 0 ? acc + val : acc + ((val * 2) % 9) || 9), 0);\n  sum += lastDigit;\n  return sum % 10 === 0;\n};",
          "es5": "var luhnCheck = function luhnCheck(num) {\n  var arr = (num + '').split('').reverse().map(function (x) {\n    return parseInt(x);\n  });\n  var lastDigit = arr.splice(0, 1)[0];\n  var sum = arr.reduce(function (acc, val, i) {\n    return i % 2 !== 0 ? acc + val : acc + val * 2 % 9 || 9;\n  }, 0);\n  sum += lastDigit;\n  return sum % 10 === 0;\n};",
          "example": "luhnCheck('4485275742308327'); // true\nluhnCheck(6011329933655299); //  false\nluhnCheck(123456789); // false"
        },
        "tags": [
          "math",
          "utility",
          "advanced"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "37a866439f736e06c325cfdfb1ce614e8135fc724a7ab8c60174cf8cffe283cf"
      }
    },
    {
      "id": "mapKeys",
      "type": "snippet",
      "attributes": {
        "fileName": "mapKeys.md",
        "text": "Creates an object with keys generated by running the provided function for each key and the same values as the provided object.\n\nUse `Object.keys(obj)` to iterate over the object's keys.\nUse `Array.prototype.reduce()` to create a new object with the same values and mapped keys using `fn`.",
        "codeBlocks": {
          "es6": "const mapKeys = (obj, fn) =>\n  Object.keys(obj).reduce((acc, k) => {\n    acc[fn(obj[k], k, obj)] = obj[k];\n    return acc;\n  }, {});",
          "es5": "var mapKeys = function mapKeys(obj, fn) {\n  return Object.keys(obj).reduce(function (acc, k) {\n    acc[fn(obj[k], k, obj)] = obj[k];\n    return acc;\n  }, {});\n};",
          "example": "mapKeys({ a: 1, b: 2 }, (val, key) => key + val); // { a1: 1, b2: 2 }"
        },
        "tags": [
          "object",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "215198b03c4b2e9c7961de606fa9df83fa5964f2210fcf17b4ea69ee15294bcb"
      }
    },
    {
      "id": "mapObject",
      "type": "snippet",
      "attributes": {
        "fileName": "mapObject.md",
        "text": "Maps the values of an array to an object using a function, where the key-value pairs consist of the original value as the key and the mapped value.\n\nUse an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new `Array` to store the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations).",
        "codeBlocks": {
          "es6": "const mapObject = (arr, fn) =>\n  (a => (\n    (a = [arr, arr.map(fn)]), a[0].reduce((acc, val, ind) => ((acc[val] = a[1][ind]), acc), {})\n  ))();",
          "es5": "var mapObject = function mapObject(arr, fn) {\n  return function (a) {\n    return a = [arr, arr.map(fn)], a[0].reduce(function (acc, val, ind) {\n      return acc[val] = a[1][ind], acc;\n    }, {});\n  }();\n};",
          "example": "const squareIt = arr => mapObject(arr, a => a * a);\nsquareIt([1, 2, 3]); // { 1: 1, 2: 4, 3: 9 }"
        },
        "tags": [
          "array",
          "object",
          "advanced"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "c7f0f9b6b22590a17c41057c56ea5cf14e74dfbbd4fb7e4bc5c08db3760ef76d"
      }
    },
    {
      "id": "mapString",
      "type": "snippet",
      "attributes": {
        "fileName": "mapString.md",
        "text": "Creates a new string with the results of calling a provided function on every character in the calling string.\n\nUse `String.prototype.split('')` and `Array.prototype.map()` to call the provided function, `fn`, for each character in `str`.\nUse `Array.prototype.join('')` to recombine the array of characters into a string.\nThe callback function, `fn`, takes three arguments (the current character, the index of the current character and the string `mapString` was called upon).",
        "codeBlocks": {
          "es6": "const mapString = (str, fn) =>\n  str\n    .split('')\n    .map((c, i) => fn(c, i, str))\n    .join('');",
          "es5": "var mapString = function mapString(str, fn) {\n  return str.split('').map(function (c, i) {\n    return fn(c, i, str);\n  }).join('');\n};",
          "example": "mapString('lorem ipsum', c => c.toUpperCase()); // 'LOREM IPSUM'"
        },
        "tags": [
          "string",
          "array",
          "function",
          "utility",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "7ea3b8a83b25f531ed389bfb8318ad70e65dbe2dc9f966a81924415c447a38df"
      }
    },
    {
      "id": "mapValues",
      "type": "snippet",
      "attributes": {
        "fileName": "mapValues.md",
        "text": "Creates an object with the same keys as the provided object and values generated by running the provided function for each value.\n\nUse `Object.keys(obj)` to iterate over the object's keys.\nUse `Array.prototype.reduce()` to create a new object with the same keys and mapped values using `fn`.",
        "codeBlocks": {
          "es6": "const mapValues = (obj, fn) =>\n  Object.keys(obj).reduce((acc, k) => {\n    acc[k] = fn(obj[k], k, obj);\n    return acc;\n  }, {});",
          "es5": "var mapValues = function mapValues(obj, fn) {\n  return Object.keys(obj).reduce(function (acc, k) {\n    acc[k] = fn(obj[k], k, obj);\n    return acc;\n  }, {});\n};",
          "example": "const users = {\n  fred: { user: 'fred', age: 40 },\n  pebbles: { user: 'pebbles', age: 1 }\n};\nmapValues(users, u => u.age); // { fred: 40, pebbles: 1 }"
        },
        "tags": [
          "object",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "10d552b21c7b8d85c9588a47bffc571ed837df53d24a47cb80e8016f49b04885"
      }
    },
    {
      "id": "mask",
      "type": "snippet",
      "attributes": {
        "fileName": "mask.md",
        "text": "Replaces all but the last `num` of characters with the specified mask character.\n\nUse `String.prototype.slice()` to grab the portion of the characters that will remain unmasked and use `String.padStart()` to fill the beginning of the string with the mask character up to the original length.\nOmit the second argument, `num`, to keep a default of `4` characters unmasked. If `num` is negative, the unmasked characters will be at the start of the string.\nOmit the third argument, `mask`, to use a default character of `'*'` for the mask.",
        "codeBlocks": {
          "es6": "const mask = (cc, num = 4, mask = '*') => `${cc}`.slice(-num).padStart(`${cc}`.length, mask);",
          "es5": "var mask = function mask(cc) {\n  var num = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 4;\n  var mask = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '*';\n  return \"\".concat(cc).slice(-num).padStart(\"\".concat(cc).length, mask);\n};",
          "example": "mask(1234567890); // '******7890'\nmask(1234567890, 3); // '*******890'\nmask(1234567890, -4, '$'); // '$$$$567890'"
        },
        "tags": [
          "string",
          "utility",
          "regexp",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "23226393059fc47128562284e5982e5f9a4b365b8d0625f7e18cabde49f2e682"
      }
    },
    {
      "id": "matches",
      "type": "snippet",
      "attributes": {
        "fileName": "matches.md",
        "text": "Compares two objects to determine if the first one contains equivalent property values to the second one.\n\nUse `Object.keys(source)` to get all the keys of the second object, then `Array.prototype.every()`, `Object.hasOwnProperty()` and strict comparison to determine if all keys exist in the first object and have the same values.",
        "codeBlocks": {
          "es6": "const matches = (obj, source) =>\n  Object.keys(source).every(key => obj.hasOwnProperty(key) && obj[key] === source[key]);",
          "es5": "var matches = function matches(obj, source) {\n  return Object.keys(source).every(function (key) {\n    return obj.hasOwnProperty(key) && obj[key] === source[key];\n  });\n};",
          "example": "matches({ age: 25, hair: 'long', beard: true }, { hair: 'long', beard: true }); // true\nmatches({ hair: 'long', beard: true }, { age: 25, hair: 'long', beard: true }); // false"
        },
        "tags": [
          "object",
          "type",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "b937a42861d79ec84dc8217b31c193351ec82f3220d5eccc8840d059673823ba"
      }
    },
    {
      "id": "matchesWith",
      "type": "snippet",
      "attributes": {
        "fileName": "matchesWith.md",
        "text": "Compares two objects to determine if the first one contains equivalent property values to the second one, based on a provided function.\n\nUse `Object.keys(source)` to get all the keys of the second object, then `Array.prototype.every()`, `Object.hasOwnProperty()` and the provided function to determine if all keys exist in the first object and have equivalent values.\nIf no function is provided, the values will be compared using the equality operator.",
        "codeBlocks": {
          "es6": "const matchesWith = (obj, source, fn) =>\n  Object.keys(source).every(\n    key =>\n      obj.hasOwnProperty(key) && fn\n        ? fn(obj[key], source[key], key, obj, source)\n        : obj[key] == source[key]\n  );",
          "es5": "var matchesWith = function matchesWith(obj, source, fn) {\n  return Object.keys(source).every(function (key) {\n    return obj.hasOwnProperty(key) && fn ? fn(obj[key], source[key], key, obj, source) : obj[key] == source[key];\n  });\n};",
          "example": "const isGreeting = val => /^h(?:i|ello)$/.test(val);\nmatchesWith(\n  { greeting: 'hello' },\n  { greeting: 'hi' },\n  (oV, sV) => isGreeting(oV) && isGreeting(sV)\n); // true"
        },
        "tags": [
          "object",
          "type",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "a6ce779c9f00b00d0035baeeb187ac97b6f96d748db6e4583f408173a2310dac"
      }
    },
    {
      "id": "maxBy",
      "type": "snippet",
      "attributes": {
        "fileName": "maxBy.md",
        "text": "Returns the maximum value 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`, `Math.max()` to get the maximum value.",
        "codeBlocks": {
          "es6": "const maxBy = (arr, fn) => Math.max(...arr.map(typeof fn === 'function' ? fn : val => val[fn]));",
          "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 maxBy = function maxBy(arr, fn) {\n  return Math.max.apply(Math, _toConsumableArray(arr.map(typeof fn === 'function' ? fn : function (val) {\n    return val[fn];\n  })));\n};",
          "example": "maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 8\nmaxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 8"
        },
        "tags": [
          "math",
          "array",
          "function",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "00851da4972ff91286aecc46f1070ce619d0d64287ac6a8c90b6f8f3c0da2abc"
      }
    },
    {
      "id": "maxDate",
      "type": "snippet",
      "attributes": {
        "fileName": "maxDate.md",
        "text": "Returns the maximum of the given dates.\n\nUse `Math.max.apply()` to find the maximum date value, `new Date()` to convert it to a `Date` object.",
        "codeBlocks": {
          "es6": "const maxDate = (...dates) => new Date(Math.max.apply(null, ...dates));",
          "es5": "var maxDate = function maxDate() {\n  var _Math$max;\n\n  for (var _len = arguments.length, dates = new Array(_len), _key = 0; _key < _len; _key++) {\n    dates[_key] = arguments[_key];\n  }\n\n  return new Date((_Math$max = Math.max).apply.apply(_Math$max, [null].concat(dates)));\n};",
          "example": "const array = [\n  new Date(2017, 4, 13),\n  new Date(2018, 2, 12),\n  new Date(2016, 0, 10),\n  new Date(2016, 0, 9)\n];\nmaxDate(array); // 2018-03-11T22:00:00.000Z"
        },
        "tags": [
          "date",
          "math",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "8d1b95da3bac65bf8a1801edfd1efce94ea17902669a7612c5a0138fad9d0b12"
      }
    },
    {
      "id": "maxN",
      "type": "snippet",
      "attributes": {
        "fileName": "maxN.md",
        "text": "Returns the `n` maximum elements from the provided array.\nIf `n` is greater than or equal to the provided array's length, then return the original array (sorted in descending order).\n\nUse `Array.prototype.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in descending order.\nUse `Array.prototype.slice()` to get the specified number of elements.\nOmit the second argument, `n`, to get a one-element array.",
        "codeBlocks": {
          "es6": "const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).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 maxN = function maxN(arr) {\n  var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;\n  return _toConsumableArray(arr).sort(function (a, b) {\n    return b - a;\n  }).slice(0, n);\n};",
          "example": "maxN([1, 2, 3]); // [3]\nmaxN([1, 2, 3], 2); // [3,2]"
        },
        "tags": [
          "array",
          "math",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "71e58ca545b7dd0256d29b719b0c48c177968ef615a5ca1fc92377e6a4b089f7"
      }
    },
    {
      "id": "median",
      "type": "snippet",
      "attributes": {
        "fileName": "median.md",
        "text": "Returns the median of an array of numbers.\n\nFind the middle of the array, use `Array.prototype.sort()` to sort the values.\nReturn the number at the midpoint if `length` is odd, otherwise the average of the two middle numbers.",
        "codeBlocks": {
          "es6": "const median = arr => {\n  const mid = Math.floor(arr.length / 2),\n    nums = [...arr].sort((a, b) => a - b);\n  return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;\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 median = function median(arr) {\n  var mid = Math.floor(arr.length / 2),\n      nums = _toConsumableArray(arr).sort(function (a, b) {\n    return a - b;\n  });\n\n  return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;\n};",
          "example": "median([5, 6, 50, 1, -5]); // 5"
        },
        "tags": [
          "math",
          "array",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "448c71acf264e7e0752383faf025b6f118a02954cc651c1c5308e3894a83cc44"
      }
    },
    {
      "id": "memoize",
      "type": "snippet",
      "attributes": {
        "fileName": "memoize.md",
        "text": "Returns the memoized (cached) function.\n\nCreate an empty cache by instantiating a new `Map` object.\nReturn a function which takes a single argument to be supplied to the memoized function by first checking if the function's output for that specific input value is already cached, or store and return it if not. The `function` keyword must be used in order to allow the memoized function to have its `this` context changed if necessary.\nAllow access to the `cache` by setting it as a property on the returned function.",
        "codeBlocks": {
          "es6": "const memoize = fn => {\n  const cache = new Map();\n  const cached = function(val) {\n    return cache.has(val) ? cache.get(val) : cache.set(val, fn.call(this, val)) && cache.get(val);\n  };\n  cached.cache = cache;\n  return cached;\n};",
          "es5": "var memoize = function memoize(fn) {\n  var cache = new Map();\n\n  var cached = function cached(val) {\n    return cache.has(val) ? cache.get(val) : cache.set(val, fn.call(this, val)) && cache.get(val);\n  };\n\n  cached.cache = cache;\n  return cached;\n};",
          "example": "// See the `anagrams` snippet.\nconst anagramsCached = memoize(anagrams);\nanagramsCached('javascript'); // takes a long time\nanagramsCached('javascript'); // returns virtually instantly since it's now cached\nconsole.log(anagramsCached.cache); // The cached anagrams map"
        },
        "tags": [
          "function",
          "advanced"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "b0de7050159a7c0fab5a089e2118d3e20d48d96a4aae6a0ddb98f489882bb80f"
      }
    },
    {
      "id": "merge",
      "type": "snippet",
      "attributes": {
        "fileName": "merge.md",
        "text": "Creates a new object from the combination of two or more objects.\n\nUse `Array.prototype.reduce()` combined with `Object.keys(obj)` to iterate over all objects and keys.\nUse `hasOwnProperty()` and `Array.prototype.concat()` to append values for keys existing in multiple objects.",
        "codeBlocks": {
          "es6": "const merge = (...objs) =>\n  [...objs].reduce(\n    (acc, obj) =>\n      Object.keys(obj).reduce((a, k) => {\n        acc[k] = acc.hasOwnProperty(k) ? [].concat(acc[k]).concat(obj[k]) : obj[k];\n        return acc;\n      }, {}),\n    {}\n  );",
          "es5": "var merge = function merge() {\n  for (var _len = arguments.length, objs = new Array(_len), _key = 0; _key < _len; _key++) {\n    objs[_key] = arguments[_key];\n  }\n\n  return objs.concat().reduce(function (acc, obj) {\n    return Object.keys(obj).reduce(function (a, k) {\n      acc[k] = acc.hasOwnProperty(k) ? [].concat(acc[k]).concat(obj[k]) : obj[k];\n      return acc;\n    }, {});\n  }, {});\n};",
          "example": "const object = {\n  a: [{ x: 2 }, { y: 4 }],\n  b: 1\n};\nconst other = {\n  a: { z: 3 },\n  b: [2, 3],\n  c: 'foo'\n};\nmerge(object, other); // { a: [ { x: 2 }, { y: 4 }, { z: 3 } ], b: [ 1, 2, 3 ], c: 'foo' }"
        },
        "tags": [
          "object",
          "array",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "13f1b8dca2fb1c6ebba61abb7e5784fc80288e59f4979e463c5f4b81497d76bd"
      }
    },
    {
      "id": "minBy",
      "type": "snippet",
      "attributes": {
        "fileName": "minBy.md",
        "text": "Returns the minimum value 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`, `Math.min()` to get the maximum value.",
        "codeBlocks": {
          "es6": "const minBy = (arr, fn) => Math.min(...arr.map(typeof fn === 'function' ? fn : val => val[fn]));",
          "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 minBy = function minBy(arr, fn) {\n  return Math.min.apply(Math, _toConsumableArray(arr.map(typeof fn === 'function' ? fn : function (val) {\n    return val[fn];\n  })));\n};",
          "example": "minBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 2\nminBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 2"
        },
        "tags": [
          "math",
          "array",
          "function",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "58be8a0dc3e56ec09b0bb927c2c575c033c70ac3a8b612e993fdcbf6d5a99d51"
      }
    },
    {
      "id": "minDate",
      "type": "snippet",
      "attributes": {
        "fileName": "minDate.md",
        "text": "Returns the minimum of the given dates.\n\nUse `Math.min.apply()` to find the minimum date value, `new Date()` to convert it to a `Date` object.",
        "codeBlocks": {
          "es6": "const minDate = (...dates) => new Date(Math.min.apply(null, ...dates));",
          "es5": "var minDate = function minDate() {\n  var _Math$min;\n\n  for (var _len = arguments.length, dates = new Array(_len), _key = 0; _key < _len; _key++) {\n    dates[_key] = arguments[_key];\n  }\n\n  return new Date((_Math$min = Math.min).apply.apply(_Math$min, [null].concat(dates)));\n};",
          "example": "const array = [\n  new Date(2017, 4, 13),\n  new Date(2018, 2, 12),\n  new Date(2016, 0, 10),\n  new Date(2016, 0, 9)\n];\nminDate(array); // 2016-01-08T22:00:00.000Z"
        },
        "tags": [
          "date",
          "math",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "436e070c2961cd8cbeffbc05fae7b3fa978eefe1e048de248bc17b86a2b06705"
      }
    },
    {
      "id": "minN",
      "type": "snippet",
      "attributes": {
        "fileName": "minN.md",
        "text": "Returns the `n` minimum elements from the provided array.\nIf `n` is greater than or equal to the provided array's length, then return the original array (sorted in ascending order).\n\nUse `Array.prototype.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in ascending order.\nUse `Array.prototype.slice()` to get the specified number of elements.\nOmit the second argument, `n`, to get a one-element array.",
        "codeBlocks": {
          "es6": "const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).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 minN = function minN(arr) {\n  var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;\n  return _toConsumableArray(arr).sort(function (a, b) {\n    return a - b;\n  }).slice(0, n);\n};",
          "example": "minN([1, 2, 3]); // [1]\nminN([1, 2, 3], 2); // [1,2]"
        },
        "tags": [
          "array",
          "math",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "325ab83a7c6da0d014c69236fc2134080bb8b2e6153608ba63c5924041db1c3a"
      }
    },
    {
      "id": "mostPerformant",
      "type": "snippet",
      "attributes": {
        "fileName": "mostPerformant.md",
        "text": "Returns the index of the function in an array of functions which executed the fastest.\n\nUse `Array.prototype.map()` to generate an array where each value is the total time taken to execute the function after `iterations` times. Use the difference in `performance.now()` values before and after to get the total time in milliseconds to a high degree of accuracy.\nUse `Math.min()` to find the minimum execution time, and return the index of that shortest time which corresponds to the index of the most performant function.\nOmit the second argument, `iterations`, to use a default of 10,000 iterations. The more iterations, the more reliable the result but the longer it will take.",
        "codeBlocks": {
          "es6": "const mostPerformant = (fns, iterations = 10000) => {\n  const times = fns.map(fn => {\n    const before = performance.now();\n    for (let i = 0; i < iterations; i++) fn();\n    return performance.now() - before;\n  });\n  return times.indexOf(Math.min(...times));\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 mostPerformant = function mostPerformant(fns) {\n  var iterations = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10000;\n  var times = fns.map(function (fn) {\n    var before = performance.now();\n\n    for (var i = 0; i < iterations; i++) {\n      fn();\n    }\n\n    return performance.now() - before;\n  });\n  return times.indexOf(Math.min.apply(Math, _toConsumableArray(times)));\n};",
          "example": "mostPerformant([\n  () => {\n    // Loops through the entire array before returning `false`\n    [1, 2, 3, 4, 5, 6, 7, 8, 9, '10'].every(el => typeof el === 'number');\n  },\n  () => {\n    // Only needs to reach index `1` before returning false\n    [1, '2', 3, 4, 5, 6, 7, 8, 9, 10].every(el => typeof el === 'number');\n  }\n]); // 1"
        },
        "tags": [
          "utility",
          "function"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "77b76c99d021860bb2c03c1b0b37f2eeddd9f9c9594aad735744fb1014e3e62a"
      }
    },
    {
      "id": "negate",
      "type": "snippet",
      "attributes": {
        "fileName": "negate.md",
        "text": "Negates a predicate function.\n\nTake a predicate function and apply the not operator (`!`) to it with its arguments.",
        "codeBlocks": {
          "es6": "const negate = func => (...args) => !func(...args);",
          "es5": "var negate = function negate(func) {\n  return function () {\n    return !func.apply(void 0, arguments);\n  };\n};",
          "example": "[1, 2, 3, 4, 5, 6].filter(negate(n => n % 2 === 0)); // [ 1, 3, 5 ]"
        },
        "tags": [
          "function",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "7cc8011d1cb158b7371144dff98b6243752e862d9dc3786caac77e50539060ed"
      }
    },
    {
      "id": "nest",
      "type": "snippet",
      "attributes": {
        "fileName": "nest.md",
        "text": "Given a flat array of objects linked to one another, it will nest them recursively.\nUseful for nesting comments, such as the ones on reddit.com.\n\nUse recursion.\nUse `Array.prototype.filter()` to filter the items where the `id` matches the `link`, then `Array.prototype.map()` to map each one to a new object that has a `children` property which recursively nests the items based on which ones are children of the current item.\nOmit the second argument, `id`, to default to `null` which indicates the object is not linked to another one (i.e. it is a top level object).\nOmit the third argument, `link`, to use `'parent_id'` as the default property which links the object to another one by its `id`.",
        "codeBlocks": {
          "es6": "const nest = (items, id = null, link = 'parent_id') =>\n  items\n    .filter(item => item[link] === id)\n    .map(item => ({ ...item, children: nest(items, item.id) }));",
          "es5": "function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar nest = function nest(items) {\n  var id = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;\n  var link = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'parent_id';\n  return items.filter(function (item) {\n    return item[link] === id;\n  }).map(function (item) {\n    return _objectSpread({}, item, {\n      children: nest(items, item.id)\n    });\n  });\n};",
          "example": "// One top level comment\nconst comments = [\n  { id: 1, parent_id: null },\n  { id: 2, parent_id: 1 },\n  { id: 3, parent_id: 1 },\n  { id: 4, parent_id: 2 },\n  { id: 5, parent_id: 4 }\n];\nconst nestedComments = nest(comments); // [{ id: 1, parent_id: null, children: [...] }]"
        },
        "tags": [
          "object",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "ff06e5aeb0e1159f9193332187323f6a4f990eeddaa4fbc706c5a6025b53290e"
      }
    },
    {
      "id": "nodeListToArray",
      "type": "snippet",
      "attributes": {
        "fileName": "nodeListToArray.md",
        "text": "Converts a `NodeList` to an array.\n\nUse spread operator inside new array to convert a `NodeList` to an array.",
        "codeBlocks": {
          "es6": "const nodeListToArray = nodeList => [...nodeList];",
          "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 nodeListToArray = function nodeListToArray(nodeList) {\n  return _toConsumableArray(nodeList);\n};",
          "example": "nodeListToArray(document.childNodes); // [ <!DOCTYPE html>, html ]"
        },
        "tags": [
          "browser",
          "array",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "50e0b97be1cc2256f34991c379bae0bba8c99db160dcd5842112752074de92ec"
      }
    },
    {
      "id": "none",
      "type": "snippet",
      "attributes": {
        "fileName": "none.md",
        "text": "Returns `true` if the provided predicate function returns `false` for all elements 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.",
        "codeBlocks": {
          "es6": "const none = (arr, fn = Boolean) => !arr.some(fn);",
          "es5": "var none = function none(arr) {\n  var fn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Boolean;\n  return !arr.some(fn);\n};",
          "example": "none([0, 1, 3, 0], x => x == 2); // true\nnone([0, 0, 0]); // true"
        },
        "tags": [
          "array",
          "function",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "efc733592e40a00d2d25b1b1fff5fe8064f9ecc8f67059279d70430c00a7a23c"
      }
    },
    {
      "id": "nthArg",
      "type": "snippet",
      "attributes": {
        "fileName": "nthArg.md",
        "text": "Creates a function that gets the argument at index `n`. If `n` is negative, the nth argument from the end is returned.\n\nUse `Array.prototype.slice()` to get the desired argument at index `n`.",
        "codeBlocks": {
          "es6": "const nthArg = n => (...args) => args.slice(n)[0];",
          "es5": "var nthArg = function nthArg(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 args.slice(n)[0];\n  };\n};",
          "example": "const third = nthArg(2);\nthird(1, 2, 3); // 3\nthird(1, 2); // undefined\nconst last = nthArg(-1);\nlast(1, 2, 3, 4, 5); // 5"
        },
        "tags": [
          "utility",
          "function",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "0afafa961fb6ef8cef3a7d74fa55d16ccf5c1d94d790e1d1984242fd165770d7"
      }
    },
    {
      "id": "nthElement",
      "type": "snippet",
      "attributes": {
        "fileName": "nthElement.md",
        "text": "Returns the nth element of an array.\n\nUse `Array.prototype.slice()` to get an array containing the nth element at the first place.\nIf the index is out of bounds, return `undefined`.\nOmit the second argument, `n`, to get the first element of the array.",
        "codeBlocks": {
          "es6": "const nthElement = (arr, n = 0) => (n === -1 ? arr.slice(n) : arr.slice(n, n + 1))[0];",
          "es5": "var nthElement = function nthElement(arr) {\n  var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n  return (n === -1 ? arr.slice(n) : arr.slice(n, n + 1))[0];\n};",
          "example": "nthElement(['a', 'b', 'c'], 1); // 'b'\nnthElement(['a', 'b', 'b'], -3); // 'a'"
        },
        "tags": [
          "array",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "20c4b668b37a52e61bbaa72b87a507cd4c7ca770d9e179d753258ccdead5ee6c"
      }
    },
    {
      "id": "objectFromPairs",
      "type": "snippet",
      "attributes": {
        "fileName": "objectFromPairs.md",
        "text": "Creates an object from the given key-value pairs.\n\nUse `Array.prototype.reduce()` to create and combine key-value pairs.",
        "codeBlocks": {
          "es6": "const objectFromPairs = arr => arr.reduce((a, [key, val]) => ((a[key] = val), a), {});",
          "es5": "function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }\n\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance\"); }\n\nfunction _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i[\"return\"] != null) _i[\"return\"](); } finally { if (_d) throw _e; } } return _arr; }\n\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n\nvar objectFromPairs = function objectFromPairs(arr) {\n  return arr.reduce(function (a, _ref) {\n    var _ref2 = _slicedToArray(_ref, 2),\n        key = _ref2[0],\n        val = _ref2[1];\n\n    return a[key] = val, a;\n  }, {});\n};",
          "example": "objectFromPairs([['a', 1], ['b', 2]]); // {a: 1, b: 2}"
        },
        "tags": [
          "object",
          "array",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "2d12e5cb31a3f9dd51639897eaf42ca6844fd2d8a899f51523f8b5a10a8f2348"
      }
    },
    {
      "id": "objectToPairs",
      "type": "snippet",
      "attributes": {
        "fileName": "objectToPairs.md",
        "text": "Creates an array of key-value pair arrays from an object.\n\nUse `Object.keys()` and `Array.prototype.map()` to iterate over the object's keys and produce an array with key-value pairs.",
        "codeBlocks": {
          "es6": "const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]);",
          "es5": "var objectToPairs = function objectToPairs(obj) {\n  return Object.keys(obj).map(function (k) {\n    return [k, obj[k]];\n  });\n};",
          "example": "objectToPairs({ a: 1, b: 2 }); // [ ['a', 1], ['b', 2] ]"
        },
        "tags": [
          "object",
          "array",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "251db16d7571ac9e81cde0ca431de71ecb2b9817a07b5075834072dc10eb9989"
      }
    },
    {
      "id": "observeMutations",
      "type": "snippet",
      "attributes": {
        "fileName": "observeMutations.md",
        "text": "Returns a new MutationObserver and runs the provided callback for each mutation on the specified element.\n\nUse a [`MutationObserver`](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) to observe mutations on the given element.\nUse `Array.prototype.forEach()` to run the callback for each mutation that is observed.\nOmit the third argument, `options`, to use the default [options](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver#MutationObserverInit) (all `true`).",
        "codeBlocks": {
          "es6": "const observeMutations = (element, callback, options) => {\n  const observer = new MutationObserver(mutations => mutations.forEach(m => callback(m)));\n  observer.observe(\n    element,\n    Object.assign(\n      {\n        childList: true,\n        attributes: true,\n        attributeOldValue: true,\n        characterData: true,\n        characterDataOldValue: true,\n        subtree: true\n      },\n      options\n    )\n  );\n  return observer;\n};",
          "es5": "var observeMutations = function observeMutations(element, callback, options) {\n  var observer = new MutationObserver(function (mutations) {\n    return mutations.forEach(function (m) {\n      return callback(m);\n    });\n  });\n  observer.observe(element, Object.assign({\n    childList: true,\n    attributes: true,\n    attributeOldValue: true,\n    characterData: true,\n    characterDataOldValue: true,\n    subtree: true\n  }, options));\n  return observer;\n};",
          "example": "const obs = observeMutations(document, console.log); // Logs all mutations that happen on the page\nobs.disconnect(); // Disconnects the observer and stops logging mutations on the page"
        },
        "tags": [
          "browser",
          "event",
          "advanced"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "043ee85dc41a7310271c16b31c9a2b3e662b83c1108a04490c753f1dd0473929"
      }
    },
    {
      "id": "off",
      "type": "snippet",
      "attributes": {
        "fileName": "off.md",
        "text": "Removes an event listener from an element.\n\nUse `EventTarget.removeEventListener()` to remove an event listener from an element. \nOmit the fourth argument `opts` to use `false` or specify it based on the options used when the event listener was added.",
        "codeBlocks": {
          "es6": "const off = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts);",
          "es5": "var off = function off(el, evt, fn) {\n  var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;\n  return el.removeEventListener(evt, fn, opts);\n};",
          "example": "const fn = () => console.log('!');\ndocument.body.addEventListener('click', fn);\noff(document.body, 'click', fn); // no longer logs '!' upon clicking on the page"
        },
        "tags": [
          "browser",
          "event",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "875854e1205203c8e8bff08adbf474ff88cbca4d33d49cb68417a72620096171"
      }
    },
    {
      "id": "offset",
      "type": "snippet",
      "attributes": {
        "fileName": "offset.md",
        "text": "Moves the specified amount of elements to the end of the array.\n\nUse `Array.prototype.slice()` twice to get the elements after the specified index and the elements before that.\nUse the spread operator(`...`) to combine the two into one array.\nIf `offset` is negative, the elements will be moved from end to start.",
        "codeBlocks": {
          "es6": "const offset = (arr, offset) => [...arr.slice(offset), ...arr.slice(0, offset)];",
          "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 offset = function offset(arr, _offset) {\n  return _toConsumableArray(arr.slice(_offset)).concat(_toConsumableArray(arr.slice(0, _offset)));\n};",
          "example": "offset([1, 2, 3, 4, 5], 2); // [3, 4, 5, 1, 2]\noffset([1, 2, 3, 4, 5], -2); // [4, 5, 1, 2, 3]"
        },
        "tags": [
          "array",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "f00343d616edbcad85ba18f1eb279f55bc663512ab725a6ea5ca0b94903164a8"
      }
    },
    {
      "id": "omit",
      "type": "snippet",
      "attributes": {
        "fileName": "omit.md",
        "text": "Omits the key-value pairs corresponding to the given keys from an object.\n\nUse `Object.keys(obj)`, `Array.prototype.filter()` and `Array.prototype.includes()` to remove the provided keys.\nUse `Array.prototype.reduce()` to convert the filtered keys back to an object with the corresponding key-value pairs.",
        "codeBlocks": {
          "es6": "const omit = (obj, arr) =>\n  Object.keys(obj)\n    .filter(k => !arr.includes(k))\n    .reduce((acc, key) => ((acc[key] = obj[key]), acc), {});",
          "es5": "var omit = function omit(obj, arr) {\n  return Object.keys(obj).filter(function (k) {\n    return !arr.includes(k);\n  }).reduce(function (acc, key) {\n    return acc[key] = obj[key], acc;\n  }, {});\n};",
          "example": "omit({ a: 1, b: '2', c: 3 }, ['b']); // { 'a': 1, 'c': 3 }"
        },
        "tags": [
          "object",
          "array",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "0a91b2ae1b488c8a3ac1d732d48396ea0545314114d97ff559f6c6b275b8e2b1"
      }
    },
    {
      "id": "omitBy",
      "type": "snippet",
      "attributes": {
        "fileName": "omitBy.md",
        "text": "Creates an object composed of the properties the given function returns falsey for. The function is invoked with two arguments: (value, key).\n\nUse `Object.keys(obj)` and `Array.prototype.filter()`to remove the keys for which `fn` returns a truthy value.\nUse `Array.prototype.reduce()` to convert the filtered keys back to an object with the corresponding key-value pairs.",
        "codeBlocks": {
          "es6": "const omitBy = (obj, fn) =>\n  Object.keys(obj)\n    .filter(k => !fn(obj[k], k))\n    .reduce((acc, key) => ((acc[key] = obj[key]), acc), {});",
          "es5": "var omitBy = function omitBy(obj, fn) {\n  return Object.keys(obj).filter(function (k) {\n    return !fn(obj[k], k);\n  }).reduce(function (acc, key) {\n    return acc[key] = obj[key], acc;\n  }, {});\n};",
          "example": "omitBy({ a: 1, b: '2', c: 3 }, x => typeof x === 'number'); // { b: '2' }"
        },
        "tags": [
          "object",
          "array",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "359fd8eb0861de57213387e715687174cf671e22e9b66e358ac28364ad1b2be2"
      }
    },
    {
      "id": "on",
      "type": "snippet",
      "attributes": {
        "fileName": "on.md",
        "text": "Adds an event listener to an element with the ability to use event delegation.\n\nUse `EventTarget.addEventListener()` to add an event listener to an element. If there is a `target` property supplied to the options object, ensure the event target matches the target specified and then invoke the callback by supplying the correct `this` context.\nReturns a reference to the custom delegator function, in order to be possible to use with [`off`](#off).\nOmit `opts` to default to non-delegation behavior and event bubbling.",
        "codeBlocks": {
          "es6": "const on = (el, evt, fn, opts = {}) => {\n  const delegatorFn = e => e.target.matches(opts.target) && fn.call(e.target, e);\n  el.addEventListener(evt, opts.target ? delegatorFn : fn, opts.options || false);\n  if (opts.target) return delegatorFn;\n};",
          "es5": "var on = function on(el, evt, fn) {\n  var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n\n  var delegatorFn = function delegatorFn(e) {\n    return e.target.matches(opts.target) && fn.call(e.target, e);\n  };\n\n  el.addEventListener(evt, opts.target ? delegatorFn : fn, opts.options || false);\n  if (opts.target) return delegatorFn;\n};",
          "example": "const fn = () => console.log('!');\non(document.body, 'click', fn); // logs '!' upon clicking the body\non(document.body, 'click', fn, { target: 'p' }); // logs '!' upon clicking a `p` element child of the body\non(document.body, 'click', fn, { options: true }); // use capturing instead of bubbling"
        },
        "tags": [
          "browser",
          "event",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "9baea961cebb81bcaec83515bc98ca1e77affc03b2550c88e5d559973025d3d7"
      }
    },
    {
      "id": "once",
      "type": "snippet",
      "attributes": {
        "fileName": "once.md",
        "text": "Ensures a function is called only once.\n\nUtilizing a closure, use a flag, `called`, and set it to `true` once the function is called for the first time, preventing it from being called again. In order to allow the function to have its `this` context changed (such as in an event listener), the `function` keyword must be used, and the supplied function must have the context applied.\nAllow the function to be supplied with an arbitrary number of arguments using the rest/spread (`...`) operator.",
        "codeBlocks": {
          "es6": "const once = fn => {\n  let called = false;\n  return function(...args) {\n    if (called) return;\n    called = true;\n    return fn.apply(this, args);\n  };\n};",
          "es5": "var once = function once(fn) {\n  var called = false;\n  return function () {\n    if (called) return;\n    called = true;\n\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(this, args);\n  };\n};",
          "example": "const startApp = function(event) {\n  console.log(this, event); // document.body, MouseEvent\n};\ndocument.body.addEventListener('click', once(startApp)); // only runs `startApp` once upon click"
        },
        "tags": [
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "66051661cb13aa6295a539dda924cb6d55964fc0a438448414decaadbcc64637"
      }
    },
    {
      "id": "onUserInputChange",
      "type": "snippet",
      "attributes": {
        "fileName": "onUserInputChange.md",
        "text": "Run the callback whenever the user input type changes (`mouse` or `touch`). Useful for enabling/disabling code depending on the input device. This process is dynamic and works with hybrid devices (e.g. touchscreen laptops).\n\nUse two event listeners. Assume `mouse` input initially and bind a `touchstart` event listener to the document. \nOn `touchstart`, add a `mousemove` event listener to listen for two consecutive `mousemove` events firing within 20ms, using `performance.now()`.\nRun the callback with the input type as an argument in either of these situations.",
        "codeBlocks": {
          "es6": "const onUserInputChange = callback => {\n  let type = 'mouse',\n    lastTime = 0;\n  const mousemoveHandler = () => {\n    const now = performance.now();\n    if (now - lastTime < 20)\n      (type = 'mouse'), callback(type), document.removeEventListener('mousemove', mousemoveHandler);\n    lastTime = now;\n  };\n  document.addEventListener('touchstart', () => {\n    if (type === 'touch') return;\n    (type = 'touch'), callback(type), document.addEventListener('mousemove', mousemoveHandler);\n  });\n};",
          "es5": "var onUserInputChange = function onUserInputChange(callback) {\n  var type = 'mouse',\n      lastTime = 0;\n\n  var mousemoveHandler = function mousemoveHandler() {\n    var now = performance.now();\n    if (now - lastTime < 20) type = 'mouse', callback(type), document.removeEventListener('mousemove', mousemoveHandler);\n    lastTime = now;\n  };\n\n  document.addEventListener('touchstart', function () {\n    if (type === 'touch') return;\n    type = 'touch', callback(type), document.addEventListener('mousemove', mousemoveHandler);\n  });\n};",
          "example": "onUserInputChange(type => {\n  console.log('The user is now using', type, 'as an input method.');\n});"
        },
        "tags": [
          "browser",
          "event",
          "advanced"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "f42b7a49b6b92be7da1537a058588818c05d1110150fcad063c4325665a4d4e3"
      }
    },
    {
      "id": "orderBy",
      "type": "snippet",
      "attributes": {
        "fileName": "orderBy.md",
        "text": "Returns a sorted array of objects ordered by properties and orders.\n\nUses `Array.prototype.sort()`, `Array.prototype.reduce()` on the `props` array with a default value of `0`, use array destructuring to swap the properties position depending on the order passed.\nIf no `orders` array is passed it sort by `'asc'` by default.",
        "codeBlocks": {
          "es6": "const orderBy = (arr, props, orders) =>\n  [...arr].sort((a, b) =>\n    props.reduce((acc, prop, i) => {\n      if (acc === 0) {\n        const [p1, p2] = orders && orders[i] === 'desc' ? [b[prop], a[prop]] : [a[prop], b[prop]];\n        acc = p1 > p2 ? 1 : p1 < p2 ? -1 : 0;\n      }\n      return acc;\n    }, 0)\n  );",
          "es5": "function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }\n\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance\"); }\n\nfunction _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i[\"return\"] != null) _i[\"return\"](); } finally { if (_d) throw _e; } } return _arr; }\n\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n\nfunction _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 orderBy = function orderBy(arr, props, orders) {\n  return _toConsumableArray(arr).sort(function (a, b) {\n    return props.reduce(function (acc, prop, i) {\n      if (acc === 0) {\n        var _ref = orders && orders[i] === 'desc' ? [b[prop], a[prop]] : [a[prop], b[prop]],\n            _ref2 = _slicedToArray(_ref, 2),\n            p1 = _ref2[0],\n            p2 = _ref2[1];\n\n        acc = p1 > p2 ? 1 : p1 < p2 ? -1 : 0;\n      }\n\n      return acc;\n    }, 0);\n  });\n};",
          "example": "const users = [{ name: 'fred', age: 48 }, { name: 'barney', age: 36 }, { name: 'fred', age: 40 }];\norderBy(users, ['name', 'age'], ['asc', 'desc']); // [{name: 'barney', age: 36}, {name: 'fred', age: 48}, {name: 'fred', age: 40}]\norderBy(users, ['name', 'age']); // [{name: 'barney', age: 36}, {name: 'fred', age: 40}, {name: 'fred', age: 48}]"
        },
        "tags": [
          "object",
          "array",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "1a1adbe92bb44aa61583613d8aebf70143f4ac9cd9aae2afa1d5ac88410958d7"
      }
    },
    {
      "id": "over",
      "type": "snippet",
      "attributes": {
        "fileName": "over.md",
        "text": "Creates a function that invokes each provided function with the arguments it receives and returns the results.\n\nUse `Array.prototype.map()` and `Function.prototype.apply()` to apply each function to the given arguments.",
        "codeBlocks": {
          "es6": "const over = (...fns) => (...args) => fns.map(fn => fn.apply(null, args));",
          "es5": "var over = function over() {\n  for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) {\n    fns[_key] = 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 fns.map(function (fn) {\n      return fn.apply(null, args);\n    });\n  };\n};",
          "example": "const minMax = over(Math.min, Math.max);\nminMax(1, 2, 3, 4, 5); // [1,5]"
        },
        "tags": [
          "adapter",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "c888834c4829c50c67c9828127ff4b8b810d99925202dd2cc42110ad32010ea7"
      }
    },
    {
      "id": "overArgs",
      "type": "snippet",
      "attributes": {
        "fileName": "overArgs.md",
        "text": "Creates a function that invokes the provided function with its arguments transformed.\n\nUse `Array.prototype.map()` to apply `transforms` to `args` in combination with the spread operator (`...`) to pass the transformed arguments to `fn`.",
        "codeBlocks": {
          "es6": "const overArgs = (fn, transforms) => (...args) => fn(...args.map((val, i) => transforms[i](val)));",
          "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 overArgs = function overArgs(fn, transforms) {\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.map(function (val, i) {\n      return transforms[i](val);\n    })));\n  };\n};",
          "example": "const square = n => n * n;\nconst double = n => n * 2;\nconst fn = overArgs((x, y) => [x, y], [square, double]);\nfn(9, 3); // [81, 6]"
        },
        "tags": [
          "adapter",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "50d31769481bb1a8c09db3bcece1b3c8346fb83f9db32d5ae0c99f09e3b45eaf"
      }
    },
    {
      "id": "pad",
      "type": "snippet",
      "attributes": {
        "fileName": "pad.md",
        "text": "Pads a string on both sides with the specified character, if it's shorter than the specified length.\n\nUse `String.padStart()` and `String.padEnd()` to pad both sides of the given string.\nOmit the third argument, `char`, to use the whitespace character as the default padding character.",
        "codeBlocks": {
          "es6": "const pad = (str, length, char = ' ') =>\n  str.padStart((str.length + length) / 2, char).padEnd(length, char);",
          "es5": "var pad = function pad(str, length) {\n  var char = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ' ';\n  return str.padStart((str.length + length) / 2, char).padEnd(length, char);\n};",
          "example": "pad('cat', 8); // '  cat   '\npad(String(42), 6, '0'); // '004200'\npad('foobar', 3); // 'foobar'"
        },
        "tags": [
          "string",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "9a7c678e67831c68d0589a63a2928d4b68e4defa7a015d598dda253710401902"
      }
    },
    {
      "id": "palindrome",
      "type": "snippet",
      "attributes": {
        "fileName": "palindrome.md",
        "text": "Returns `true` if the given string is a palindrome, `false` otherwise.\n\nConvert the string to `String.prototype.toLowerCase()` and use `String.prototype.replace()` to remove non-alphanumeric characters from it.\nThen, use the spread operator (`...`) to split the string into individual characters, `Array.prototype.reverse()`, `String.prototype.join('')` and compare it to the original, unreversed string, after converting it to `String.prototype.toLowerCase()`.",
        "codeBlocks": {
          "es6": "const palindrome = str => {\n  const s = str.toLowerCase().replace(/[\\W_]/g, '');\n  return s === [...s].reverse().join('');\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 palindrome = function palindrome(str) {\n  var s = str.toLowerCase().replace(/[\\W_]/g, '');\n  return s === _toConsumableArray(s).reverse().join('');\n};",
          "example": "palindrome('taco cat'); // true"
        },
        "tags": [
          "string",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "497b0275ae10369768d3c3c1db1b4de53ff82f64be838e5fd38ba469a88b4de9"
      }
    },
    {
      "id": "parseCookie",
      "type": "snippet",
      "attributes": {
        "fileName": "parseCookie.md",
        "text": "Parse an HTTP Cookie header string and return an object of all cookie name-value pairs.\n\nUse `String.prototype.split(';')` to separate key-value pairs from each other.\nUse `Array.prototype.map()` and `String.prototype.split('=')` to separate keys from values in each pair.\nUse `Array.prototype.reduce()` and `decodeURIComponent()` to create an object with all key-value pairs.",
        "codeBlocks": {
          "es6": "const parseCookie = str =>\n  str\n    .split(';')\n    .map(v => v.split('='))\n    .reduce((acc, v) => {\n      acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim());\n      return acc;\n    }, {});",
          "es5": "var parseCookie = function parseCookie(str) {\n  return str.split(';').map(function (v) {\n    return v.split('=');\n  }).reduce(function (acc, v) {\n    acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim());\n    return acc;\n  }, {});\n};",
          "example": "parseCookie('foo=bar; equation=E%3Dmc%5E2'); // { foo: 'bar', equation: 'E=mc^2' }"
        },
        "tags": [
          "utility",
          "string",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "634d9c15c437db3db0789f91c3aff73e469714a1dbd28af731a52ae1d7fd6443"
      }
    },
    {
      "id": "partial",
      "type": "snippet",
      "attributes": {
        "fileName": "partial.md",
        "text": "Creates a function that invokes `fn` with `partials` prepended to the arguments it receives.\n\nUse the spread operator (`...`) to prepend `partials` to the list of arguments of `fn`.",
        "codeBlocks": {
          "es6": "const partial = (fn, ...partials) => (...args) => fn(...partials, ...args);",
          "es5": "var partial = function partial(fn) {\n  for (var _len = arguments.length, partials = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n    partials[_key - 1] = 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(void 0, partials.concat(args));\n  };\n};",
          "example": "const greet = (greeting, name) => greeting + ' ' + name + '!';\nconst greetHello = partial(greet, 'Hello');\ngreetHello('John'); // 'Hello John!'"
        },
        "tags": [
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "b57e228d9f4be72f0b54e613db0d03f8f580c79e48cd7ba43673eaac874fd057"
      }
    },
    {
      "id": "partialRight",
      "type": "snippet",
      "attributes": {
        "fileName": "partialRight.md",
        "text": "Creates a function that invokes `fn` with `partials` appended to the arguments it receives.\n\nUse the spread operator (`...`) to append `partials` to the list of arguments of `fn`.",
        "codeBlocks": {
          "es6": "const partialRight = (fn, ...partials) => (...args) => fn(...args, ...partials);",
          "es5": "var partialRight = function partialRight(fn) {\n  for (var _len = arguments.length, partials = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n    partials[_key - 1] = 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(void 0, args.concat(partials));\n  };\n};",
          "example": "const greet = (greeting, name) => greeting + ' ' + name + '!';\nconst greetJohn = partialRight(greet, 'John');\ngreetJohn('Hello'); // 'Hello John!'"
        },
        "tags": [
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "907872c83c8820b239838c65f4d5174783e372275e85fd96050d9218932325b4"
      }
    },
    {
      "id": "partition",
      "type": "snippet",
      "attributes": {
        "fileName": "partition.md",
        "text": "Groups the elements into two arrays, depending on the provided function's truthiness for each element.\n\nUse `Array.prototype.reduce()` to create an array of two arrays.\nUse `Array.prototype.push()` to add elements for which `fn` returns `true` to the first array and elements for which `fn` returns `false` to the second one.",
        "codeBlocks": {
          "es6": "const partition = (arr, fn) =>\n  arr.reduce(\n    (acc, val, i, arr) => {\n      acc[fn(val, i, arr) ? 0 : 1].push(val);\n      return acc;\n    },\n    [[], []]\n  );",
          "es5": "var partition = function partition(arr, fn) {\n  return arr.reduce(function (acc, val, i, arr) {\n    acc[fn(val, i, arr) ? 0 : 1].push(val);\n    return acc;\n  }, [[], []]);\n};",
          "example": "const users = [{ user: 'barney', age: 36, active: false }, { user: 'fred', age: 40, active: true }];\npartition(users, o => o.active); // [[{ 'user': 'fred',    'age': 40, 'active': true }],[{ 'user': 'barney',  'age': 36, 'active': false }]]"
        },
        "tags": [
          "array",
          "object",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "578eac814b69f7854e2febd57c64bf3323fe2e59beea24e5708fef5d64f7856c"
      }
    },
    {
      "id": "percentile",
      "type": "snippet",
      "attributes": {
        "fileName": "percentile.md",
        "text": "Uses the percentile formula to calculate how many numbers in the given array are less or equal to the given value.\n\nUse `Array.prototype.reduce()` to calculate how many numbers are below the value and how many are the same value and apply the percentile formula.",
        "codeBlocks": {
          "es6": "const percentile = (arr, val) =>\n  (100 * arr.reduce((acc, v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), 0)) / arr.length;",
          "es5": "var percentile = function percentile(arr, val) {\n  return 100 * arr.reduce(function (acc, v) {\n    return acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0);\n  }, 0) / arr.length;\n};",
          "example": "percentile([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 6); // 55"
        },
        "tags": [
          "math",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "8343f8ddd30fced511584cb972818cf5c0e6e8cf9a6ea74071d254c3b6808061"
      }
    },
    {
      "id": "permutations",
      "type": "snippet",
      "attributes": {
        "fileName": "permutations.md",
        "text": "⚠️ **WARNING**: This function's execution time increases exponentially with each array element. Anything more than 8 to 10 entries will cause your browser to hang as it tries to solve all the different combinations.\n\nGenerates all permutations of an array's elements (contains duplicates).\n\nUse recursion.\nFor each element in the given array, create all the partial permutations for the rest of its elements.\nUse `Array.prototype.map()` to combine the element with each partial permutation, then `Array.prototype.reduce()` to combine all permutations in one array.\nBase cases are for array `length` equal to `2` or `1`.",
        "codeBlocks": {
          "es6": "const permutations = arr => {\n  if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr;\n  return arr.reduce(\n    (acc, item, i) =>\n      acc.concat(\n        permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [item, ...val])\n      ),\n    []\n  );\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 permutations = function permutations(arr) {\n  if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr;\n  return arr.reduce(function (acc, item, i) {\n    return acc.concat(permutations(_toConsumableArray(arr.slice(0, i)).concat(_toConsumableArray(arr.slice(i + 1)))).map(function (val) {\n      return [item].concat(_toConsumableArray(val));\n    }));\n  }, []);\n};",
          "example": "permutations([1, 33, 5]); // [ [ 1, 33, 5 ], [ 1, 5, 33 ], [ 33, 1, 5 ], [ 33, 5, 1 ], [ 5, 1, 33 ], [ 5, 33, 1 ] ]"
        },
        "tags": [
          "array",
          "recursion",
          "advanced"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "ed705722088f82143e0af891539884b168f192f28e2c3926d2a15a26ae9ef539"
      }
    },
    {
      "id": "pick",
      "type": "snippet",
      "attributes": {
        "fileName": "pick.md",
        "text": "Picks the key-value pairs corresponding to the given keys from an object.\n\nUse `Array.prototype.reduce()` to convert the filtered/picked keys back to an object with the corresponding key-value pairs if the key exists in the object.",
        "codeBlocks": {
          "es6": "const pick = (obj, arr) =>\n  arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {});",
          "es5": "var pick = function pick(obj, arr) {\n  return arr.reduce(function (acc, curr) {\n    return curr in obj && (acc[curr] = obj[curr]), acc;\n  }, {});\n};",
          "example": "pick({ a: 1, b: '2', c: 3 }, ['a', 'c']); // { 'a': 1, 'c': 3 }"
        },
        "tags": [
          "object",
          "array",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "31d70a01cc4a9045343efcd04f041bb6b4a9754dfa1665ed6aa546003803d6dd"
      }
    },
    {
      "id": "pickBy",
      "type": "snippet",
      "attributes": {
        "fileName": "pickBy.md",
        "text": "Creates an object composed of the properties the given function returns truthy for. The function is invoked with two arguments: (value, key).\n\nUse `Object.keys(obj)` and `Array.prototype.filter()`to remove the keys for which `fn` returns a falsey value.\nUse `Array.prototype.reduce()` to convert the filtered keys back to an object with the corresponding key-value pairs.",
        "codeBlocks": {
          "es6": "const pickBy = (obj, fn) =>\n  Object.keys(obj)\n    .filter(k => fn(obj[k], k))\n    .reduce((acc, key) => ((acc[key] = obj[key]), acc), {});",
          "es5": "var pickBy = function pickBy(obj, fn) {\n  return Object.keys(obj).filter(function (k) {\n    return fn(obj[k], k);\n  }).reduce(function (acc, key) {\n    return acc[key] = obj[key], acc;\n  }, {});\n};",
          "example": "pickBy({ a: 1, b: '2', c: 3 }, x => typeof x === 'number'); // { 'a': 1, 'c': 3 }"
        },
        "tags": [
          "object",
          "array",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "0842f93bde56f28c9663d341314b7e27b71a686784e7276b34909b0fa5551502"
      }
    },
    {
      "id": "pipeAsyncFunctions",
      "type": "snippet",
      "attributes": {
        "fileName": "pipeAsyncFunctions.md",
        "text": "Performs left-to-right function composition for asynchronous functions.\n\nUse `Array.prototype.reduce()` with the spread operator (`...`) to perform left-to-right function composition using `Promise.then()`.\nThe functions can return a combination of: simple values, `Promise`'s, or they can be defined as `async` ones returning through `await`.\nAll functions must be unary.",
        "codeBlocks": {
          "es6": "const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg));",
          "es5": "var pipeAsyncFunctions = function pipeAsyncFunctions() {\n  for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) {\n    fns[_key] = arguments[_key];\n  }\n\n  return function (arg) {\n    return fns.reduce(function (p, f) {\n      return p.then(f);\n    }, Promise.resolve(arg));\n  };\n};",
          "example": "const sum = pipeAsyncFunctions(\n  x => x + 1,\n  x => new Promise(resolve => setTimeout(() => resolve(x + 2), 1000)),\n  x => x + 3,\n  async x => (await x) + 4\n);\n(async() => {\n  console.log(await sum(5)); // 15 (after one second)\n})();"
        },
        "tags": [
          "adapter",
          "function",
          "promise",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "4815876fd6dbb17ad34c0d8918e7a72d837104f9beee7dc51b0fa73057b9e83e"
      }
    },
    {
      "id": "pipeFunctions",
      "type": "snippet",
      "attributes": {
        "fileName": "pipeFunctions.md",
        "text": "Performs left-to-right function composition.\n\nUse `Array.prototype.reduce()` with the spread operator (`...`) to perform left-to-right function composition.\nThe first (leftmost) function can accept one or more arguments; the remaining functions must be unary.",
        "codeBlocks": {
          "es6": "const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));",
          "es5": "var pipeFunctions = function pipeFunctions() {\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 add5 = x => x + 5;\nconst multiply = (x, y) => x * y;\nconst multiplyAndAdd5 = pipeFunctions(multiply, add5);\nmultiplyAndAdd5(5, 2); // 15"
        },
        "tags": [
          "adapter",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "3603cce07f53157cdf5d69e262bf0bd61c3103b5afd9e3d892cd4db39b037785"
      }
    },
    {
      "id": "pluralize",
      "type": "snippet",
      "attributes": {
        "fileName": "pluralize.md",
        "text": "Returns the singular or plural form of the word based on the input number. If the first argument is an `object`, it will use a closure by returning a function that can auto-pluralize words that don't simply end in `s` if the supplied dictionary contains the word.\n\nIf `num` is either `-1` or `1`, return the singular form of the word. If `num` is any other number, return the plural form. Omit the third argument to use the default of the singular word + `s`, or supply a custom pluralized word when necessary. If the first argument is an `object`, utilize a closure by returning a function which can use the supplied dictionary to resolve the correct plural form of the word.",
        "codeBlocks": {
          "es6": "const pluralize = (val, word, plural = word + 's') => {\n  const _pluralize = (num, word, plural = word + 's') =>\n    [1, -1].includes(Number(num)) ? word : plural;\n  if (typeof val === 'object') return (num, word) => _pluralize(num, word, val[word]);\n  return _pluralize(val, word, plural);\n};",
          "es5": "function _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nvar pluralize = function pluralize(val, word) {\n  var plural = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : word + 's';\n\n  var _pluralize = function _pluralize(num, word) {\n    var plural = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : word + 's';\n    return [1, -1].includes(Number(num)) ? word : plural;\n  };\n\n  if (_typeof(val) === 'object') return function (num, word) {\n    return _pluralize(num, word, val[word]);\n  };\n  return _pluralize(val, word, plural);\n};",
          "example": "pluralize(0, 'apple'); // 'apples'\npluralize(1, 'apple'); // 'apple'\npluralize(2, 'apple'); // 'apples'\npluralize(2, 'person', 'people'); // 'people'\n\nconst PLURALS = {\n  person: 'people',\n  radius: 'radii'\n};\nconst autoPluralize = pluralize(PLURALS);\nautoPluralize(2, 'person'); // 'people'"
        },
        "tags": [
          "string",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "9270afe4dfddee1974a2535ea2625e6130c41cbb890784ca837dd34df4efd030"
      }
    },
    {
      "id": "powerset",
      "type": "snippet",
      "attributes": {
        "fileName": "powerset.md",
        "text": "Returns the powerset of a given array of numbers.\n\nUse `Array.prototype.reduce()` combined with `Array.prototype.map()` to iterate over elements and combine into an array containing all combinations.",
        "codeBlocks": {
          "es6": "const powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]);",
          "es5": "var powerset = function powerset(arr) {\n  return arr.reduce(function (a, v) {\n    return a.concat(a.map(function (r) {\n      return [v].concat(r);\n    }));\n  }, [[]]);\n};",
          "example": "powerset([1, 2]); // [[], [1], [2], [2, 1]]"
        },
        "tags": [
          "math",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "21941200f0c5bfd1dedb00cd4a8dfd799062d7fe43cf8a82c0483e54b560ac0d"
      }
    },
    {
      "id": "prefix",
      "type": "snippet",
      "attributes": {
        "fileName": "prefix.md",
        "text": "Returns the prefixed version (if necessary) of a CSS property that the browser supports.\n\nUse `Array.prototype.findIndex()` on an array of vendor prefix strings to test if `document.body` has one of them defined in its `CSSStyleDeclaration` object, otherwise return `null`.\nUse `String.prototype.charAt()` and `String.prototype.toUpperCase()` to capitalize the property, which will be appended to the vendor prefix string.",
        "codeBlocks": {
          "es6": "const prefix = prop => {\n  const capitalizedProp = prop.charAt(0).toUpperCase() + prop.slice(1);\n  const prefixes = ['', 'webkit', 'moz', 'ms', 'o'];\n  const i = prefixes.findIndex(\n    prefix => typeof document.body.style[prefix ? prefix + capitalizedProp : prop] !== 'undefined'\n  );\n  return i !== -1 ? (i === 0 ? prop : prefixes[i] + capitalizedProp) : null;\n};",
          "es5": "var prefix = function prefix(prop) {\n  var capitalizedProp = prop.charAt(0).toUpperCase() + prop.slice(1);\n  var prefixes = ['', 'webkit', 'moz', 'ms', 'o'];\n  var i = prefixes.findIndex(function (prefix) {\n    return typeof document.body.style[prefix ? prefix + capitalizedProp : prop] !== 'undefined';\n  });\n  return i !== -1 ? i === 0 ? prop : prefixes[i] + capitalizedProp : null;\n};",
          "example": "prefix('appearance'); // 'appearance' on a supported browser, otherwise 'webkitAppearance', 'mozAppearance', 'msAppearance' or 'oAppearance'"
        },
        "tags": [
          "browser",
          "utility",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "e8875fbdf505642806ab6f98b68e4ebce935e87b78a639b74a3dce8eb6f6e9a5"
      }
    },
    {
      "id": "prettyBytes",
      "type": "snippet",
      "attributes": {
        "fileName": "prettyBytes.md",
        "text": "Converts a number in bytes to a human-readable string.\n\nUse an array dictionary of units to be accessed based on the exponent.\nUse `Number.toPrecision()` to truncate the number to a certain number of digits.\nReturn the prettified string by building it up, taking into account the supplied options and whether it is negative or not.\nOmit the second argument, `precision`, to use a default precision of `3` digits.\nOmit the third argument, `addSpace`, to add space between the number and unit by default.",
        "codeBlocks": {
          "es6": "const prettyBytes = (num, precision = 3, addSpace = true) => {\n  const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];\n  if (Math.abs(num) < 1) return num + (addSpace ? ' ' : '') + UNITS[0];\n  const exponent = Math.min(Math.floor(Math.log10(num < 0 ? -num : num) / 3), UNITS.length - 1);\n  const n = Number(((num < 0 ? -num : num) / 1000 ** exponent).toPrecision(precision));\n  return (num < 0 ? '-' : '') + n + (addSpace ? ' ' : '') + UNITS[exponent];\n};",
          "es5": "var prettyBytes = function prettyBytes(num) {\n  var precision = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 3;\n  var addSpace = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n  var UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];\n  if (Math.abs(num) < 1) return num + (addSpace ? ' ' : '') + UNITS[0];\n  var exponent = Math.min(Math.floor(Math.log10(num < 0 ? -num : num) / 3), UNITS.length - 1);\n  var n = Number(((num < 0 ? -num : num) / Math.pow(1000, exponent)).toPrecision(precision));\n  return (num < 0 ? '-' : '') + n + (addSpace ? ' ' : '') + UNITS[exponent];\n};",
          "example": "prettyBytes(1000); // \"1 KB\"\nprettyBytes(-27145424323.5821, 5); // \"-27.145 GB\"\nprettyBytes(123456789, 3, false); // \"123MB\""
        },
        "tags": [
          "utility",
          "string",
          "math",
          "advanced"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "5f269ecc2da6d263be94fb94725167f0a2002e1eeb3fd2123ffc9403a2ef2933"
      }
    },
    {
      "id": "primes",
      "type": "snippet",
      "attributes": {
        "fileName": "primes.md",
        "text": "Generates primes up to a given number, using the Sieve of Eratosthenes.\n\nGenerate an array from `2` to the given number. Use `Array.prototype.filter()` to filter out the values divisible by any number from `2` to the square root of the provided number.",
        "codeBlocks": {
          "es6": "const primes = num => {\n  let arr = Array.from({ length: num - 1 }).map((x, i) => i + 2),\n    sqroot = Math.floor(Math.sqrt(num)),\n    numsTillSqroot = Array.from({ length: sqroot - 1 }).map((x, i) => i + 2);\n  numsTillSqroot.forEach(x => (arr = arr.filter(y => y % x !== 0 || y === x)));\n  return arr;\n};",
          "es5": "var primes = function primes(num) {\n  var arr = Array.from({\n    length: num - 1\n  }).map(function (x, i) {\n    return i + 2;\n  }),\n      sqroot = Math.floor(Math.sqrt(num)),\n      numsTillSqroot = Array.from({\n    length: sqroot - 1\n  }).map(function (x, i) {\n    return i + 2;\n  });\n  numsTillSqroot.forEach(function (x) {\n    return arr = arr.filter(function (y) {\n      return y % x !== 0 || y === x;\n    });\n  });\n  return arr;\n};",
          "example": "primes(10); // [2,3,5,7]"
        },
        "tags": [
          "math",
          "array",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "6d0f66159240aa2ef6015747b2530d0a7191ec3810f3c502d9bd156012603d45"
      }
    },
    {
      "id": "promisify",
      "type": "snippet",
      "attributes": {
        "fileName": "promisify.md",
        "text": "Converts an asynchronous function to return a promise.\n\nUse currying to return a function returning a `Promise` that calls the original function.\nUse the `...rest` operator to pass in all the parameters.\n\n*In Node 8+, you can use [`util.promisify`](https://nodejs.org/api/util.html#util_util_promisify_original)*",
        "codeBlocks": {
          "es6": "const promisify = func => (...args) =>\n  new Promise((resolve, reject) =>\n    func(...args, (err, result) => (err ? reject(err) : resolve(result)))\n  );",
          "es5": "var promisify = function promisify(func) {\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 new Promise(function (resolve, reject) {\n      return func.apply(void 0, args.concat([function (err, result) {\n        return err ? reject(err) : resolve(result);\n      }]));\n    });\n  };\n};",
          "example": "const delay = promisify((d, cb) => setTimeout(cb, d));\ndelay(2000).then(() => console.log('Hi!')); // // Promise resolves after 2s"
        },
        "tags": [
          "adapter",
          "function",
          "promise",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "d269b5a8124cd646189075c2679331bbadbb3cd535a1e3135d12f7de46836dda"
      }
    },
    {
      "id": "pull",
      "type": "snippet",
      "attributes": {
        "fileName": "pull.md",
        "text": "Mutates the original array to filter out the values specified.\n\nUse `Array.prototype.filter()` and `Array.prototype.includes()` to pull out the values that are not needed.\nUse `Array.prototype.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.prototype.push()` to re-populate it with only the pulled values.\n\n_(For a snippet that does not mutate the original array see [`without`](#without))_",
        "codeBlocks": {
          "es6": "const pull = (arr, ...args) => {\n  let argState = Array.isArray(args[0]) ? args[0] : args;\n  let pulled = arr.filter((v, i) => !argState.includes(v));\n  arr.length = 0;\n  pulled.forEach(v => arr.push(v));\n};",
          "es5": "var pull = function pull(arr) {\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  var argState = Array.isArray(args[0]) ? args[0] : args;\n  var pulled = arr.filter(function (v, i) {\n    return !argState.includes(v);\n  });\n  arr.length = 0;\n  pulled.forEach(function (v) {\n    return arr.push(v);\n  });\n};",
          "example": "let myArray = ['a', 'b', 'c', 'a', 'b', 'c'];\npull(myArray, 'a', 'c'); // myArray = [ 'b', 'b' ]"
        },
        "tags": [
          "array",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "eed98a26fc85c7684508f33ab909070e6205747990c5e4562f2d120728bd6a3c"
      }
    },
    {
      "id": "pullAtIndex",
      "type": "snippet",
      "attributes": {
        "fileName": "pullAtIndex.md",
        "text": "Mutates the original array to filter out the values at the specified indexes.\n\nUse `Array.prototype.filter()` and `Array.prototype.includes()` to pull out the values that are not needed.\nUse `Array.prototype.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.prototype.push()` to re-populate it with only the pulled values.\nUse `Array.prototype.push()` to keep track of pulled values",
        "codeBlocks": {
          "es6": "const pullAtIndex = (arr, pullArr) => {\n  let removed = [];\n  let pulled = arr\n    .map((v, i) => (pullArr.includes(i) ? removed.push(v) : v))\n    .filter((v, i) => !pullArr.includes(i));\n  arr.length = 0;\n  pulled.forEach(v => arr.push(v));\n  return removed;\n};",
          "es5": "var pullAtIndex = function pullAtIndex(arr, pullArr) {\n  var removed = [];\n  var pulled = arr.map(function (v, i) {\n    return pullArr.includes(i) ? removed.push(v) : v;\n  }).filter(function (v, i) {\n    return !pullArr.includes(i);\n  });\n  arr.length = 0;\n  pulled.forEach(function (v) {\n    return arr.push(v);\n  });\n  return removed;\n};",
          "example": "let myArray = ['a', 'b', 'c', 'd'];\nlet pulled = pullAtIndex(myArray, [1, 3]); // myArray = [ 'a', 'c' ] , pulled = [ 'b', 'd' ]"
        },
        "tags": [
          "array",
          "advanced"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "d034820c71f581ba5cdce7ab47e4fb0ff64baf554c1f19a0e45c5d0e71eeae4c"
      }
    },
    {
      "id": "pullAtValue",
      "type": "snippet",
      "attributes": {
        "fileName": "pullAtValue.md",
        "text": "Mutates the original array to filter out the values specified. Returns the removed elements.\n\nUse `Array.prototype.filter()` and `Array.prototype.includes()` to pull out the values that are not needed.\nUse `Array.prototype.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.prototype.push()` to re-populate it with only the pulled values.\nUse `Array.prototype.push()` to keep track of pulled values",
        "codeBlocks": {
          "es6": "const pullAtValue = (arr, pullArr) => {\n  let removed = [],\n    pushToRemove = arr.forEach((v, i) => (pullArr.includes(v) ? removed.push(v) : v)),\n    mutateTo = arr.filter((v, i) => !pullArr.includes(v));\n  arr.length = 0;\n  mutateTo.forEach(v => arr.push(v));\n  return removed;\n};",
          "es5": "var pullAtValue = function pullAtValue(arr, pullArr) {\n  var removed = [],\n      pushToRemove = arr.forEach(function (v, i) {\n    return pullArr.includes(v) ? removed.push(v) : v;\n  }),\n      mutateTo = arr.filter(function (v, i) {\n    return !pullArr.includes(v);\n  });\n  arr.length = 0;\n  mutateTo.forEach(function (v) {\n    return arr.push(v);\n  });\n  return removed;\n};",
          "example": "let myArray = ['a', 'b', 'c', 'd'];\nlet pulled = pullAtValue(myArray, ['b', 'd']); // myArray = [ 'a', 'c' ] , pulled = [ 'b', 'd' ]"
        },
        "tags": [
          "array",
          "advanced"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "e1e0ce4362866a007fe261a0b7995282b5e579397517a71202cd9bb89d021d48"
      }
    },
    {
      "id": "pullBy",
      "type": "snippet",
      "attributes": {
        "fileName": "pullBy.md",
        "text": "Mutates the original array to filter out the values specified, based on a given iterator function.\n\nCheck if the last argument provided in a function.\nUse `Array.prototype.map()` to apply the iterator function `fn` to all array elements.\nUse `Array.prototype.filter()` and `Array.prototype.includes()` to pull out the values that are not needed.\nUse `Array.prototype.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.prototype.push()` to re-populate it with only the pulled values.",
        "codeBlocks": {
          "es6": "const pullBy = (arr, ...args) => {\n  const length = args.length;\n  let fn = length > 1 ? args[length - 1] : undefined;\n  fn = typeof fn == 'function' ? (args.pop(), fn) : undefined;\n  let argState = (Array.isArray(args[0]) ? args[0] : args).map(val => fn(val));\n  let pulled = arr.filter((v, i) => !argState.includes(fn(v)));\n  arr.length = 0;\n  pulled.forEach(v => arr.push(v));\n};",
          "es5": "var pullBy = function pullBy(arr) {\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  var length = args.length;\n  var fn = length > 1 ? args[length - 1] : undefined;\n  fn = typeof fn == 'function' ? (args.pop(), fn) : undefined;\n  var argState = (Array.isArray(args[0]) ? args[0] : args).map(function (val) {\n    return fn(val);\n  });\n  var pulled = arr.filter(function (v, i) {\n    return !argState.includes(fn(v));\n  });\n  arr.length = 0;\n  pulled.forEach(function (v) {\n    return arr.push(v);\n  });\n};",
          "example": "var myArray = [{ x: 1 }, { x: 2 }, { x: 3 }, { x: 1 }];\npullBy(myArray, [{ x: 1 }, { x: 3 }], o => o.x); // myArray = [{ x: 2 }]"
        },
        "tags": [
          "array",
          "function",
          "advanced"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "6e597c1a6a73606b584d7be8f1a4974cd312a2ec5c500078ce146609e6ecc537"
      }
    },
    {
      "id": "radsToDegrees",
      "type": "snippet",
      "attributes": {
        "fileName": "radsToDegrees.md",
        "text": "Converts an angle from radians to degrees.\n\nUse `Math.PI` and the radian to degree formula to convert the angle from radians to degrees.",
        "codeBlocks": {
          "es6": "const radsToDegrees = rad => (rad * 180.0) / Math.PI;",
          "es5": "var radsToDegrees = function radsToDegrees(rad) {\n  return rad * 180.0 / Math.PI;\n};",
          "example": "radsToDegrees(Math.PI / 2); // 90"
        },
        "tags": [
          "math",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "b749df623cb50779135ffb38d968cc58d9a8d5d1eadeacfa1d9eec43641c8e9e"
      }
    },
    {
      "id": "randomHexColorCode",
      "type": "snippet",
      "attributes": {
        "fileName": "randomHexColorCode.md",
        "text": "Generates a random hexadecimal color code.\n\nUse `Math.random` to generate a random 24-bit(6x4bits) hexadecimal number. Use bit shifting and then convert it to an hexadecimal String using `toString(16)`.",
        "codeBlocks": {
          "es6": "const randomHexColorCode = () => {\n  let n = (Math.random() * 0xfffff * 1000000).toString(16);\n  return '#' + n.slice(0, 6);\n};",
          "es5": "var randomHexColorCode = function randomHexColorCode() {\n  var n = (Math.random() * 0xfffff * 1000000).toString(16);\n  return '#' + n.slice(0, 6);\n};",
          "example": "randomHexColorCode(); // \"#e34155\""
        },
        "tags": [
          "utility",
          "random",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "038ef05a24294c7bb16d04d465628066418099465e99c020a21d073372ebe0cc"
      }
    },
    {
      "id": "randomIntArrayInRange",
      "type": "snippet",
      "attributes": {
        "fileName": "randomIntArrayInRange.md",
        "text": "Returns an array of n random integers in the specified range.\n\nUse `Array.from()` to create an empty array of the specific length, `Math.random()` to generate a random number and map it to the desired range, using `Math.floor()` to make it an integer.",
        "codeBlocks": {
          "es6": "const randomIntArrayInRange = (min, max, n = 1) =>\n  Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min);",
          "es5": "var randomIntArrayInRange = function randomIntArrayInRange(min, max) {\n  var n = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n  return Array.from({\n    length: n\n  }, function () {\n    return Math.floor(Math.random() * (max - min + 1)) + min;\n  });\n};",
          "example": "randomIntArrayInRange(12, 35, 10); // [ 34, 14, 27, 17, 30, 27, 20, 26, 21, 14 ]"
        },
        "tags": [
          "math",
          "utility",
          "random",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "f5c5c857e9d57ef7c22734163098e058d050ad0a9e3f28c57b307695ee982514"
      }
    },
    {
      "id": "randomIntegerInRange",
      "type": "snippet",
      "attributes": {
        "fileName": "randomIntegerInRange.md",
        "text": "Returns a random integer in the specified range.\n\nUse `Math.random()` to generate a random number and map it to the desired range, using `Math.floor()` to make it an integer.",
        "codeBlocks": {
          "es6": "const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;",
          "es5": "var randomIntegerInRange = function randomIntegerInRange(min, max) {\n  return Math.floor(Math.random() * (max - min + 1)) + min;\n};",
          "example": "randomIntegerInRange(0, 5); // 2"
        },
        "tags": [
          "math",
          "utility",
          "random",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "791ff20ffbb7736f586cafa1106f6e77e8e89d497bc8a479c0a0cd708fb907ce"
      }
    },
    {
      "id": "randomNumberInRange",
      "type": "snippet",
      "attributes": {
        "fileName": "randomNumberInRange.md",
        "text": "Returns a random number in the specified range.\n\nUse `Math.random()` to generate a random value, map it to the desired range using multiplication.",
        "codeBlocks": {
          "es6": "const randomNumberInRange = (min, max) => Math.random() * (max - min) + min;",
          "es5": "var randomNumberInRange = function randomNumberInRange(min, max) {\n  return Math.random() * (max - min) + min;\n};",
          "example": "randomNumberInRange(2, 10); // 6.0211363285087005"
        },
        "tags": [
          "math",
          "utility",
          "random",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "0ebc2c972fac7d4a8438188025158e0f75456b3787ecf2faae9d3db8d12ee677"
      }
    },
    {
      "id": "readFileLines",
      "type": "snippet",
      "attributes": {
        "fileName": "readFileLines.md",
        "text": "Returns an array of lines from the specified file.\n\nUse `readFileSync` function in `fs` node package to create a `Buffer` from a file.\nconvert buffer to string using `toString(encoding)` function.\ncreating an array from contents of file by `split`ing file content line by line (each `\\n`).",
        "codeBlocks": {
          "es6": "const fs = require('fs');\nconst readFileLines = filename =>\n  fs\n    .readFileSync(filename)\n    .toString('UTF8')\n    .split('\\n');",
          "es5": "var fs = require('fs');\n\nvar readFileLines = function readFileLines(filename) {\n  return fs.readFileSync(filename).toString('UTF8').split('\\n');\n};",
          "example": "/*\ncontents of test.txt :\n  line1\n  line2\n  line3\n  ___________________________\n*/\nlet arr = readFileLines('test.txt');\nconsole.log(arr); // ['line1', 'line2', 'line3']"
        },
        "tags": [
          "node",
          "array",
          "string",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "8463ee2c8b3e9165b105ee90b59e143a4f1c8b60f8080770d94ec0bbcb455bb6"
      }
    },
    {
      "id": "rearg",
      "type": "snippet",
      "attributes": {
        "fileName": "rearg.md",
        "text": "Creates a function that invokes the provided function with its arguments arranged according to the specified indexes.\n\nUse `Array.prototype.map()` to reorder arguments based on `indexes` in combination with the spread operator (`...`) to pass the transformed arguments to `fn`.",
        "codeBlocks": {
          "es6": "const rearg = (fn, indexes) => (...args) => fn(...indexes.map(i => args[i]));",
          "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 rearg = function rearg(fn, indexes) {\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(indexes.map(function (i) {\n      return args[i];\n    })));\n  };\n};",
          "example": "var rearged = rearg(\n  function(a, b, c) {\n    return [a, b, c];\n  },\n  [2, 0, 1]\n);\nrearged('b', 'c', 'a'); // ['a', 'b', 'c']"
        },
        "tags": [
          "adapter",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "b0007cb91fbeab8d350028d5ae4448c366e79264de6c88e8fa15743158b1a927"
      }
    },
    {
      "id": "recordAnimationFrames",
      "type": "snippet",
      "attributes": {
        "fileName": "recordAnimationFrames.md",
        "text": "Invokes the provided callback on each animation frame.\n\nUse recursion. \nProvided that `running` is `true`, continue invoking `window.requestAnimationFrame()` which invokes the provided callback. \nReturn an object with two methods `start` and `stop` to allow manual control of the recording. \nOmit the second argument, `autoStart`, to implicitly call `start` when the function is invoked.",
        "codeBlocks": {
          "es6": "const recordAnimationFrames = (callback, autoStart = true) => {\n  let running = true,\n    raf;\n  const stop = () => {\n    running = false;\n    cancelAnimationFrame(raf);\n  };\n  const start = () => {\n    running = true;\n    run();\n  };\n  const run = () => {\n    raf = requestAnimationFrame(() => {\n      callback();\n      if (running) run();\n    });\n  };\n  if (autoStart) start();\n  return { start, stop };\n};",
          "es5": "var recordAnimationFrames = function recordAnimationFrames(callback) {\n  var autoStart = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n  var running = true,\n      raf;\n\n  var stop = function stop() {\n    running = false;\n    cancelAnimationFrame(raf);\n  };\n\n  var start = function start() {\n    running = true;\n    run();\n  };\n\n  var run = function run() {\n    raf = requestAnimationFrame(function () {\n      callback();\n      if (running) run();\n    });\n  };\n\n  if (autoStart) start();\n  return {\n    start: start,\n    stop: stop\n  };\n};",
          "example": "const cb = () => console.log('Animation frame fired');\nconst recorder = recordAnimationFrames(cb); // logs 'Animation frame fired' on each animation frame\nrecorder.stop(); // stops logging\nrecorder.start(); // starts again\nconst recorder2 = recordAnimationFrames(cb, false); // `start` needs to be explicitly called to begin recording frames"
        },
        "tags": [
          "browser",
          "utility",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "461445d77d76f9f3bc05c2bc534cfb551689a99b1b73995ba7f4066a38c60fc7"
      }
    },
    {
      "id": "redirect",
      "type": "snippet",
      "attributes": {
        "fileName": "redirect.md",
        "text": "Redirects to a specified URL.\n\nUse `window.location.href` or `window.location.replace()` to redirect to `url`.\nPass a second argument to simulate a link click (`true` - default) or an HTTP redirect (`false`).",
        "codeBlocks": {
          "es6": "const redirect = (url, asLink = true) =>\n  asLink ? (window.location.href = url) : window.location.replace(url);",
          "es5": "var redirect = function redirect(url) {\n  var asLink = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n  return asLink ? window.location.href = url : window.location.replace(url);\n};",
          "example": "redirect('https://google.com');"
        },
        "tags": [
          "browser",
          "url",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "dba349eee909dff1e13e6708ac067e1e7e776ff5862e79097aca630548846ed6"
      }
    },
    {
      "id": "reducedFilter",
      "type": "snippet",
      "attributes": {
        "fileName": "reducedFilter.md",
        "text": "Filter an array of objects based on a condition while also filtering out unspecified keys.\n\nUse `Array.prototype.filter()` to filter the array based on the predicate `fn` so that it returns the objects for which the condition returned a truthy value.\nOn the filtered array, use `Array.prototype.map()` to return the new object using `Array.prototype.reduce()` to filter out the keys which were not supplied as the `keys` argument.",
        "codeBlocks": {
          "es6": "const reducedFilter = (data, keys, fn) =>\n  data.filter(fn).map(el =>\n    keys.reduce((acc, key) => {\n      acc[key] = el[key];\n      return acc;\n    }, {})\n  );",
          "es5": "var reducedFilter = function reducedFilter(data, keys, fn) {\n  return data.filter(fn).map(function (el) {\n    return keys.reduce(function (acc, key) {\n      acc[key] = el[key];\n      return acc;\n    }, {});\n  });\n};",
          "example": "const data = [\n  {\n    id: 1,\n    name: 'john',\n    age: 24\n  },\n  {\n    id: 2,\n    name: 'mike',\n    age: 50\n  }\n];\n\nreducedFilter(data, ['id', 'name'], item => item.age > 24); // [{ id: 2, name: 'mike'}]"
        },
        "tags": [
          "array",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "90f20d7a605d4ec82be0bf5d4891d16d68639e9fbce578fe1c7e38c0d9027f03"
      }
    },
    {
      "id": "reduceSuccessive",
      "type": "snippet",
      "attributes": {
        "fileName": "reduceSuccessive.md",
        "text": "Applies a function against an accumulator and each element in the array (from left to right), returning an array of successively reduced values.\n\nUse `Array.prototype.reduce()` to apply the given function to the given array, storing each new result.",
        "codeBlocks": {
          "es6": "const reduceSuccessive = (arr, fn, acc) =>\n  arr.reduce((res, val, i, arr) => (res.push(fn(res.slice(-1)[0], val, i, arr)), res), [acc]);",
          "es5": "var reduceSuccessive = function reduceSuccessive(arr, fn, acc) {\n  return arr.reduce(function (res, val, i, arr) {\n    return res.push(fn(res.slice(-1)[0], val, i, arr)), res;\n  }, [acc]);\n};",
          "example": "reduceSuccessive([1, 2, 3, 4, 5, 6], (acc, val) => acc + val, 0); // [0, 1, 3, 6, 10, 15, 21]"
        },
        "tags": [
          "array",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "2eaf8ad72f65e8c4476c13e1c9b88967346df47c9cfddb6c9a7edcebcdb65304"
      }
    },
    {
      "id": "reduceWhich",
      "type": "snippet",
      "attributes": {
        "fileName": "reduceWhich.md",
        "text": "Returns the minimum/maximum value of an array, after applying the provided function to set comparing rule.\n\nUse `Array.prototype.reduce()` in combination with the `comparator` function to get the appropriate element in the array.\nYou can omit the second parameter, `comparator`, to use the default one that returns the minimum element in the array.",
        "codeBlocks": {
          "es6": "const reduceWhich = (arr, comparator = (a, b) => a - b) =>\n  arr.reduce((a, b) => (comparator(a, b) >= 0 ? b : a));",
          "es5": "var reduceWhich = function reduceWhich(arr) {\n  var comparator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (a, b) {\n    return a - b;\n  };\n  return arr.reduce(function (a, b) {\n    return comparator(a, b) >= 0 ? b : a;\n  });\n};",
          "example": "reduceWhich([1, 3, 2]); // 1\nreduceWhich([1, 3, 2], (a, b) => b - a); // 3\nreduceWhich(\n  [{ name: 'Tom', age: 12 }, { name: 'Jack', age: 18 }, { name: 'Lucy', age: 9 }],\n  (a, b) => a.age - b.age\n); // {name: \"Lucy\", age: 9}"
        },
        "tags": [
          "array",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "f0ac72c245cd8a375c6838281de679f0bfbe4326277ef64bf36589eede9d82fe"
      }
    },
    {
      "id": "reject",
      "type": "snippet",
      "attributes": {
        "fileName": "reject.md",
        "text": "Takes a predicate and array, like `Array.prototype.filter()`, but only keeps `x` if `pred(x) === false`.",
        "codeBlocks": {
          "es6": "const reject = (pred, array) => array.filter((...args) => !pred(...args));",
          "es5": "var reject = function reject(pred, array) {\n  return array.filter(function () {\n    return !pred.apply(void 0, arguments);\n  });\n};",
          "example": "reject(x => x % 2 === 0, [1, 2, 3, 4, 5]); // [1, 3, 5]\nreject(word => word.length > 4, ['Apple', 'Pear', 'Kiwi', 'Banana']); // ['Pear', 'Kiwi']"
        },
        "tags": [
          "array",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "523ed896411e3460f65347a417d12e1ec2c62cc0d97ae474d69927d12c01b4c8"
      }
    },
    {
      "id": "remove",
      "type": "snippet",
      "attributes": {
        "fileName": "remove.md",
        "text": "Removes elements from an array for which the given function returns `false`.\n\nUse `Array.prototype.filter()` to find array elements that return truthy values and `Array.prototype.reduce()` to remove elements using `Array.prototype.splice()`.\nThe `func` is invoked with three arguments (`value, index, array`).",
        "codeBlocks": {
          "es6": "const remove = (arr, func) =>\n  Array.isArray(arr)\n    ? arr.filter(func).reduce((acc, val) => {\n      arr.splice(arr.indexOf(val), 1);\n      return acc.concat(val);\n    }, [])\n    : [];",
          "es5": "var remove = function remove(arr, func) {\n  return Array.isArray(arr) ? arr.filter(func).reduce(function (acc, val) {\n    arr.splice(arr.indexOf(val), 1);\n    return acc.concat(val);\n  }, []) : [];\n};",
          "example": "remove([1, 2, 3, 4], n => n % 2 === 0); // [2, 4]"
        },
        "tags": [
          "array",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "ec9cb9384817f84cf0bacd62a23b69b2304fa2cf0352b16d3950b21d48c04f11"
      }
    },
    {
      "id": "removeNonASCII",
      "type": "snippet",
      "attributes": {
        "fileName": "removeNonASCII.md",
        "text": "Removes non-printable ASCII characters.\n\nUse a regular expression to remove non-printable ASCII characters.",
        "codeBlocks": {
          "es6": "const removeNonASCII = str => str.replace(/[^\\x20-\\x7E]/g, '');",
          "es5": "var removeNonASCII = function removeNonASCII(str) {\n  return str.replace(/[^\\x20-\\x7E]/g, '');\n};",
          "example": "removeNonASCII('äÄçÇéÉêlorem-ipsumöÖÐþúÚ'); // 'lorem-ipsum'"
        },
        "tags": [
          "string",
          "regexp",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "00483703389f0ba2b0ed4bdb8ef9f68e4de1a19b209655d85e4fcef0a16a660c"
      }
    },
    {
      "id": "renameKeys",
      "type": "snippet",
      "attributes": {
        "fileName": "renameKeys.md",
        "text": "Replaces the names of multiple object keys with the values provided.\n\nUse `Object.keys()` in combination with `Array.prototype.reduce()` and the spread operator (`...`) to get the object's keys and rename them according to `keysMap`.",
        "codeBlocks": {
          "es6": "const renameKeys = (keysMap, obj) =>\n  Object.keys(obj).reduce(\n    (acc, key) => ({\n      ...acc,\n      ...{ [keysMap[key] || key]: obj[key] }\n    }),\n    {}\n  );",
          "es5": "function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar renameKeys = function renameKeys(keysMap, obj) {\n  return Object.keys(obj).reduce(function (acc, key) {\n    return _objectSpread({}, acc, _defineProperty({}, keysMap[key] || key, obj[key]));\n  }, {});\n};",
          "example": "const obj = { name: 'Bobo', job: 'Front-End Master', shoeSize: 100 };\nrenameKeys({ name: 'firstName', job: 'passion' }, obj); // { firstName: 'Bobo', passion: 'Front-End Master', shoeSize: 100 }"
        },
        "tags": [
          "object",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "bf42670ada90c9ea2a790523ce7ea1f140523f5d47b0f06808c32e4f174906d8"
      }
    },
    {
      "id": "reverseString",
      "type": "snippet",
      "attributes": {
        "fileName": "reverseString.md",
        "text": "Reverses a string.\n\nUse the spread operator (`...`) and `Array.prototype.reverse()` to reverse the order of the characters in the string.\nCombine characters to get a string using `String.prototype.join('')`.",
        "codeBlocks": {
          "es6": "const reverseString = str => [...str].reverse().join('');",
          "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 reverseString = function reverseString(str) {\n  return _toConsumableArray(str).reverse().join('');\n};",
          "example": "reverseString('foobar'); // 'raboof'"
        },
        "tags": [
          "string",
          "array",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "32cbb7ef4ab365f228c244ad3ad8b87d88ef08426807031dbd87b709c76c61d4"
      }
    },
    {
      "id": "RGBToHex",
      "type": "snippet",
      "attributes": {
        "fileName": "RGBToHex.md",
        "text": "Converts the values of RGB components to a color code.\n\nConvert given RGB parameters to hexadecimal string using bitwise left-shift operator (`<<`) and `toString(16)`, then `String.padStart(6,'0')` to get a 6-digit hexadecimal value.",
        "codeBlocks": {
          "es6": "const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');",
          "es5": "var RGBToHex = function RGBToHex(r, g, b) {\n  return ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');\n};",
          "example": "RGBToHex(255, 165, 1); // 'ffa501'"
        },
        "tags": [
          "utility",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "92e4282492b80dbbd7efa34ae308bcda2c8c6865615e64049bf34dd8eb3f4810"
      }
    },
    {
      "id": "round",
      "type": "snippet",
      "attributes": {
        "fileName": "round.md",
        "text": "Rounds a number to a specified amount of digits.\n\nUse `Math.round()` and template literals to round the number to the specified number of digits.\nOmit the second argument, `decimals` to round to an integer.",
        "codeBlocks": {
          "es6": "const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);",
          "es5": "var round = function round(n) {\n  var decimals = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n  return Number(\"\".concat(Math.round(\"\".concat(n, \"e\").concat(decimals)), \"e-\").concat(decimals));\n};",
          "example": "round(1.005, 2); // 1.01"
        },
        "tags": [
          "math",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "6170ee4eec91a2bf73961a9cc15ce90c48fbf15caf11363c12b3d6478efa48ea"
      }
    },
    {
      "id": "runAsync",
      "type": "snippet",
      "attributes": {
        "fileName": "runAsync.md",
        "text": "Runs a function in a separate thread by using a [Web Worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers), allowing long running functions to not block the UI.\n\nCreate a new `Worker` using a `Blob` object URL, the contents of which should be the stringified version of the supplied function.\nImmediately post the return value of calling the function back.\nReturn a promise, listening for `onmessage` and `onerror` events and resolving the data posted back from the worker, or throwing an error.",
        "codeBlocks": {
          "es6": "const runAsync = fn => {\n  const worker = new Worker(\n    URL.createObjectURL(new Blob([`postMessage((${fn})());`]), {\n      type: 'application/javascript; charset=utf-8'\n    })\n  );\n  return new Promise((res, rej) => {\n    worker.onmessage = ({ data }) => {\n      res(data), worker.terminate();\n    };\n    worker.onerror = err => {\n      rej(err), worker.terminate();\n    };\n  });\n};",
          "es5": "var runAsync = function runAsync(fn) {\n  var worker = new Worker(URL.createObjectURL(new Blob([\"postMessage((\".concat(fn, \")());\")]), {\n    type: 'application/javascript; charset=utf-8'\n  }));\n  return new Promise(function (res, rej) {\n    worker.onmessage = function (_ref) {\n      var data = _ref.data;\n      res(data), worker.terminate();\n    };\n\n    worker.onerror = function (err) {\n      rej(err), worker.terminate();\n    };\n  });\n};",
          "example": "const longRunningFunction = () => {\n  let result = 0;\n  for (let i = 0; i < 1000; i++)\n    for (let j = 0; j < 700; j++) for (let k = 0; k < 300; k++) result = result + i + j + k;\n\n  return result;\n};\n/*\n  NOTE: Since the function is running in a different context, closures are not supported.\n  The function supplied to `runAsync` gets stringified, so everything becomes literal.\n  All variables and functions must be defined inside.\n*/\nrunAsync(longRunningFunction).then(console.log); // 209685000000\nrunAsync(() => 10 ** 3).then(console.log); // 1000\nlet outsideVariable = 50;\nrunAsync(() => typeof outsideVariable).then(console.log); // 'undefined'"
        },
        "tags": [
          "browser",
          "function",
          "advanced",
          "promise",
          "url"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "39ed2d279733ad4061a381d85afccd111f56d15053132858991daf02e2c7fb36"
      }
    },
    {
      "id": "runPromisesInSeries",
      "type": "snippet",
      "attributes": {
        "fileName": "runPromisesInSeries.md",
        "text": "Runs an array of promises in series.\n\nUse `Array.prototype.reduce()` to create a promise chain, where each promise returns the next promise when resolved.",
        "codeBlocks": {
          "es6": "const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());",
          "es5": "var runPromisesInSeries = function runPromisesInSeries(ps) {\n  return ps.reduce(function (p, next) {\n    return p.then(next);\n  }, Promise.resolve());\n};",
          "example": "const delay = d => new Promise(r => setTimeout(r, d));\nrunPromisesInSeries([() => delay(1000), () => delay(2000)]); // Executes each promise sequentially, taking a total of 3 seconds to complete"
        },
        "tags": [
          "function",
          "promise",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "b47ebe31470158288d2f5c1ff80fd72b2b5779442ff1b2732217c09adb976447"
      }
    },
    {
      "id": "sample",
      "type": "snippet",
      "attributes": {
        "fileName": "sample.md",
        "text": "Returns a random element from an array.\n\nUse `Math.random()` to generate a random number, multiply it by `length` and round it off to the nearest whole number using `Math.floor()`.\nThis method also works with strings.",
        "codeBlocks": {
          "es6": "const sample = arr => arr[Math.floor(Math.random() * arr.length)];",
          "es5": "var sample = function sample(arr) {\n  return arr[Math.floor(Math.random() * arr.length)];\n};",
          "example": "sample([3, 7, 9, 11]); // 9"
        },
        "tags": [
          "array",
          "random",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "42ed9355cd80aaaa2370363e05913b04d89cb6daf46ac7459ea6a0f2bec2b93c"
      }
    },
    {
      "id": "sampleSize",
      "type": "snippet",
      "attributes": {
        "fileName": "sampleSize.md",
        "text": "Gets `n` random elements at unique keys from `array` up to the size of `array`.\n\nShuffle the array using the [Fisher-Yates algorithm](https://github.com/30-seconds/30-seconds-of-code#shuffle).\nUse `Array.prototype.slice()` to get the first `n` elements.\nOmit the second argument, `n` to get only one element at random from the array.",
        "codeBlocks": {
          "es6": "const sampleSize = ([...arr], n = 1) => {\n  let m = arr.length;\n  while (m) {\n    const i = Math.floor(Math.random() * m--);\n    [arr[m], arr[i]] = [arr[i], arr[m]];\n  }\n  return arr.slice(0, n);\n};",
          "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 sampleSize = function sampleSize(_ref) {\n  var _ref2 = _toArray(_ref),\n      arr = _ref2.slice(0);\n\n  var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;\n  var m = arr.length;\n\n  while (m) {\n    var i = Math.floor(Math.random() * m--);\n    var _ref3 = [arr[i], arr[m]];\n    arr[m] = _ref3[0];\n    arr[i] = _ref3[1];\n  }\n\n  return arr.slice(0, n);\n};",
          "example": "sampleSize([1, 2, 3], 2); // [3,1]\nsampleSize([1, 2, 3], 4); // [2,3,1]"
        },
        "tags": [
          "array",
          "random",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "dd7864be6b3d433e2a64999561cb152f012ccf2a611c5efa76e38cc2d72497e8"
      }
    },
    {
      "id": "scrollToTop",
      "type": "snippet",
      "attributes": {
        "fileName": "scrollToTop.md",
        "text": "Smooth-scrolls to the top of the page.\n\nGet distance from top using `document.documentElement.scrollTop` or `document.body.scrollTop`.\nScroll by a fraction of the distance from the top. Use `window.requestAnimationFrame()` to animate the scrolling.",
        "codeBlocks": {
          "es6": "const scrollToTop = () => {\n  const c = document.documentElement.scrollTop || document.body.scrollTop;\n  if (c > 0) {\n    window.requestAnimationFrame(scrollToTop);\n    window.scrollTo(0, c - c / 8);\n  }\n};",
          "es5": "var scrollToTop = function scrollToTop() {\n  var c = document.documentElement.scrollTop || document.body.scrollTop;\n\n  if (c > 0) {\n    window.requestAnimationFrame(scrollToTop);\n    window.scrollTo(0, c - c / 8);\n  }\n};",
          "example": "scrollToTop();"
        },
        "tags": [
          "browser",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "9d097840156322f4316042fe727f6887b9cef948a92ffdbda4c92e0161f3389d"
      }
    },
    {
      "id": "sdbm",
      "type": "snippet",
      "attributes": {
        "fileName": "sdbm.md",
        "text": "Hashes the input string into a whole number.\n\nUse `String.prototype.split('')` and `Array.prototype.reduce()` to create a hash of the input string, utilizing bit shifting.",
        "codeBlocks": {
          "es6": "const sdbm = str => {\n  let arr = str.split('');\n  return arr.reduce(\n    (hashCode, currentVal) =>\n      (hashCode = currentVal.charCodeAt(0) + (hashCode << 6) + (hashCode << 16) - hashCode),\n    0\n  );\n};",
          "es5": "var sdbm = function sdbm(str) {\n  var arr = str.split('');\n  return arr.reduce(function (hashCode, currentVal) {\n    return hashCode = currentVal.charCodeAt(0) + (hashCode << 6) + (hashCode << 16) - hashCode;\n  }, 0);\n};",
          "example": "sdbm('name'); // -3521204949"
        },
        "tags": [
          "math",
          "utility",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "682cce8b08b295ff61885b2fdf8595c93eb0bc0c83cc6fbae5c6c20727a60eff"
      }
    },
    {
      "id": "serializeCookie",
      "type": "snippet",
      "attributes": {
        "fileName": "serializeCookie.md",
        "text": "Serialize a cookie name-value pair into a Set-Cookie header string.\n\nUse template literals and `encodeURIComponent()` to create the appropriate string.",
        "codeBlocks": {
          "es6": "const serializeCookie = (name, val) => `${encodeURIComponent(name)}=${encodeURIComponent(val)}`;",
          "es5": "var serializeCookie = function serializeCookie(name, val) {\n  return \"\".concat(encodeURIComponent(name), \"=\").concat(encodeURIComponent(val));\n};",
          "example": "serializeCookie('foo', 'bar'); // 'foo=bar'"
        },
        "tags": [
          "utility",
          "string",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "a69e2913ccc5c7ca2100de571087a44c14b7ca475154740bace342852357b379"
      }
    },
    {
      "id": "setStyle",
      "type": "snippet",
      "attributes": {
        "fileName": "setStyle.md",
        "text": "Sets the value of a CSS rule for the specified element.\n\nUse `element.style` to set the value of the CSS rule for the specified element to `val`.",
        "codeBlocks": {
          "es6": "const setStyle = (el, ruleName, val) => (el.style[ruleName] = val);",
          "es5": "var setStyle = function setStyle(el, ruleName, val) {\n  return el.style[ruleName] = val;\n};",
          "example": "setStyle(document.querySelector('p'), 'font-size', '20px'); // The first <p> element on the page will have a font-size of 20px"
        },
        "tags": [
          "browser",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "12eb5e821413b38e0e5d19ed1c12b7dcdf47071d1e795e9e72ffb71e693e922b"
      }
    },
    {
      "id": "shallowClone",
      "type": "snippet",
      "attributes": {
        "fileName": "shallowClone.md",
        "text": "Creates a shallow clone of an object.\n\nUse `Object.assign()` and an empty object (`{}`) to create a shallow clone of the original.",
        "codeBlocks": {
          "es6": "const shallowClone = obj => Object.assign({}, obj);",
          "es5": "var shallowClone = function shallowClone(obj) {\n  return Object.assign({}, obj);\n};",
          "example": "const a = { x: true, y: 1 };\nconst b = shallowClone(a); // a !== b"
        },
        "tags": [
          "object",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "a5a49641c0de1a0a80f192c5be195c448ab0fe0856bba4e1f246fe70af7b5431"
      }
    },
    {
      "id": "shank",
      "type": "snippet",
      "attributes": {
        "fileName": "shank.md",
        "text": "Has the same functionality as [`Array.prototype.splice()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice), but returning a new array instead of mutating the original array.\n\nUse `Array.prototype.slice()` and `Array.prototype.concat()` to get a new array with the new contents after removing existing elements and/or adding new elements.\nOmit the second argument, `index`, to start at `0`.\nOmit the third argument, `delCount`, to remove `0` elements.\nOmit the fourth argument, `elements`, in order to not add any new elements.",
        "codeBlocks": {
          "es6": "const shank = (arr, index = 0, delCount = 0, ...elements) =>\n  arr\n    .slice(0, index)\n    .concat(elements)\n    .concat(arr.slice(index + delCount));",
          "es5": "var shank = function shank(arr) {\n  var index = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n  var delCount = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;\n\n  for (var _len = arguments.length, elements = new Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {\n    elements[_key - 3] = arguments[_key];\n  }\n\n  return arr.slice(0, index).concat(elements).concat(arr.slice(index + delCount));\n};",
          "example": "const names = ['alpha', 'bravo', 'charlie'];\nconst namesAndDelta = shank(names, 1, 0, 'delta'); // [ 'alpha', 'delta', 'bravo', 'charlie' ]\nconst namesNoBravo = shank(names, 1, 1); // [ 'alpha', 'charlie' ]\nconsole.log(names); // ['alpha', 'bravo', 'charlie']"
        },
        "tags": [
          "array",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "956dedf2a511fc90c2d2acf5a8018838a7d2830b847761dafdbeb2f2df9779ed"
      }
    },
    {
      "id": "show",
      "type": "snippet",
      "attributes": {
        "fileName": "show.md",
        "text": "Shows all the elements specified.\n\nUse the spread operator (`...`) and `Array.prototype.forEach()` to clear the `display` property for each element specified.",
        "codeBlocks": {
          "es6": "const show = (...el) => [...el].forEach(e => (e.style.display = ''));",
          "es5": "var show = function show() {\n  for (var _len = arguments.length, el = new Array(_len), _key = 0; _key < _len; _key++) {\n    el[_key] = arguments[_key];\n  }\n\n  return el.concat().forEach(function (e) {\n    return e.style.display = '';\n  });\n};",
          "example": "show(...document.querySelectorAll('img')); // Shows all <img> elements on the page"
        },
        "tags": [
          "browser",
          "css",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "9116653208cf97e75bc4918bd4e22e647c88d1ed8a8b8772cc4813a5ab2ff9ed"
      }
    },
    {
      "id": "shuffle",
      "type": "snippet",
      "attributes": {
        "fileName": "shuffle.md",
        "text": "Randomizes the order of the values of an array, returning a new array.\n\nUses the [Fisher-Yates algorithm](https://github.com/30-seconds/30-seconds-of-code#shuffle) to reorder the elements of the array.",
        "codeBlocks": {
          "es6": "const shuffle = ([...arr]) => {\n  let m = arr.length;\n  while (m) {\n    const i = Math.floor(Math.random() * m--);\n    [arr[m], arr[i]] = [arr[i], arr[m]];\n  }\n  return arr;\n};",
          "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 shuffle = function shuffle(_ref) {\n  var _ref2 = _toArray(_ref),\n      arr = _ref2.slice(0);\n\n  var m = arr.length;\n\n  while (m) {\n    var i = Math.floor(Math.random() * m--);\n    var _ref3 = [arr[i], arr[m]];\n    arr[m] = _ref3[0];\n    arr[i] = _ref3[1];\n  }\n\n  return arr;\n};",
          "example": "const foo = [1, 2, 3];\nshuffle(foo); // [2, 3, 1], foo = [1, 2, 3]"
        },
        "tags": [
          "array",
          "random",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "c9dda34ebe6e4f24ce3cc310bea23011208d050ae227000a347ac4e681b21171"
      }
    },
    {
      "id": "similarity",
      "type": "snippet",
      "attributes": {
        "fileName": "similarity.md",
        "text": "Returns an array of elements that appear in both arrays.\n\nUse `Array.prototype.filter()` to remove values that are not part of `values`, determined using `Array.prototype.includes()`.",
        "codeBlocks": {
          "es6": "const similarity = (arr, values) => arr.filter(v => values.includes(v));",
          "es5": "var similarity = function similarity(arr, values) {\n  return arr.filter(function (v) {\n    return values.includes(v);\n  });\n};",
          "example": "similarity([1, 2, 3], [1, 2, 4]); // [1, 2]"
        },
        "tags": [
          "array",
          "math",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "d2f87b9fca9c7c5d90d95fb1e9865c7593a7dff9845296b690c7a7bf2a79d292"
      }
    },
    {
      "id": "size",
      "type": "snippet",
      "attributes": {
        "fileName": "size.md",
        "text": "Get size of arrays, objects or strings.\n\nGet type of `val` (`array`, `object` or `string`). \nUse `length` property for arrays.\nUse `length` or `size` value if available or number of keys for objects.\nUse `size` of a [`Blob` object](https://developer.mozilla.org/en-US/docs/Web/API/Blob) created from `val` for strings.\n\nSplit strings into array of characters with `split('')` and return its length.",
        "codeBlocks": {
          "es6": "const size = val =>\n  Array.isArray(val)\n    ? val.length\n    : val && typeof val === 'object'\n      ? val.size || val.length || Object.keys(val).length\n      : typeof val === 'string'\n        ? new Blob([val]).size\n        : 0;",
          "es5": "function _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nvar size = function size(val) {\n  return Array.isArray(val) ? val.length : val && _typeof(val) === 'object' ? val.size || val.length || Object.keys(val).length : typeof val === 'string' ? new Blob([val]).size : 0;\n};",
          "example": "size([1, 2, 3, 4, 5]); // 5\nsize('size'); // 4\nsize({ one: 1, two: 2, three: 3 }); // 3"
        },
        "tags": [
          "object",
          "array",
          "string",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "ac93ebf2905bbaeec36266cb011753e11c3895f78771e332c6694e05c62a3535"
      }
    },
    {
      "id": "sleep",
      "type": "snippet",
      "attributes": {
        "fileName": "sleep.md",
        "text": "Delays the execution of an asynchronous function.\n\nDelay executing part of an `async` function, by putting it to sleep, returning a `Promise`.",
        "codeBlocks": {
          "es6": "const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));",
          "es5": "var sleep = function sleep(ms) {\n  return new Promise(function (resolve) {\n    return setTimeout(resolve, ms);\n  });\n};",
          "example": "async function sleepyWork() {\n  console.log(\"I'm going to sleep for 1 second.\");\n  await sleep(1000);\n  console.log('I woke up after 1 second.');\n}"
        },
        "tags": [
          "function",
          "promise",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "cf97f402b25ec7ffd2b670d4b541093b567334595439167c0c7a5534962ad2a1"
      }
    },
    {
      "id": "smoothScroll",
      "type": "snippet",
      "attributes": {
        "fileName": "smoothScroll.md",
        "text": "Smoothly scrolls the element on which it's called into the visible area of the browser window.\n\nUse `.scrollIntoView` method to scroll the element. \nPass `{ behavior: 'smooth' }` to `.scrollIntoView` so it scrolls smoothly.",
        "codeBlocks": {
          "es6": "const smoothScroll = element =>\n  document.querySelector(element).scrollIntoView({\n    behavior: 'smooth'\n  });",
          "es5": "var smoothScroll = function smoothScroll(element) {\n  return document.querySelector(element).scrollIntoView({\n    behavior: 'smooth'\n  });\n};",
          "example": "smoothScroll('#fooBar'); // scrolls smoothly to the element with the id fooBar\nsmoothScroll('.fooBar'); // scrolls smoothly to the first element with a class of fooBar"
        },
        "tags": [
          "browser",
          "css",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "160e603850eac9489b210f1a3de5486944e23c0f799eb06936c6524af117fd06"
      }
    },
    {
      "id": "sortCharactersInString",
      "type": "snippet",
      "attributes": {
        "fileName": "sortCharactersInString.md",
        "text": "Alphabetically sorts the characters in a string.\n\nUse the spread operator (`...`), `Array.prototype.sort()` and  `String.localeCompare()` to sort the characters in `str`, recombine using `String.prototype.join('')`.",
        "codeBlocks": {
          "es6": "const sortCharactersInString = str => [...str].sort((a, b) => a.localeCompare(b)).join('');",
          "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 sortCharactersInString = function sortCharactersInString(str) {\n  return _toConsumableArray(str).sort(function (a, b) {\n    return a.localeCompare(b);\n  }).join('');\n};",
          "example": "sortCharactersInString('cabbage'); // 'aabbceg'"
        },
        "tags": [
          "string",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "5adc748425d58db5bc6b547a393d46b5f1b99c6ec4f6c7006ed5038d9abf09d6"
      }
    },
    {
      "id": "sortedIndex",
      "type": "snippet",
      "attributes": {
        "fileName": "sortedIndex.md",
        "text": "Returns the lowest index at which value should be inserted into array in order to maintain its sort order.\n\nCheck if the array is sorted in descending order (loosely).\nUse `Array.prototype.findIndex()` to find the appropriate index where the element should be inserted.",
        "codeBlocks": {
          "es6": "const sortedIndex = (arr, n) => {\n  const isDescending = arr[0] > arr[arr.length - 1];\n  const index = arr.findIndex(el => (isDescending ? n >= el : n <= el));\n  return index === -1 ? arr.length : index;\n};",
          "es5": "var sortedIndex = function sortedIndex(arr, n) {\n  var isDescending = arr[0] > arr[arr.length - 1];\n  var index = arr.findIndex(function (el) {\n    return isDescending ? n >= el : n <= el;\n  });\n  return index === -1 ? arr.length : index;\n};",
          "example": "sortedIndex([5, 3, 2, 1], 4); // 1\nsortedIndex([30, 50], 40); // 1"
        },
        "tags": [
          "array",
          "math",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "1d748071f0dfc6d63b004336b2859d60d9084303257f34d7ac8e0b1ba17bb531"
      }
    },
    {
      "id": "sortedIndexBy",
      "type": "snippet",
      "attributes": {
        "fileName": "sortedIndexBy.md",
        "text": "Returns the lowest index at which value should be inserted into array in order to maintain its sort order, based on a provided iterator function.\n\nCheck if the array is sorted in descending order (loosely).\nUse `Array.prototype.findIndex()` to find the appropriate index where the element should be inserted, based on the iterator function `fn`.",
        "codeBlocks": {
          "es6": "const sortedIndexBy = (arr, n, fn) => {\n  const isDescending = fn(arr[0]) > fn(arr[arr.length - 1]);\n  const val = fn(n);\n  const index = arr.findIndex(el => (isDescending ? val >= fn(el) : val <= fn(el)));\n  return index === -1 ? arr.length : index;\n};",
          "es5": "var sortedIndexBy = function sortedIndexBy(arr, n, fn) {\n  var isDescending = fn(arr[0]) > fn(arr[arr.length - 1]);\n  var val = fn(n);\n  var index = arr.findIndex(function (el) {\n    return isDescending ? val >= fn(el) : val <= fn(el);\n  });\n  return index === -1 ? arr.length : index;\n};",
          "example": "sortedIndexBy([{ x: 4 }, { x: 5 }], { x: 4 }, o => o.x); // 0"
        },
        "tags": [
          "array",
          "math",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "158bb20051dc59ccd73a94ae416179c3499b70bc26003fb569f5b8d157266485"
      }
    },
    {
      "id": "sortedLastIndex",
      "type": "snippet",
      "attributes": {
        "fileName": "sortedLastIndex.md",
        "text": "Returns the highest index at which value should be inserted into array in order to maintain its sort order.\n\nCheck if the array is sorted in descending order (loosely).\nUse `Array.prototype.reverse()` and `Array.prototype.findIndex()` to find the appropriate last index where the element should be inserted.",
        "codeBlocks": {
          "es6": "const sortedLastIndex = (arr, n) => {\n  const isDescending = arr[0] > arr[arr.length - 1];\n  const index = arr.reverse().findIndex(el => (isDescending ? n <= el : n >= el));\n  return index === -1 ? 0 : arr.length - index;\n};",
          "es5": "var sortedLastIndex = function sortedLastIndex(arr, n) {\n  var isDescending = arr[0] > arr[arr.length - 1];\n  var index = arr.reverse().findIndex(function (el) {\n    return isDescending ? n <= el : n >= el;\n  });\n  return index === -1 ? 0 : arr.length - index;\n};",
          "example": "sortedLastIndex([10, 20, 30, 30, 40], 30); // 4"
        },
        "tags": [
          "array",
          "math",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "e8cca852ff9566bae5b21e6b0cc53294d0f2c7e563236d0f4a5ef0b47fe69f2b"
      }
    },
    {
      "id": "sortedLastIndexBy",
      "type": "snippet",
      "attributes": {
        "fileName": "sortedLastIndexBy.md",
        "text": "Returns the highest index at which value should be inserted into array in order to maintain its sort order, based on a provided iterator function.\n\nCheck if the array is sorted in descending order (loosely).\nUse `Array.prototype.map()` to apply the iterator function to all elements of the array.\nUse `Array.prototype.reverse()` and `Array.prototype.findIndex()` to find the appropriate last index where the element should be inserted, based on the provided iterator function.",
        "codeBlocks": {
          "es6": "const sortedLastIndexBy = (arr, n, fn) => {\n  const isDescending = fn(arr[0]) > fn(arr[arr.length - 1]);\n  const val = fn(n);\n  const index = arr\n    .map(fn)\n    .reverse()\n    .findIndex(el => (isDescending ? val <= el : val >= el));\n  return index === -1 ? 0 : arr.length - index;\n};",
          "es5": "var sortedLastIndexBy = function sortedLastIndexBy(arr, n, fn) {\n  var isDescending = fn(arr[0]) > fn(arr[arr.length - 1]);\n  var val = fn(n);\n  var index = arr.map(fn).reverse().findIndex(function (el) {\n    return isDescending ? val <= el : val >= el;\n  });\n  return index === -1 ? 0 : arr.length - index;\n};",
          "example": "sortedLastIndexBy([{ x: 4 }, { x: 5 }], { x: 4 }, o => o.x); // 1"
        },
        "tags": [
          "array",
          "math",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "390f014b69fe582d2273b46cb769f22b73f1aec240cf0d38458680ca9cc892e4"
      }
    },
    {
      "id": "splitLines",
      "type": "snippet",
      "attributes": {
        "fileName": "splitLines.md",
        "text": "Splits a multiline string into an array of lines.\n\nUse `String.prototype.split()` and a regular expression to match line breaks and create an array.",
        "codeBlocks": {
          "es6": "const splitLines = str => str.split(/\\r?\\n/);",
          "es5": "var splitLines = function splitLines(str) {\n  return str.split(/\\r?\\n/);\n};",
          "example": "splitLines('This\\nis a\\nmultiline\\nstring.\\n'); // ['This', 'is a', 'multiline', 'string.' , '']"
        },
        "tags": [
          "string",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "b6f1f62e437bba475c89e0457c89e6bea4fb2521f421c27d4a11b9b55bf8a02d"
      }
    },
    {
      "id": "spreadOver",
      "type": "snippet",
      "attributes": {
        "fileName": "spreadOver.md",
        "text": "Takes a variadic function and returns a closure that accepts an array of arguments to map to the inputs of the function.\r\n\r\nUse closures and the spread operator (`...`) to map the array of arguments to the inputs of the function.",
        "codeBlocks": {
          "es6": "const spreadOver = fn => argsArr => fn(...argsArr);",
          "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 spreadOver = function spreadOver(fn) {\n  return function (argsArr) {\n    return fn.apply(void 0, _toConsumableArray(argsArr));\n  };\n};",
          "example": "const arrayMax = spreadOver(Math.max);\narrayMax([1, 2, 3]); // 3"
        },
        "tags": [
          "adapter",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "9a79940f01badd37efb5156b8e3d220c85601c99a6908b79fe9508d0cd4d8ff5"
      }
    },
    {
      "id": "stableSort",
      "type": "snippet",
      "attributes": {
        "fileName": "stableSort.md",
        "text": "Performs stable sorting of an array, preserving the initial indexes of items when their values are the same.\nDoes not mutate the original array, but returns a new array instead.\n\nUse `Array.prototype.map()` to pair each element of the input array with its corresponding index.\nUse `Array.prototype.sort()` and a `compare` function to sort the list, preserving their initial order if the items compared are equal.\nUse `Array.prototype.map()` to convert back to the initial array items.",
        "codeBlocks": {
          "es6": "const stableSort = (arr, compare) =>\n  arr\n    .map((item, index) => ({ item, index }))\n    .sort((a, b) => compare(a.item, b.item) || a.index - b.index)\n    .map(({ item }) => item);",
          "es5": "var stableSort = function stableSort(arr, compare) {\n  return arr.map(function (item, index) {\n    return {\n      item: item,\n      index: index\n    };\n  }).sort(function (a, b) {\n    return compare(a.item, b.item) || a.index - b.index;\n  }).map(function (_ref) {\n    var item = _ref.item;\n    return item;\n  });\n};",
          "example": "const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\nconst stable = stableSort(arr, () => 0); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
        },
        "tags": [
          "array",
          "sort",
          "advanced",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "454a110a54555ac9abdd8e6512a04e15f707ac89f5bb08b9c4175f0dd777f486"
      }
    },
    {
      "id": "standardDeviation",
      "type": "snippet",
      "attributes": {
        "fileName": "standardDeviation.md",
        "text": "Returns the standard deviation of an array of numbers.\n\nUse `Array.prototype.reduce()` to calculate the mean, variance and the sum of the variance of the values, the variance of the values, then\ndetermine the standard deviation.\nYou can omit the second argument to get the sample standard deviation or set it to `true` to get the population standard deviation.",
        "codeBlocks": {
          "es6": "const standardDeviation = (arr, usePopulation = false) => {\n  const mean = arr.reduce((acc, val) => acc + val, 0) / arr.length;\n  return Math.sqrt(\n    arr.reduce((acc, val) => acc.concat((val - mean) ** 2), []).reduce((acc, val) => acc + val, 0) /\n      (arr.length - (usePopulation ? 0 : 1))\n  );\n};",
          "es5": "var standardDeviation = function standardDeviation(arr) {\n  var usePopulation = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n  var mean = arr.reduce(function (acc, val) {\n    return acc + val;\n  }, 0) / arr.length;\n  return Math.sqrt(arr.reduce(function (acc, val) {\n    return acc.concat(Math.pow(val - mean, 2));\n  }, []).reduce(function (acc, val) {\n    return acc + val;\n  }, 0) / (arr.length - (usePopulation ? 0 : 1)));\n};",
          "example": "standardDeviation([10, 2, 38, 23, 38, 23, 21]); // 13.284434142114991 (sample)\nstandardDeviation([10, 2, 38, 23, 38, 23, 21], true); // 12.29899614287479 (population)"
        },
        "tags": [
          "math",
          "array",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "dd14903917fdf148409dd1ad440c2a1f098d3fe9a9d7742e72704d94e9d0f816"
      }
    },
    {
      "id": "stringPermutations",
      "type": "snippet",
      "attributes": {
        "fileName": "stringPermutations.md",
        "text": "⚠️ **WARNING**: This function's execution time increases exponentially with each character. Anything more than 8 to 10 characters will cause your browser to hang as it tries to solve all the different combinations.\n\nGenerates all permutations of a string (contains duplicates).\n\nUse recursion.\nFor each letter in the given string, create all the partial permutations for the rest of its letters.\nUse `Array.prototype.map()` to combine the letter with each partial permutation, then `Array.prototype.reduce()` to combine all permutations in one array.\nBase cases are for string `length` equal to `2` or `1`.",
        "codeBlocks": {
          "es6": "const stringPermutations = str => {\n  if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];\n  return str\n    .split('')\n    .reduce(\n      (acc, letter, i) =>\n        acc.concat(stringPermutations(str.slice(0, i) + str.slice(i + 1)).map(val => letter + val)),\n      []\n    );\n};",
          "es5": "var stringPermutations = function stringPermutations(str) {\n  if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];\n  return str.split('').reduce(function (acc, letter, i) {\n    return acc.concat(stringPermutations(str.slice(0, i) + str.slice(i + 1)).map(function (val) {\n      return letter + val;\n    }));\n  }, []);\n};",
          "example": "stringPermutations('abc'); // ['abc','acb','bac','bca','cab','cba']"
        },
        "tags": [
          "string",
          "recursion",
          "advanced"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "aa461317f9e5e0fac8a60d7513ecaeb9706c15ac2c7ad3fe9be397b9328b1b7e"
      }
    },
    {
      "id": "stripHTMLTags",
      "type": "snippet",
      "attributes": {
        "fileName": "stripHTMLTags.md",
        "text": "Removes HTML/XML tags from string.\n\nUse a regular expression to remove HTML/XML tags from a string.",
        "codeBlocks": {
          "es6": "const stripHTMLTags = str => str.replace(/<[^>]*>/g, '');",
          "es5": "var stripHTMLTags = function stripHTMLTags(str) {\n  return str.replace(/<[^>]*>/g, '');\n};",
          "example": "stripHTMLTags('<p><em>lorem</em> <strong>ipsum</strong></p>'); // 'lorem ipsum'"
        },
        "tags": [
          "string",
          "utility",
          "regexp",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "a46d835b66eead91516d7c00db7e80bd396a7d410ee8dddb1a79a0aad8666036"
      }
    },
    {
      "id": "sum",
      "type": "snippet",
      "attributes": {
        "fileName": "sum.md",
        "text": "Returns the sum of two or more numbers/arrays.\n\nUse `Array.prototype.reduce()` to add each value to an accumulator, initialized with a value of `0`.",
        "codeBlocks": {
          "es6": "const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0);",
          "es5": "var sum = function sum() {\n  for (var _len = arguments.length, arr = new Array(_len), _key = 0; _key < _len; _key++) {\n    arr[_key] = arguments[_key];\n  }\n\n  return arr.concat().reduce(function (acc, val) {\n    return acc + val;\n  }, 0);\n};",
          "example": "sum(...[1, 2, 3, 4]); // 10"
        },
        "tags": [
          "math",
          "array",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "c19982a92698e82e05f0f903aeac184191a6371efc35459475bbf2177e64c6e9"
      }
    },
    {
      "id": "sumBy",
      "type": "snippet",
      "attributes": {
        "fileName": "sumBy.md",
        "text": "Returns the sum 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`.",
        "codeBlocks": {
          "es6": "const sumBy = (arr, fn) =>\n  arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0);",
          "es5": "var sumBy = function sumBy(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);\n};",
          "example": "sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 20\nsumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 20"
        },
        "tags": [
          "math",
          "array",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "59c447ac5984c9c7b632adc170e74168336faddbdea47df47e533d1d87a07cd5"
      }
    },
    {
      "id": "sumPower",
      "type": "snippet",
      "attributes": {
        "fileName": "sumPower.md",
        "text": "Returns the sum of the powers of all the numbers from `start` to `end` (both inclusive).\n\nUse `Array.prototype.fill()` to create an array of all the numbers in the target range, `Array.prototype.map()` and the exponent operator (`**`) to raise them to `power` and `Array.prototype.reduce()` to add them together.\nOmit the second argument, `power`, to use a default power of `2`.\nOmit the third argument, `start`, to use a default starting value of `1`.",
        "codeBlocks": {
          "es6": "const sumPower = (end, power = 2, start = 1) =>\n  Array(end + 1 - start)\n    .fill(0)\n    .map((x, i) => (i + start) ** power)\n    .reduce((a, b) => a + b, 0);",
          "es5": "var sumPower = function sumPower(end) {\n  var power = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;\n  var start = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n  return Array(end + 1 - start).fill(0).map(function (x, i) {\n    return Math.pow(i + start, power);\n  }).reduce(function (a, b) {\n    return a + b;\n  }, 0);\n};",
          "example": "sumPower(10); // 385\nsumPower(10, 3); // 3025\nsumPower(10, 3, 5); // 2925"
        },
        "tags": [
          "math",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "bc4cdf47b99e2ace6163d4fde6adea551f06362bae92cac8c7fda67712912391"
      }
    },
    {
      "id": "symmetricDifference",
      "type": "snippet",
      "attributes": {
        "fileName": "symmetricDifference.md",
        "text": "Returns the symmetric difference between two arrays, without filtering out duplicate values.\n\nCreate a `Set` from each array, then use `Array.prototype.filter()` on each of them to only keep values not contained in the other.",
        "codeBlocks": {
          "es6": "const symmetricDifference = (a, b) => {\n  const sA = new Set(a),\n    sB = new Set(b);\n  return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))];\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 symmetricDifference = function symmetricDifference(a, b) {\n  var sA = new Set(a),\n      sB = new Set(b);\n  return _toConsumableArray(a.filter(function (x) {\n    return !sB.has(x);\n  })).concat(_toConsumableArray(b.filter(function (x) {\n    return !sA.has(x);\n  })));\n};",
          "example": "symmetricDifference([1, 2, 3], [1, 2, 4]); // [3, 4]\nsymmetricDifference([1, 2, 2], [1, 3, 1]); // [2, 2, 3]"
        },
        "tags": [
          "array",
          "math",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "520bb2600d7d31d2dee3aa377986e8cc5b368fc9bb257c73255c9a295804f6a6"
      }
    },
    {
      "id": "symmetricDifferenceBy",
      "type": "snippet",
      "attributes": {
        "fileName": "symmetricDifferenceBy.md",
        "text": "Returns the symmetric difference between two arrays, after applying the provided function to each array element of both.\n\nCreate a `Set` by applying `fn` to each array's elements, then use `Array.prototype.filter()` on each of them to only keep values not contained in the other.",
        "codeBlocks": {
          "es6": "const symmetricDifferenceBy = (a, b, fn) => {\n  const sA = new Set(a.map(v => fn(v))),\n    sB = new Set(b.map(v => fn(v)));\n  return [...a.filter(x => !sB.has(fn(x))), ...b.filter(x => !sA.has(fn(x)))];\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 symmetricDifferenceBy = function symmetricDifferenceBy(a, b, fn) {\n  var sA = new Set(a.map(function (v) {\n    return fn(v);\n  })),\n      sB = new Set(b.map(function (v) {\n    return fn(v);\n  }));\n  return _toConsumableArray(a.filter(function (x) {\n    return !sB.has(fn(x));\n  })).concat(_toConsumableArray(b.filter(function (x) {\n    return !sA.has(fn(x));\n  })));\n};",
          "example": "symmetricDifferenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [ 1.2, 3.4 ]"
        },
        "tags": [
          "array",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "8af295527bdf0a150d3e2f20eb7d07acca0d68a808f0bb622178576baa33128c"
      }
    },
    {
      "id": "symmetricDifferenceWith",
      "type": "snippet",
      "attributes": {
        "fileName": "symmetricDifferenceWith.md",
        "text": "Returns the symmetric difference between two arrays, using a provided function as a comparator.\n\nUse `Array.prototype.filter()` and `Array.prototype.findIndex()` to find the appropriate values.",
        "codeBlocks": {
          "es6": "const symmetricDifferenceWith = (arr, val, comp) => [\n  ...arr.filter(a => val.findIndex(b => comp(a, b)) === -1),\n  ...val.filter(a => arr.findIndex(b => comp(a, b)) === -1)\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 symmetricDifferenceWith = function symmetricDifferenceWith(arr, val, comp) {\n  return _toConsumableArray(arr.filter(function (a) {\n    return val.findIndex(function (b) {\n      return comp(a, b);\n    }) === -1;\n  })).concat(_toConsumableArray(val.filter(function (a) {\n    return arr.findIndex(function (b) {\n      return comp(a, b);\n    }) === -1;\n  })));\n};",
          "example": "symmetricDifferenceWith(\n  [1, 1.2, 1.5, 3, 0],\n  [1.9, 3, 0, 3.9],\n  (a, b) => Math.round(a) === Math.round(b)\n); // [1, 1.2, 3.9]"
        },
        "tags": [
          "array",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "338cc5e1c426261c149a8431ac04040389550f11cf5afa77ffae32ad13be9256"
      }
    },
    {
      "id": "tail",
      "type": "snippet",
      "attributes": {
        "fileName": "tail.md",
        "text": "Returns all elements in an array except for the first one.\n\nReturn `Array.prototype.slice(1)` if the array's `length` is more than `1`, otherwise, return the whole array.",
        "codeBlocks": {
          "es6": "const tail = arr => (arr.length > 1 ? arr.slice(1) : arr);",
          "es5": "var tail = function tail(arr) {\n  return arr.length > 1 ? arr.slice(1) : arr;\n};",
          "example": "tail([1, 2, 3]); // [2,3]\ntail([1]); // [1]"
        },
        "tags": [
          "array",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "df81add854aa09b654d62fa7eab314aa8d272da24ed59e876fa75a4477db8737"
      }
    },
    {
      "id": "take",
      "type": "snippet",
      "attributes": {
        "fileName": "take.md",
        "text": "Returns an array with n elements removed from the beginning.\n\nUse `Array.prototype.slice()` to create a slice of the array with `n` elements taken from the beginning.",
        "codeBlocks": {
          "es6": "const take = (arr, n = 1) => arr.slice(0, n);",
          "es5": "var take = function take(arr) {\n  var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;\n  return arr.slice(0, n);\n};",
          "example": "take([1, 2, 3], 5); // [1, 2, 3]\ntake([1, 2, 3], 0); // []"
        },
        "tags": [
          "array",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "8e1123ba492a1103e2ac793c7febb0851905301dd190c453a253e23b05a27a6c"
      }
    },
    {
      "id": "takeRight",
      "type": "snippet",
      "attributes": {
        "fileName": "takeRight.md",
        "text": "Returns an array with n elements removed from the end.\n\nUse `Array.prototype.slice()` to create a slice of the array with `n` elements taken from the end.",
        "codeBlocks": {
          "es6": "const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length);",
          "es5": "var takeRight = function takeRight(arr) {\n  var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;\n  return arr.slice(arr.length - n, arr.length);\n};",
          "example": "takeRight([1, 2, 3], 2); // [ 2, 3 ]\ntakeRight([1, 2, 3]); // [3]"
        },
        "tags": [
          "array",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "30d3b8ac6dd36237d4b3221e3b9a8d6c1a097d2adefa52d694ee2d8733472159"
      }
    },
    {
      "id": "takeRightWhile",
      "type": "snippet",
      "attributes": {
        "fileName": "takeRightWhile.md",
        "text": "Removes elements from the end of an array until the passed function returns `true`. Returns the removed elements.\n\nLoop through the array, using a `Array.prototype.reduceRight()` and accumulating elements while the function returns falsy value.",
        "codeBlocks": {
          "es6": "const takeRightWhile = (arr, func) =>\n  arr.reduceRight((acc, el) => (func(el) ? acc : [el, ...acc]), []);",
          "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 takeRightWhile = function takeRightWhile(arr, func) {\n  return arr.reduceRight(function (acc, el) {\n    return func(el) ? acc : [el].concat(_toConsumableArray(acc));\n  }, []);\n};",
          "example": "takeRightWhile([1, 2, 3, 4], n => n < 3); // [3, 4]"
        },
        "tags": [
          "array",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "e229ed3f9dfffee8681ff978f7b1417b1a07b3820af0350f0c8b0332147a8525"
      }
    },
    {
      "id": "takeWhile",
      "type": "snippet",
      "attributes": {
        "fileName": "takeWhile.md",
        "text": "Removes elements in an array until the passed function returns `true`. Returns the removed elements.\n\nLoop through the array, using a `for...of` loop over `Array.prototype.entries()` until the returned value from the function is `true`.\nReturn the removed elements, using `Array.prototype.slice()`.",
        "codeBlocks": {
          "es6": "const takeWhile = (arr, func) => {\n  for (const [i, val] of arr.entries()) if (func(val)) return arr.slice(0, i);\n  return arr;\n};",
          "es5": "function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }\n\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance\"); }\n\nfunction _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i[\"return\"] != null) _i[\"return\"](); } finally { if (_d) throw _e; } } return _arr; }\n\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n\nvar takeWhile = function takeWhile(arr, func) {\n  var _iteratorNormalCompletion = true;\n  var _didIteratorError = false;\n  var _iteratorError = undefined;\n\n  try {\n    for (var _iterator = arr.entries()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n      var _step$value = _slicedToArray(_step.value, 2),\n          i = _step$value[0],\n          val = _step$value[1];\n\n      if (func(val)) return arr.slice(0, i);\n    }\n  } catch (err) {\n    _didIteratorError = true;\n    _iteratorError = err;\n  } finally {\n    try {\n      if (!_iteratorNormalCompletion && _iterator.return != null) {\n        _iterator.return();\n      }\n    } finally {\n      if (_didIteratorError) {\n        throw _iteratorError;\n      }\n    }\n  }\n\n  return arr;\n};",
          "example": "takeWhile([1, 2, 3, 4], n => n >= 3); // [1, 2]"
        },
        "tags": [
          "array",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "ffaf357a96c9dca6e963ca5ec4c809b0012b92a551e0869f35c87fce5eabb95a"
      }
    },
    {
      "id": "throttle",
      "type": "snippet",
      "attributes": {
        "fileName": "throttle.md",
        "text": "Creates a throttled function that only invokes the provided function at most once per every `wait` milliseconds\n\nUse `setTimeout()` and `clearTimeout()` to throttle the given method, `fn`.\nUse `Function.prototype.apply()` to apply the `this` context to the function and provide the necessary `arguments`.\nUse `Date.now()` to keep track of the last time the throttled function was invoked.\nOmit the second argument, `wait`, to set the timeout at a default of 0 ms.",
        "codeBlocks": {
          "es6": "const throttle = (fn, wait) => {\n  let inThrottle, lastFn, lastTime;\n  return function() {\n    const context = this,\n      args = arguments;\n    if (!inThrottle) {\n      fn.apply(context, args);\n      lastTime = Date.now();\n      inThrottle = true;\n    } else {\n      clearTimeout(lastFn);\n      lastFn = setTimeout(function() {\n        if (Date.now() - lastTime >= wait) {\n          fn.apply(context, args);\n          lastTime = Date.now();\n        }\n      }, Math.max(wait - (Date.now() - lastTime), 0));\n    }\n  };\n};",
          "es5": "var throttle = function throttle(fn, wait) {\n  var inThrottle, lastFn, lastTime;\n  return function () {\n    var context = this,\n        args = arguments;\n\n    if (!inThrottle) {\n      fn.apply(context, args);\n      lastTime = Date.now();\n      inThrottle = true;\n    } else {\n      clearTimeout(lastFn);\n      lastFn = setTimeout(function () {\n        if (Date.now() - lastTime >= wait) {\n          fn.apply(context, args);\n          lastTime = Date.now();\n        }\n      }, Math.max(wait - (Date.now() - lastTime), 0));\n    }\n  };\n};",
          "example": "window.addEventListener(\n  'resize',\n  throttle(function(evt) {\n    console.log(window.innerWidth);\n    console.log(window.innerHeight);\n  }, 250)\n); // Will log the window dimensions at most every 250ms"
        },
        "tags": [
          "function",
          "advanced"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "8eece384966f81ded39d67601ec6d6e320e2ffb750cc5f026e4158c439bf2815"
      }
    },
    {
      "id": "times",
      "type": "snippet",
      "attributes": {
        "fileName": "times.md",
        "text": "Iterates over a callback `n` times\n\nUse `Function.call()` to call `fn` `n` times or until it returns `false`.\nOmit the last argument, `context`, to use an `undefined` object (or the global object in non-strict mode).",
        "codeBlocks": {
          "es6": "const times = (n, fn, context = undefined) => {\n  let i = 0;\n  while (fn.call(context, i) !== false && ++i < n) {}\n};",
          "es5": "var times = function times(n, fn) {\n  var context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;\n  var i = 0;\n\n  while (fn.call(context, i) !== false && ++i < n) {}\n};",
          "example": "var output = '';\ntimes(5, i => (output += i));\nconsole.log(output); // 01234"
        },
        "tags": [
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "90ab922b56f62b3eafff4a31b2a1f1345d2126e712f02360cb8a6e8b31adee96"
      }
    },
    {
      "id": "timeTaken",
      "type": "snippet",
      "attributes": {
        "fileName": "timeTaken.md",
        "text": "Measures the time taken by a function to execute.\n\nUse `console.time()` and `console.timeEnd()` to measure the difference between the start and end times to determine how long the callback took to execute.",
        "codeBlocks": {
          "es6": "const timeTaken = callback => {\n  console.time('timeTaken');\n  const r = callback();\n  console.timeEnd('timeTaken');\n  return r;\n};",
          "es5": "var timeTaken = function timeTaken(callback) {\n  console.time('timeTaken');\n  var r = callback();\n  console.timeEnd('timeTaken');\n  return r;\n};",
          "example": "timeTaken(() => Math.pow(2, 10)); // 1024, (logged): timeTaken: 0.02099609375ms"
        },
        "tags": [
          "utility",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "48d1e866b152eacd9fa16d8bf5c3136d01072522a58ad005a13d9b1792a3c37f"
      }
    },
    {
      "id": "toCamelCase",
      "type": "snippet",
      "attributes": {
        "fileName": "toCamelCase.md",
        "text": "Converts a string to camelcase.\n\nBreak the string into words and combine them capitalizing the first letter of each word, using a regexp.",
        "codeBlocks": {
          "es6": "const toCamelCase = str => {\n  let s =\n    str &&\n    str\n      .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)\n      .map(x => x.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase())\n      .join('');\n  return s.slice(0, 1).toLowerCase() + s.slice(1);\n};",
          "es5": "var toCamelCase = function toCamelCase(str) {\n  var s = str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g).map(function (x) {\n    return x.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase();\n  }).join('');\n  return s.slice(0, 1).toLowerCase() + s.slice(1);\n};",
          "example": "toCamelCase('some_database_field_name'); // 'someDatabaseFieldName'\ntoCamelCase('Some label that needs to be camelized'); // 'someLabelThatNeedsToBeCamelized'\ntoCamelCase('some-javascript-property'); // 'someJavascriptProperty'\ntoCamelCase('some-mixed_string with spaces_underscores-and-hyphens'); // 'someMixedStringWithSpacesUnderscoresAndHyphens'"
        },
        "tags": [
          "string",
          "regexp",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "870a6ab0b2c7a69e26af06ce5f1cb2bd1706ae678139d2c2c3f59ce277c0cea3"
      }
    },
    {
      "id": "toCurrency",
      "type": "snippet",
      "attributes": {
        "fileName": "toCurrency.md",
        "text": "Take a number and return specified currency formatting.\n\nUse `Intl.NumberFormat` to enable country / currency sensitive formatting.",
        "codeBlocks": {
          "es6": "const toCurrency = (n, curr, LanguageFormat = undefined) =>\n  Intl.NumberFormat(LanguageFormat, { style: 'currency', currency: curr }).format(n);",
          "es5": "var toCurrency = function toCurrency(n, curr) {\n  var LanguageFormat = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;\n  return Intl.NumberFormat(LanguageFormat, {\n    style: 'currency',\n    currency: curr\n  }).format(n);\n};",
          "example": "toCurrency(123456.789, 'EUR'); // €123,456.79  | currency: Euro | currencyLangFormat: Local\ntoCurrency(123456.789, 'USD', 'en-us'); // $123,456.79  | currency: US Dollar | currencyLangFormat: English (United States)\ntoCurrency(123456.789, 'USD', 'fa'); // ۱۲۳٬۴۵۶٫۷۹ ؜$ | currency: US Dollar | currencyLangFormat: Farsi\ntoCurrency(322342436423.2435, 'JPY'); // ¥322,342,436,423 | currency: Japanese Yen | currencyLangFormat: Local\ntoCurrency(322342436423.2435, 'JPY', 'fi'); // 322 342 436 423 ¥ | currency: Japanese Yen | currencyLangFormat: Finnish"
        },
        "tags": [
          "utility",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "85a601168285577950b9fd0f28fa0d0283261dda12a2cb0e1a0e1cc78a6e81ae"
      }
    },
    {
      "id": "toDecimalMark",
      "type": "snippet",
      "attributes": {
        "fileName": "toDecimalMark.md",
        "text": "Use `toLocaleString()` to convert a float-point arithmetic to the [Decimal mark](https://en.wikipedia.org/wiki/Decimal_mark) form. It makes a comma separated string from a number.",
        "codeBlocks": {
          "es6": "const toDecimalMark = num => num.toLocaleString('en-US');",
          "es5": "var toDecimalMark = function toDecimalMark(num) {\n  return num.toLocaleString('en-US');\n};",
          "example": "toDecimalMark(12305030388.9087); // \"12,305,030,388.909\""
        },
        "tags": [
          "utility",
          "math",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "37225304d6109741f6ccb03fc845b2dbe84e0e2142861dfc73f5d3b5d770bde7"
      }
    },
    {
      "id": "toggleClass",
      "type": "snippet",
      "attributes": {
        "fileName": "toggleClass.md",
        "text": "Toggle a class for an element.\n\nUse `element.classList.toggle()` to toggle the specified class for the element.",
        "codeBlocks": {
          "es6": "const toggleClass = (el, className) => el.classList.toggle(className);",
          "es5": "var toggleClass = function toggleClass(el, className) {\n  return el.classList.toggle(className);\n};",
          "example": "toggleClass(document.querySelector('p.special'), 'special'); // The paragraph will not have the 'special' class anymore"
        },
        "tags": [
          "browser",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "c1fec7508780ad0ceacbf58c049668201e9f88eee043234394e11666530cfb21"
      }
    },
    {
      "id": "toHash",
      "type": "snippet",
      "attributes": {
        "fileName": "toHash.md",
        "text": "Reduces a given Array-like into a value hash (keyed data store).\n\nGiven an Iterable or Array-like structure, call `Array.prototype.reduce.call()` on the provided object to step over it and return an Object, keyed by the reference value.",
        "codeBlocks": {
          "es6": "const toHash = (object, key) =>\n  Array.prototype.reduce.call(\n    object,\n    (acc, data, index) => ((acc[!key ? index : data[key]] = data), acc),\n    {}\n  );",
          "es5": "var toHash = function toHash(object, key) {\n  return Array.prototype.reduce.call(object, function (acc, data, index) {\n    return acc[!key ? index : data[key]] = data, acc;\n  }, {});\n};",
          "example": "toHash([4, 3, 2, 1]); // { 0: 4, 1: 3, 2: 2, 3: 1 }\ntoHash([{ a: 'label' }], 'a'); // { label: { a: 'label' } }\n// A more in depth example:\nlet users = [{ id: 1, first: 'Jon' }, { id: 2, first: 'Joe' }, { id: 3, first: 'Moe' }];\nlet managers = [{ manager: 1, employees: [2, 3] }];\n// We use function here because we want a bindable reference, but a closure referencing the hash would work, too.\nmanagers.forEach(\n  manager =>\n    (manager.employees = manager.employees.map(function(id) {\n      return this[id];\n    }, toHash(users, 'id')))\n);\nmanagers; // [ { manager:1, employees: [ { id: 2, first: \"Joe\" }, { id: 3, first: \"Moe\" } ] } ]"
        },
        "tags": [
          "array",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "2fd449a2a993bdbc2b93d185ef09aea72af7845152de46d6050db82efe912130"
      }
    },
    {
      "id": "toKebabCase",
      "type": "snippet",
      "attributes": {
        "fileName": "toKebabCase.md",
        "text": "Converts a string to kebab case.\n\nBreak the string into words and combine them adding `-` as a separator, using a regexp.",
        "codeBlocks": {
          "es6": "const toKebabCase = str =>\n  str &&\n  str\n    .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)\n    .map(x => x.toLowerCase())\n    .join('-');",
          "es5": "var toKebabCase = function toKebabCase(str) {\n  return str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g).map(function (x) {\n    return x.toLowerCase();\n  }).join('-');\n};",
          "example": "toKebabCase('camelCase'); // 'camel-case'\ntoKebabCase('some text'); // 'some-text'\ntoKebabCase('some-mixed_string With spaces_underscores-and-hyphens'); // 'some-mixed-string-with-spaces-underscores-and-hyphens'\ntoKebabCase('AllThe-small Things'); // \"all-the-small-things\"\ntoKebabCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML'); // \"i-am-listening-to-fm-while-loading-different-url-on-my-browser-and-also-editing-xml-and-html\""
        },
        "tags": [
          "string",
          "regexp",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "40bb52f6eb89e1b796af964316c93bee286e44952d8d2e410ac7f8124b6cd8ac"
      }
    },
    {
      "id": "tomorrow",
      "type": "snippet",
      "attributes": {
        "fileName": "tomorrow.md",
        "text": "Results in a string representation of tomorrow's date.\n\nUse `new Date()` to get today's date, adding one day using `Date.getDate()` and `Date.setDate()`, and converting the Date object to a string.",
        "codeBlocks": {
          "es6": "const tomorrow = (long = false) => {\n  let t = new Date();\n  t.setDate(t.getDate() + 1);\n  const ret = `${t.getFullYear()}-${String(t.getMonth() + 1).padStart(2, '0')}-${String(\n    t.getDate()\n  ).padStart(2, '0')}`;\n  return !long ? ret : `${ret}T00:00:00`;\n};",
          "es5": "var tomorrow = function tomorrow() {\n  var long = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n  var t = new Date();\n  t.setDate(t.getDate() + 1);\n  var ret = \"\".concat(t.getFullYear(), \"-\").concat(String(t.getMonth() + 1).padStart(2, '0'), \"-\").concat(String(t.getDate()).padStart(2, '0'));\n  return !long ? ret : \"\".concat(ret, \"T00:00:00\");\n};",
          "example": "tomorrow(); // 2017-12-27 (if current date is 2017-12-26)\ntomorrow(true); // 2017-12-27T00:00:00 (if current date is 2017-12-26)"
        },
        "tags": [
          "date",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "4794ae637e65b9c1ac43f6c964555a98cda83e1410684e11ed34753c81db35fb"
      }
    },
    {
      "id": "toOrdinalSuffix",
      "type": "snippet",
      "attributes": {
        "fileName": "toOrdinalSuffix.md",
        "text": "Adds an ordinal suffix to a number.\n\nUse the modulo operator (`%`) to find values of single and tens digits.\nFind which ordinal pattern digits match.\nIf digit is found in teens pattern, use teens ordinal.",
        "codeBlocks": {
          "es6": "const toOrdinalSuffix = num => {\n  const int = parseInt(num),\n    digits = [int % 10, int % 100],\n    ordinals = ['st', 'nd', 'rd', 'th'],\n    oPattern = [1, 2, 3, 4],\n    tPattern = [11, 12, 13, 14, 15, 16, 17, 18, 19];\n  return oPattern.includes(digits[0]) && !tPattern.includes(digits[1])\n    ? int + ordinals[digits[0] - 1]\n    : int + ordinals[3];\n};",
          "es5": "var toOrdinalSuffix = function toOrdinalSuffix(num) {\n  var int = parseInt(num),\n      digits = [int % 10, int % 100],\n      ordinals = ['st', 'nd', 'rd', 'th'],\n      oPattern = [1, 2, 3, 4],\n      tPattern = [11, 12, 13, 14, 15, 16, 17, 18, 19];\n  return oPattern.includes(digits[0]) && !tPattern.includes(digits[1]) ? int + ordinals[digits[0] - 1] : int + ordinals[3];\n};",
          "example": "toOrdinalSuffix('123'); // \"123rd\""
        },
        "tags": [
          "utility",
          "math",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "9e162528df1b8dd803a71a770f3c5e1555ca5995005e26e416f5652024b3fd1e"
      }
    },
    {
      "id": "toSafeInteger",
      "type": "snippet",
      "attributes": {
        "fileName": "toSafeInteger.md",
        "text": "Converts a value to a safe integer.\n\nUse `Math.max()` and `Math.min()` to find the closest safe value.\nUse `Math.round()` to convert to an integer.",
        "codeBlocks": {
          "es6": "const toSafeInteger = num =>\n  Math.round(Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER));",
          "es5": "var toSafeInteger = function toSafeInteger(num) {\n  return Math.round(Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER));\n};",
          "example": "toSafeInteger('3.2'); // 3\ntoSafeInteger(Infinity); // 9007199254740991"
        },
        "tags": [
          "math",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "9f1ec1d236c7cd6787078f8eb21ac9076a2049b9e63b99bb67017be40a0f833b"
      }
    },
    {
      "id": "toSnakeCase",
      "type": "snippet",
      "attributes": {
        "fileName": "toSnakeCase.md",
        "text": "Converts a string to snake case.\n\nBreak the string into words and combine them adding `_` as a separator, using a regexp.",
        "codeBlocks": {
          "es6": "const toSnakeCase = str =>\n  str &&\n  str\n    .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)\n    .map(x => x.toLowerCase())\n    .join('_');",
          "es5": "var toSnakeCase = function toSnakeCase(str) {\n  return str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g).map(function (x) {\n    return x.toLowerCase();\n  }).join('_');\n};",
          "example": "toSnakeCase('camelCase'); // 'camel_case'\ntoSnakeCase('some text'); // 'some_text'\ntoSnakeCase('some-mixed_string With spaces_underscores-and-hyphens'); // 'some_mixed_string_with_spaces_underscores_and_hyphens'\ntoSnakeCase('AllThe-small Things'); // \"all_the_smal_things\"\ntoSnakeCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML'); // \"i_am_listening_to_fm_while_loading_different_url_on_my_browser_and_also_editing_some_xml_and_html\""
        },
        "tags": [
          "string",
          "regexp",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "07be50b2d41b64458085b8f48a361023061fff8cc6db5813ce56cb3e5d22ccfa"
      }
    },
    {
      "id": "toTitleCase",
      "type": "snippet",
      "attributes": {
        "fileName": "toTitleCase.md",
        "text": "Converts a string to title case.\n\nBreak the string into words, using a regexp, and combine them capitalizing the first letter of each word and adding a whitespace between them.",
        "codeBlocks": {
          "es6": "const toTitleCase = str =>\n  str\n    .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)\n    .map(x => x.charAt(0).toUpperCase() + x.slice(1))\n    .join(' ');",
          "es5": "var toTitleCase = function toTitleCase(str) {\n  return str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g).map(function (x) {\n    return x.charAt(0).toUpperCase() + x.slice(1);\n  }).join(' ');\n};",
          "example": "toTitleCase('some_database_field_name'); // 'Some Database Field Name'\ntoTitleCase('Some label that needs to be title-cased'); // 'Some Label That Needs To Be Title Cased'\ntoTitleCase('some-package-name'); // 'Some Package Name'\ntoTitleCase('some-mixed_string with spaces_underscores-and-hyphens'); // 'Some Mixed String With Spaces Underscores And Hyphens'"
        },
        "tags": [
          "string",
          "regepx",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "e08f543efd322b776956ba59d67a62da19998e979e953f662059d57fb440c465"
      }
    },
    {
      "id": "transform",
      "type": "snippet",
      "attributes": {
        "fileName": "transform.md",
        "text": "Applies a function against an accumulator and each key in the object (from left to right).\n\nUse `Object.keys(obj)` to iterate over each key in the object, `Array.prototype.reduce()` to call the apply the specified function against the given accumulator.",
        "codeBlocks": {
          "es6": "const transform = (obj, fn, acc) => Object.keys(obj).reduce((a, k) => fn(a, obj[k], k, obj), acc);",
          "es5": "var transform = function transform(obj, fn, acc) {\n  return Object.keys(obj).reduce(function (a, k) {\n    return fn(a, obj[k], k, obj);\n  }, acc);\n};",
          "example": "transform(\n  { a: 1, b: 2, c: 1 },\n  (r, v, k) => {\n    (r[v] || (r[v] = [])).push(k);\n    return r;\n  },\n  {}\n); // { '1': ['a', 'c'], '2': ['b'] }"
        },
        "tags": [
          "object",
          "array",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "57e917442bd3ef061d052ed219cfc4041abb5ab83c3caeda491c0fc7a9341fa0"
      }
    },
    {
      "id": "triggerEvent",
      "type": "snippet",
      "attributes": {
        "fileName": "triggerEvent.md",
        "text": "Triggers a specific event on a given element, optionally passing custom data.\n\nUse `new CustomEvent()` to create an event from the specified `eventType` and details.\nUse `el.dispatchEvent()` to trigger the newly created event on the given element.\nOmit the third argument, `detail`, if you do not want to pass custom data to the triggered event.",
        "codeBlocks": {
          "es6": "const triggerEvent = (el, eventType, detail) =>\n  el.dispatchEvent(new CustomEvent(eventType, { detail }));",
          "es5": "var triggerEvent = function triggerEvent(el, eventType, detail) {\n  return el.dispatchEvent(new CustomEvent(eventType, {\n    detail: detail\n  }));\n};",
          "example": "triggerEvent(document.getElementById('myId'), 'click');\ntriggerEvent(document.getElementById('myId'), 'click', { username: 'bob' });"
        },
        "tags": [
          "browser",
          "event",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "f7aec80ce75a7058fe94c36ea21c4db37aa46bcf114817b2d9dc4a71c16b62ba"
      }
    },
    {
      "id": "truncateString",
      "type": "snippet",
      "attributes": {
        "fileName": "truncateString.md",
        "text": "Truncates a string up to a specified length.\n\nDetermine if the string's `length` is greater than `num`.\nReturn the string truncated to the desired length, with `'...'` appended to the end or the original string.",
        "codeBlocks": {
          "es6": "const truncateString = (str, num) =>\n  str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str;",
          "es5": "var truncateString = function truncateString(str, num) {\n  return str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str;\n};",
          "example": "truncateString('boomerang', 7); // 'boom...'"
        },
        "tags": [
          "string",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "656e754cd1a8ef1a738557d1453b8f6c65e5f0f67e829179c88f3d9b6d3c4ee7"
      }
    },
    {
      "id": "truthCheckCollection",
      "type": "snippet",
      "attributes": {
        "fileName": "truthCheckCollection.md",
        "text": "Checks if the predicate (second argument) is truthy on all elements of a collection (first argument).\n\nUse `Array.prototype.every()` to check if each passed object has the specified property and if it returns a truthy value.",
        "codeBlocks": {
          "es6": "const truthCheckCollection = (collection, pre) => collection.every(obj => obj[pre]);",
          "es5": "var truthCheckCollection = function truthCheckCollection(collection, pre) {\n  return collection.every(function (obj) {\n    return obj[pre];\n  });\n};",
          "example": "truthCheckCollection([{ user: 'Tinky-Winky', sex: 'male' }, { user: 'Dipsy', sex: 'male' }], 'sex'); // true"
        },
        "tags": [
          "object",
          "logic",
          "array",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "3b948351bdd9e2246bb545e3533e85337e9104854f34da559237b62e59084cca"
      }
    },
    {
      "id": "unary",
      "type": "snippet",
      "attributes": {
        "fileName": "unary.md",
        "text": "Creates a function that accepts up to one argument, ignoring any additional arguments.\n\nCall the provided function, `fn`, with just the first argument given.",
        "codeBlocks": {
          "es6": "const unary = fn => val => fn(val);",
          "es5": "var unary = function unary(fn) {\n  return function (val) {\n    return fn(val);\n  };\n};",
          "example": "['6', '8', '10'].map(unary(parseInt)); // [6, 8, 10]"
        },
        "tags": [
          "adapter",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "522df418a2b451115c7514afc7480a2f5a0f813dd320faf6e577c9eff71d379b"
      }
    },
    {
      "id": "uncurry",
      "type": "snippet",
      "attributes": {
        "fileName": "uncurry.md",
        "text": "Uncurries a function up to depth `n`.\n\nReturn a variadic function.\nUse `Array.prototype.reduce()` on the provided arguments to call each subsequent curry level of the function.\nIf the `length` of the provided arguments is less than `n` throw an error.\nOtherwise, call `fn` with the proper amount of arguments, using `Array.prototype.slice(0, n)`.\nOmit the second argument, `n`, to uncurry up to depth `1`.",
        "codeBlocks": {
          "es6": "const uncurry = (fn, n = 1) => (...args) => {\n  const next = acc => args => args.reduce((x, y) => x(y), acc);\n  if (n > args.length) throw new RangeError('Arguments too few!');\n  return next(fn)(args.slice(0, n));\n};",
          "es5": "var uncurry = function uncurry(fn) {\n  var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;\n  return function () {\n    var next = function next(acc) {\n      return function (args) {\n        return args.reduce(function (x, y) {\n          return x(y);\n        }, acc);\n      };\n    };\n\n    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n      args[_key] = arguments[_key];\n    }\n\n    if (n > args.length) throw new RangeError('Arguments too few!');\n    return next(fn)(args.slice(0, n));\n  };\n};",
          "example": "const add = x => y => z => x + y + z;\nconst uncurriedAdd = uncurry(add, 3);\nuncurriedAdd(1, 2, 3); // 6"
        },
        "tags": [
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "c2b5d3567834f4bc3149676e7130e93e8349a9a0c76078a0f31ab9de5cc739ca"
      }
    },
    {
      "id": "unescapeHTML",
      "type": "snippet",
      "attributes": {
        "fileName": "unescapeHTML.md",
        "text": "Unescapes escaped HTML characters.\n\nUse `String.prototype.replace()` with a regex that matches the characters that need to be unescaped, using a callback function to replace each escaped character instance with its associated unescaped character using a dictionary (object).",
        "codeBlocks": {
          "es6": "const unescapeHTML = str =>\n  str.replace(\n    /&amp;|&lt;|&gt;|&#39;|&quot;/g,\n    tag =>\n      ({\n        '&amp;': '&',\n        '&lt;': '<',\n        '&gt;': '>',\n        '&#39;': \"'\",\n        '&quot;': '\"'\n      }[tag] || tag)\n  );",
          "es5": "var unescapeHTML = function unescapeHTML(str) {\n  return str.replace(/&amp;|&lt;|&gt;|&#39;|&quot;/g, function (tag) {\n    return {\n      '&amp;': '&',\n      '&lt;': '<',\n      '&gt;': '>',\n      '&#39;': \"'\",\n      '&quot;': '\"'\n    }[tag] || tag;\n  });\n};",
          "example": "unescapeHTML('&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;'); // '<a href=\"#\">Me & you</a>'"
        },
        "tags": [
          "string",
          "browser",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "7caae7814b3cee1c6a312b563443a389bbc67843a78ca14221cdbeceffbdd4d2"
      }
    },
    {
      "id": "unflattenObject",
      "type": "snippet",
      "attributes": {
        "fileName": "unflattenObject.md",
        "text": "Unflatten an object with the paths for keys.\n\nUse `Object.keys(obj)` combined with `Array.prototype.reduce()` to convert flattened path node to a leaf node.\nIf the value of a key contains a dot delimiter (`.`), use `Array.prototype.split('.')`, string transformations and `JSON.parse()` to create an object, then `Object.assign()` to create the leaf node.\nOtherwise, add the appropriate key-value pair to the accumulator object.",
        "codeBlocks": {
          "es6": "const unflattenObject = obj =>\n  Object.keys(obj).reduce((acc, k) => {\n    if (k.indexOf('.') !== -1) {\n      const keys = k.split('.');\n      Object.assign(\n        acc,\n        JSON.parse(\n          '{' +\n            keys.map((v, i) => (i !== keys.length - 1 ? `\"${v}\":{` : `\"${v}\":`)).join('') +\n            obj[k] +\n            '}'.repeat(keys.length)\n        )\n      );\n    } else acc[k] = obj[k];\n    return acc;\n  }, {});",
          "es5": "var unflattenObject = function unflattenObject(obj) {\n  return Object.keys(obj).reduce(function (acc, k) {\n    if (k.indexOf('.') !== -1) {\n      var keys = k.split('.');\n      Object.assign(acc, JSON.parse('{' + keys.map(function (v, i) {\n        return i !== keys.length - 1 ? \"\\\"\".concat(v, \"\\\":{\") : \"\\\"\".concat(v, \"\\\":\");\n      }).join('') + obj[k] + '}'.repeat(keys.length)));\n    } else acc[k] = obj[k];\n\n    return acc;\n  }, {});\n};",
          "example": "unflattenObject({ 'a.b.c': 1, d: 1 }); // { a: { b: { c: 1 } }, d: 1 }"
        },
        "tags": [
          "object",
          "advanced"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "85dbe7ffa7a0dd1cc5e505ea54328de8f7a3c9809f3a051528bf4bc1cd87262d"
      }
    },
    {
      "id": "unfold",
      "type": "snippet",
      "attributes": {
        "fileName": "unfold.md",
        "text": "Builds an array, using an iterator function and an initial seed value.\n\nUse a `while` loop and `Array.prototype.push()` to call the function repeatedly until it returns `false`.\nThe iterator function accepts one argument (`seed`) and must always return an array with two elements ([`value`, `nextSeed`]) or `false` to terminate.",
        "codeBlocks": {
          "es6": "const unfold = (fn, seed) => {\n  let result = [],\n    val = [null, seed];\n  while ((val = fn(val[1]))) result.push(val[0]);\n  return result;\n};",
          "es5": "var unfold = function unfold(fn, seed) {\n  var result = [],\n      val = [null, seed];\n\n  while (val = fn(val[1])) {\n    result.push(val[0]);\n  }\n\n  return result;\n};",
          "example": "var f = n => (n > 50 ? false : [-n, n + 10]);\nunfold(f, 10); // [-10, -20, -30, -40, -50]"
        },
        "tags": [
          "function",
          "array",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "f21e8aa2e101edce3f1dc6510ece098a51cc63a3fed4c0343d065bc96abdf3c8"
      }
    },
    {
      "id": "union",
      "type": "snippet",
      "attributes": {
        "fileName": "union.md",
        "text": "Returns every element that exists in any of the two arrays once.\n\nCreate a `Set` with all values of `a` and `b` and convert to an array.",
        "codeBlocks": {
          "es6": "const union = (a, b) => Array.from(new Set([...a, ...b]));",
          "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 union = function union(a, b) {\n  return Array.from(new Set(_toConsumableArray(a).concat(_toConsumableArray(b))));\n};",
          "example": "union([1, 2, 3], [4, 3, 2]); // [1,2,3,4]"
        },
        "tags": [
          "array",
          "math",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "89bdbb02f2dd1c5bc9d1272ff3f2d5249af763115b596e9f8bc801d0f2256ac3"
      }
    },
    {
      "id": "unionBy",
      "type": "snippet",
      "attributes": {
        "fileName": "unionBy.md",
        "text": "Returns every element that exists in any of the two arrays once, after applying the provided function to each array element of both.\n\nCreate a `Set` by applying all `fn` to all values of `a`.\nCreate a `Set` from `a` and all elements in `b` whose value, after applying `fn` does not match a value in the previously created set.\nReturn the last set converted to an array.",
        "codeBlocks": {
          "es6": "const unionBy = (a, b, fn) => {\n  const s = new Set(a.map(fn));\n  return Array.from(new Set([...a, ...b.filter(x => !s.has(fn(x)))]));\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 unionBy = function unionBy(a, b, fn) {\n  var s = new Set(a.map(fn));\n  return Array.from(new Set(_toConsumableArray(a).concat(_toConsumableArray(b.filter(function (x) {\n    return !s.has(fn(x));\n  })))));\n};",
          "example": "unionBy([2.1], [1.2, 2.3], Math.floor); // [2.1, 1.2]"
        },
        "tags": [
          "array",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "6311c46f59dfe85022a091d395293fc8afe353b8f6c23bc0d535cf8c90d7df27"
      }
    },
    {
      "id": "unionWith",
      "type": "snippet",
      "attributes": {
        "fileName": "unionWith.md",
        "text": "Returns every element that exists in any of the two arrays once, using a provided comparator function.\n\nCreate a `Set` with all values of `a` and values in `b` for which the comparator finds no matches in `a`, using `Array.prototype.findIndex()`.",
        "codeBlocks": {
          "es6": "const unionWith = (a, b, comp) =>\n  Array.from(new Set([...a, ...b.filter(x => a.findIndex(y => comp(x, y)) === -1)]));",
          "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 unionWith = function unionWith(a, b, comp) {\n  return Array.from(new Set(_toConsumableArray(a).concat(_toConsumableArray(b.filter(function (x) {\n    return a.findIndex(function (y) {\n      return comp(x, y);\n    }) === -1;\n  })))));\n};",
          "example": "unionWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0, 3.9], (a, b) => Math.round(a) === Math.round(b)); // [1, 1.2, 1.5, 3, 0, 3.9]"
        },
        "tags": [
          "array",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "c43cbb8a7a57f3873fde6b1c2ff16744c2332fcbb1e107ff581faadf9a742075"
      }
    },
    {
      "id": "uniqueElements",
      "type": "snippet",
      "attributes": {
        "fileName": "uniqueElements.md",
        "text": "Returns all unique values of an array.\n\nUse ES6 `Set` and the `...rest` operator to discard all duplicated values.",
        "codeBlocks": {
          "es6": "const uniqueElements = arr => [...new Set(arr)];",
          "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 uniqueElements = function uniqueElements(arr) {\n  return _toConsumableArray(new Set(arr));\n};",
          "example": "uniqueElements([1, 2, 2, 3, 4, 4, 5]); // [1, 2, 3, 4, 5]"
        },
        "tags": [
          "array",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "a58f3cb936234ebae488f907b8bf82f80a2966007cdff2972f658a969c250f46"
      }
    },
    {
      "id": "uniqueElementsBy",
      "type": "snippet",
      "attributes": {
        "fileName": "uniqueElementsBy.md",
        "text": "Returns all unique values of an array, based on a provided comparator function.\n\nUse `Array.prototype.reduce()` and `Array.prototype.some()` for an array containing only the first unique occurence of each value, based on the comparator function, `fn`.\nThe comparator function takes two arguments: the values of the two elements being compared.",
        "codeBlocks": {
          "es6": "const uniqueElementsBy = (arr, fn) =>\n  arr.reduce((acc, v) => {\n    if (!acc.some(x => fn(v, x))) acc.push(v);\n    return acc;\n  }, []);",
          "es5": "var uniqueElementsBy = function uniqueElementsBy(arr, fn) {\n  return arr.reduce(function (acc, v) {\n    if (!acc.some(function (x) {\n      return fn(v, x);\n    })) acc.push(v);\n    return acc;\n  }, []);\n};",
          "example": "uniqueElementsBy(\n  [\n    { id: 0, value: 'a' },\n    { id: 1, value: 'b' },\n    { id: 2, value: 'c' },\n    { id: 1, value: 'd' },\n    { id: 0, value: 'e' }\n  ],\n  (a, b) => a.id == b.id\n); // [ { id: 0, value: 'a' }, { id: 1, value: 'b' }, { id: 2, value: 'c' } ]"
        },
        "tags": [
          "array",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "38bee97eef5e2918ce534d6f25ad2a8b40d4841c7a663d9a9a596dd4687ce5bc"
      }
    },
    {
      "id": "uniqueElementsByRight",
      "type": "snippet",
      "attributes": {
        "fileName": "uniqueElementsByRight.md",
        "text": "Returns all unique values of an array, based on a provided comparator function.\n\nUse `Array.prototype.reduce()` and `Array.prototype.some()` for an array containing only the last unique occurence of each value, based on the comparator function, `fn`.\nThe comparator function takes two arguments: the values of the two elements being compared.",
        "codeBlocks": {
          "es6": "const uniqueElementsByRight = (arr, fn) =>\n  arr.reduceRight((acc, v) => {\n    if (!acc.some(x => fn(v, x))) acc.push(v);\n    return acc;\n  }, []);",
          "es5": "var uniqueElementsByRight = function uniqueElementsByRight(arr, fn) {\n  return arr.reduceRight(function (acc, v) {\n    if (!acc.some(function (x) {\n      return fn(v, x);\n    })) acc.push(v);\n    return acc;\n  }, []);\n};",
          "example": "uniqueElementsByRight(\n  [\n    { id: 0, value: 'a' },\n    { id: 1, value: 'b' },\n    { id: 2, value: 'c' },\n    { id: 1, value: 'd' },\n    { id: 0, value: 'e' }\n  ],\n  (a, b) => a.id == b.id\n); // [ { id: 0, value: 'e' }, { id: 1, value: 'd' }, { id: 2, value: 'c' } ]"
        },
        "tags": [
          "array",
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "cec8e5f01c8d00c246a12fabb43713a60da510f50c3d548f703f664936373096"
      }
    },
    {
      "id": "uniqueSymmetricDifference",
      "type": "snippet",
      "attributes": {
        "fileName": "uniqueSymmetricDifference.md",
        "text": "Returns the unique symmetric difference between two arrays, not containing duplicate values from either array.\n\nUse `Array.prototype.filter()` and `Array.prototype.includes()` on each array to remove values contained in the other, then create a `Set` from the results, removing duplicate values.",
        "codeBlocks": {
          "es6": "const uniqueSymmetricDifference = (a, b) => [\n  ...new Set([...a.filter(v => !b.includes(v)), ...b.filter(v => !a.includes(v))])\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 uniqueSymmetricDifference = function uniqueSymmetricDifference(a, b) {\n  return _toConsumableArray(new Set(_toConsumableArray(a.filter(function (v) {\n    return !b.includes(v);\n  })).concat(_toConsumableArray(b.filter(function (v) {\n    return !a.includes(v);\n  })))));\n};",
          "example": "uniqueSymmetricDifference([1, 2, 3], [1, 2, 4]); // [3, 4]\nuniqueSymmetricDifference([1, 2, 2], [1, 3, 1]); // [2, 3]"
        },
        "tags": [
          "array",
          "math",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "732b6077bcba350f004edeac5667d0d6d8403b2798e0860e5cd3d5a0c4578339"
      }
    },
    {
      "id": "untildify",
      "type": "snippet",
      "attributes": {
        "fileName": "untildify.md",
        "text": "Converts a tilde path to an absolute path.\n\nUse `String.prototype.replace()` with a regular expression and `OS.homedir()` to replace the `~` in the start of the path with the home directory.",
        "codeBlocks": {
          "es6": "const untildify = str => str.replace(/^~($|\\/|\\\\)/, `${require('os').homedir()}$1`);",
          "es5": "var untildify = function untildify(str) {\n  return str.replace(/^~($|\\/|\\\\)/, \"\".concat(require('os').homedir(), \"$1\"));\n};",
          "example": "untildify('~/node'); // '/Users/aUser/node'"
        },
        "tags": [
          "node",
          "string",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "16729b1197484dd3a2b1ea4c860f297f5318e1d34831f8cb4f548d1486f51aca"
      }
    },
    {
      "id": "unzip",
      "type": "snippet",
      "attributes": {
        "fileName": "unzip.md",
        "text": "Creates an array of arrays, ungrouping the elements in an array produced by [zip](#zip).\n\nUse `Math.max.apply()` to get the longest subarray in the array, `Array.prototype.map()` to make each element an array.\nUse `Array.prototype.reduce()` and `Array.prototype.forEach()` to map grouped values to individual arrays.",
        "codeBlocks": {
          "es6": "const unzip = arr =>\n  arr.reduce(\n    (acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc),\n    Array.from({\n      length: Math.max(...arr.map(x => x.length))\n    }).map(x => [])\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 unzip = function unzip(arr) {\n  return arr.reduce(function (acc, val) {\n    return val.forEach(function (v, i) {\n      return acc[i].push(v);\n    }), acc;\n  }, Array.from({\n    length: Math.max.apply(Math, _toConsumableArray(arr.map(function (x) {\n      return x.length;\n    })))\n  }).map(function (x) {\n    return [];\n  }));\n};",
          "example": "unzip([['a', 1, true], ['b', 2, false]]); // [['a', 'b'], [1, 2], [true, false]]\nunzip([['a', 1, true], ['b', 2]]); // [['a', 'b'], [1, 2], [true]]"
        },
        "tags": [
          "array",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "dbd21f42d2200f504459f4ce7d1b39e31be3a30373b4ce4feec5afa2c85b7ef7"
      }
    },
    {
      "id": "unzipWith",
      "type": "snippet",
      "attributes": {
        "fileName": "unzipWith.md",
        "text": "Creates an array of elements, ungrouping the elements in an array produced by [zip](#zip) and applying the provided function.\n\nUse `Math.max.apply()` to get the longest subarray in the array, `Array.prototype.map()` to make each element an array.\nUse `Array.prototype.reduce()` and `Array.prototype.forEach()` to map grouped values to individual arrays.\nUse `Array.prototype.map()` and the spread operator (`...`) to apply `fn` to each individual group of elements.",
        "codeBlocks": {
          "es6": "const unzipWith = (arr, fn) =>\n  arr\n    .reduce(\n      (acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc),\n      Array.from({\n        length: Math.max(...arr.map(x => x.length))\n      }).map(x => [])\n    )\n    .map(val => fn(...val));",
          "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 unzipWith = function unzipWith(arr, fn) {\n  return arr.reduce(function (acc, val) {\n    return val.forEach(function (v, i) {\n      return acc[i].push(v);\n    }), acc;\n  }, Array.from({\n    length: Math.max.apply(Math, _toConsumableArray(arr.map(function (x) {\n      return x.length;\n    })))\n  }).map(function (x) {\n    return [];\n  })).map(function (val) {\n    return fn.apply(void 0, _toConsumableArray(val));\n  });\n};",
          "example": "unzipWith([[1, 10, 100], [2, 20, 200]], (...args) => args.reduce((acc, v) => acc + v, 0)); // [3, 30, 300]"
        },
        "tags": [
          "array",
          "function",
          "advanced"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "fe3339dc49a247dabaa0ceca106f1393ea9731c05265f5cb45d5a3f0de09c7ae"
      }
    },
    {
      "id": "URLJoin",
      "type": "snippet",
      "attributes": {
        "fileName": "URLJoin.md",
        "text": "Joins all given URL segments together, then normalizes the resulting URL.\n\nUse `String.prototype.join('/')` to combine URL segments, then 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).",
        "codeBlocks": {
          "es6": "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('&', '?');",
          "es5": "var URLJoin = function URLJoin() {\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.join('/').replace(/[\\/]+/g, '/').replace(/^(.+):\\//, '$1://').replace(/^file:/, 'file:/').replace(/\\/(\\?|&|#[^!])/g, '$1').replace(/\\?/g, '&').replace('&', '?');\n};",
          "example": "URLJoin('http://www.google.com', 'a', '/b/cd', '?foo=123', '?bar=foo'); // 'http://www.google.com/a/b/cd?foo=123&bar=foo'"
        },
        "tags": [
          "string",
          "utility",
          "regexp",
          "advanced"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "cc0aa77cc2be8e663f52513e8dd2e5926a7d71dbda37967fdb50c223c3a0a5f9"
      }
    },
    {
      "id": "UUIDGeneratorBrowser",
      "type": "snippet",
      "attributes": {
        "fileName": "UUIDGeneratorBrowser.md",
        "text": "Generates a UUID in a browser.\n\nUse `crypto` API to generate a UUID, compliant with [RFC4122](https://www.ietf.org/rfc/rfc4122.txt) version 4.",
        "codeBlocks": {
          "es6": "const UUIDGeneratorBrowser = () =>\n  ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>\n    (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16)\n  );",
          "es5": "var UUIDGeneratorBrowser = function UUIDGeneratorBrowser() {\n  return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, function (c) {\n    return (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16);\n  });\n};",
          "example": "UUIDGeneratorBrowser(); // '7982fcfe-5721-4632-bede-6000885be57d'"
        },
        "tags": [
          "browser",
          "utility",
          "random",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "f43ad3f7f82d15a02cacb2b93c6324c64b55de1c630398ae501ff9b65bd9cb35"
      }
    },
    {
      "id": "UUIDGeneratorNode",
      "type": "snippet",
      "attributes": {
        "fileName": "UUIDGeneratorNode.md",
        "text": "Generates a UUID in Node.JS.\n\nUse `crypto` API to generate a UUID, compliant with [RFC4122](https://www.ietf.org/rfc/rfc4122.txt) version 4.",
        "codeBlocks": {
          "es6": "const crypto = require('crypto');\nconst UUIDGeneratorNode = () =>\n  ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>\n    (c ^ (crypto.randomBytes(1)[0] & (15 >> (c / 4)))).toString(16)\n  );",
          "es5": "var crypto = require('crypto');\n\nvar UUIDGeneratorNode = function UUIDGeneratorNode() {\n  return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, function (c) {\n    return (c ^ crypto.randomBytes(1)[0] & 15 >> c / 4).toString(16);\n  });\n};",
          "example": "UUIDGeneratorNode(); // '79c7c136-60ee-40a2-beb2-856f1feabefc'"
        },
        "tags": [
          "node",
          "utility",
          "random",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "119c813d32e4aa4faed7a497cbf1806e98da0f7c9090656ae02297fe9224b6a1"
      }
    },
    {
      "id": "validateNumber",
      "type": "snippet",
      "attributes": {
        "fileName": "validateNumber.md",
        "text": "Returns `true` if the given value is a number, `false` otherwise.\n\nUse `!isNaN()` in combination with `parseFloat()` to check if the argument is a number.\nUse `isFinite()` to check if the number is finite.\nUse `Number()` to check if the coercion holds.",
        "codeBlocks": {
          "es6": "const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n;",
          "es5": "var validateNumber = function validateNumber(n) {\n  return !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n;\n};",
          "example": "validateNumber('10'); // true"
        },
        "tags": [
          "utility",
          "math",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "8fb993b0cf78fa83a170aca132bf5eb13430e2cef5ae06f85b9763f286bb792c"
      }
    },
    {
      "id": "when",
      "type": "snippet",
      "attributes": {
        "fileName": "when.md",
        "text": "Tests a value, `x`, against a predicate function. If `true`, return `fn(x)`. Else, return `x`. \n\nReturn a function expecting a single value, `x`, that returns the appropriate value based on `pred`.",
        "codeBlocks": {
          "es6": "const when = (pred, whenTrue) => x => (pred(x) ? whenTrue(x) : x);",
          "es5": "var when = function when(pred, whenTrue) {\n  return function (x) {\n    return pred(x) ? whenTrue(x) : x;\n  };\n};",
          "example": "const doubleEvenNumbers = when(x => x % 2 === 0, x => x * 2);\ndoubleEvenNumbers(2); // 4\ndoubleEvenNumbers(1); // 1"
        },
        "tags": [
          "function",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "4c3fb917581972b732dbf8a998c377df247721790afa904956420d0e75b3b40a"
      }
    },
    {
      "id": "without",
      "type": "snippet",
      "attributes": {
        "fileName": "without.md",
        "text": "Filters out the elements of an array, that have one of the specified values.\n\nUse `Array.prototype.filter()` to create an array excluding(using `!Array.includes()`) all given values.\n\n_(For a snippet that mutates the original array see [`pull`](#pull))_",
        "codeBlocks": {
          "es6": "const without = (arr, ...args) => arr.filter(v => !args.includes(v));",
          "es5": "var without = function without(arr) {\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 arr.filter(function (v) {\n    return !args.includes(v);\n  });\n};",
          "example": "without([2, 1, 2, 3], 1, 2); // [3]"
        },
        "tags": [
          "array",
          "beginner"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "3482e1802a239290ac1170fc1dcb57a2b1197877444c9cca8d6be60c96412e32"
      }
    },
    {
      "id": "words",
      "type": "snippet",
      "attributes": {
        "fileName": "words.md",
        "text": "Converts a given string into an array of words.\n\nUse `String.prototype.split()` with a supplied pattern (defaults to non-alpha as a regexp) to convert to an array of strings. Use `Array.prototype.filter()` to remove any empty strings.\nOmit the second argument to use the default regexp.",
        "codeBlocks": {
          "es6": "const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean);",
          "es5": "var words = function words(str) {\n  var pattern = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : /[^a-zA-Z-]+/;\n  return str.split(pattern).filter(Boolean);\n};",
          "example": "words('I love javaScript!!'); // [\"I\", \"love\", \"javaScript\"]\nwords('python, javaScript & coffee'); // [\"python\", \"javaScript\", \"coffee\"]"
        },
        "tags": [
          "string",
          "regexp",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "3e68caecbfce1d15160a60993a3270793a1573bda3c71a82fc0086fe48b17a0a"
      }
    },
    {
      "id": "xProd",
      "type": "snippet",
      "attributes": {
        "fileName": "xProd.md",
        "text": "Creates a new array out of the two supplied by creating each possible pair from the arrays.\n\nUse `Array.prototype.reduce()`, `Array.prototype.map()` and `Array.prototype.concat()` to produce every possible pair from the elements of the two arrays and save them in an array.",
        "codeBlocks": {
          "es6": "const xProd = (a, b) => a.reduce((acc, x) => acc.concat(b.map(y => [x, y])), []);",
          "es5": "var xProd = function xProd(a, b) {\n  return a.reduce(function (acc, x) {\n    return acc.concat(b.map(function (y) {\n      return [x, y];\n    }));\n  }, []);\n};",
          "example": "xProd([1, 2], ['a', 'b']); // [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]"
        },
        "tags": [
          "array",
          "math",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "e6d1da6add041592649c4c054de54a35516a8100d9bf8a4209ee0aa7e88f4550"
      }
    },
    {
      "id": "yesNo",
      "type": "snippet",
      "attributes": {
        "fileName": "yesNo.md",
        "text": "Returns `true` if the string is `y`/`yes` or `false` if the string is `n`/`no`.\n\nUse `RegExp.test()` to check if the string evaluates to `y/yes` or `n/no`.\nOmit the second argument, `def` to set the default answer as `no`.",
        "codeBlocks": {
          "es6": "const yesNo = (val, def = false) =>\n  /^(y|yes)$/i.test(val) ? true : /^(n|no)$/i.test(val) ? false : def;",
          "es5": "var yesNo = function yesNo(val) {\n  var def = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n  return /^(y|yes)$/i.test(val) ? true : /^(n|no)$/i.test(val) ? false : def;\n};",
          "example": "yesNo('Y'); // true\nyesNo('yes'); // true\nyesNo('No'); // false\nyesNo('Foo', true); // true"
        },
        "tags": [
          "utility",
          "regexp",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "86e7f2674d08de8520abe029aa6be760449367102a6578bb8efd9703508c63a2"
      }
    },
    {
      "id": "zip",
      "type": "snippet",
      "attributes": {
        "fileName": "zip.md",
        "text": "Creates an array of elements, grouped based on the position in the original arrays.\n\nUse `Math.max.apply()` to get the longest array in the arguments.\nCreates an array with that length as return value and use `Array.from()` with a map-function to create an array of grouped elements.\nIf lengths of the argument-arrays vary, `undefined` is used where no value could be found.",
        "codeBlocks": {
          "es6": "const zip = (...arrays) => {\n  const maxLength = Math.max(...arrays.map(x => x.length));\n  return Array.from({ length: maxLength }).map((_, i) => {\n    return Array.from({ length: arrays.length }, (_, k) => arrays[k][i]);\n  });\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 zip = function zip() {\n  for (var _len = arguments.length, arrays = new Array(_len), _key = 0; _key < _len; _key++) {\n    arrays[_key] = arguments[_key];\n  }\n\n  var maxLength = Math.max.apply(Math, _toConsumableArray(arrays.map(function (x) {\n    return x.length;\n  })));\n  return Array.from({\n    length: maxLength\n  }).map(function (_, i) {\n    return Array.from({\n      length: arrays.length\n    }, function (_, k) {\n      return arrays[k][i];\n    });\n  });\n};",
          "example": "zip(['a', 'b'], [1, 2], [true, false]); // [['a', 1, true], ['b', 2, false]]\nzip(['a'], [1, 2], [true, false]); // [['a', 1, true], [undefined, 2, false]]"
        },
        "tags": [
          "array",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "66cedb84131bd3704fc8dc3f9a8692d7a08a990ae749ff8cff688ced18239126"
      }
    },
    {
      "id": "zipObject",
      "type": "snippet",
      "attributes": {
        "fileName": "zipObject.md",
        "text": "Given an array of valid property identifiers and an array of values, return an object associating the properties to the values.\n\nSince an object can have undefined values but not undefined property pointers, the array of properties is used to decide the structure of the resulting object using `Array.prototype.reduce()`.",
        "codeBlocks": {
          "es6": "const zipObject = (props, values) =>\n  props.reduce((obj, prop, index) => ((obj[prop] = values[index]), obj), {});",
          "es5": "var zipObject = function zipObject(props, values) {\n  return props.reduce(function (obj, prop, index) {\n    return obj[prop] = values[index], obj;\n  }, {});\n};",
          "example": "zipObject(['a', 'b', 'c'], [1, 2]); // {a: 1, b: 2, c: undefined}\nzipObject(['a', 'b'], [1, 2, 3]); // {a: 1, b: 2}"
        },
        "tags": [
          "array",
          "object",
          "intermediate"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "75f51c079a3b129de5ff1ca656422126cae7e4ded12a74038a0453efa0bfab96"
      }
    },
    {
      "id": "zipWith",
      "type": "snippet",
      "attributes": {
        "fileName": "zipWith.md",
        "text": "Creates an array of elements, grouped based on the position in the original arrays and using function as the last value to specify how grouped values should be combined.\n\nCheck if the last argument provided is a function.\nUse `Math.max()` to get the longest array in the arguments.\nCreates an array with that length as return value and use `Array.from()` with a map-function to create an array of grouped elements.\nIf lengths of the argument-arrays vary, `undefined` is used where no value could be found.\nThe function is invoked with the elements of each group `(...group)`.",
        "codeBlocks": {
          "es6": "const zipWith = (...array) => {\n  const fn = typeof array[array.length - 1] === 'function' ? array.pop() : undefined;\n  return Array.from(\n    { length: Math.max(...array.map(a => a.length)) },\n    (_, i) => (fn ? fn(...array.map(a => a[i])) : array.map(a => a[i]))\n  );\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 zipWith = function zipWith() {\n  for (var _len = arguments.length, array = new Array(_len), _key = 0; _key < _len; _key++) {\n    array[_key] = arguments[_key];\n  }\n\n  var fn = typeof array[array.length - 1] === 'function' ? array.pop() : undefined;\n  return Array.from({\n    length: Math.max.apply(Math, _toConsumableArray(array.map(function (a) {\n      return a.length;\n    })))\n  }, function (_, i) {\n    return fn ? fn.apply(void 0, _toConsumableArray(array.map(function (a) {\n      return a[i];\n    }))) : array.map(function (a) {\n      return a[i];\n    });\n  });\n};",
          "example": "zipWith([1, 2], [10, 20], [100, 200], (a, b, c) => a + b + c); // [111,222]\nzipWith(\n  [1, 2, 3],\n  [10, 20],\n  [100, 200],\n  (a, b, c) => (a != null ? a : 'a') + (b != null ? b : 'b') + (c != null ? c : 'c')\n); // [111, 222, '3bc']"
        },
        "tags": [
          "array",
          "function",
          "advanced"
        ]
      },
      "meta": {
        "archived": false,
        "hash": "c30a9938878dbc4f535c16d16c59e0a7c09643164332f7790345f95557b44303"
      }
    },
    {
      "id": "binarySearch",
      "type": "snippet",
      "attributes": {
        "fileName": "binarySearch.md",
        "text": "Use recursion. Similar to `Array.prototype.indexOf()` that finds the index of a value within an array.\nThe difference being this operation only works with sorted arrays which offers a major performance boost due to it's logarithmic nature when compared to a linear search or `Array.prototype.indexOf()`.\n\nSearch a sorted array by repeatedly dividing the search interval in half.\nBegin with an interval covering the whole array.\nIf the value of the search is less than the item in the middle of the interval, recurse into the lower half. Otherwise recurse into the upper half.\nRepeatedly recurse until the value is found which is the mid or you've recursed to a point that is greater than the length which means the value doesn't exist and return `-1`.",
        "codeBlocks": {
          "es6": "const binarySearch = (arr, val, start = 0, end = arr.length - 1) => {\n  if (start > end) return -1;\n  const mid = Math.floor((start + end) / 2);\n  if (arr[mid] > val) return binarySearch(arr, val, start, mid - 1);\n  if (arr[mid] < val) return binarySearch(arr, val, mid + 1, end);\n  return mid;\n};",
          "es5": "var binarySearch = function binarySearch(arr, val) {\n  var start = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;\n  var end = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : arr.length - 1;\n  if (start > end) return -1;\n  var mid = Math.floor((start + end) / 2);\n  if (arr[mid] > val) return binarySearch(arr, val, start, mid - 1);\n  if (arr[mid] < val) return binarySearch(arr, val, mid + 1, end);\n  return mid;\n};",
          "example": "binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 6); // 2\nbinarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 21); // -1"
        },
        "tags": []
      },
      "meta": {
        "archived": true,
        "hash": "1ec820569490b17af8315133226e1545efb1d842e4dada922c88126c342a2132"
      }
    },
    {
      "id": "celsiusToFahrenheit",
      "type": "snippet",
      "attributes": {
        "fileName": "celsiusToFahrenheit.md",
        "text": "Celsius to Fahrenheit temperature conversion.\n\nFollows the conversion formula `F =  1.8C + 32`.",
        "codeBlocks": {
          "es6": "const celsiusToFahrenheit = degrees => 1.8 * degrees + 32;",
          "es5": "var celsiusToFahrenheit = function celsiusToFahrenheit(degrees) {\n  return 1.8 * degrees + 32;\n};",
          "example": "celsiusToFahrenheit(33) // 91.4"
        },
        "tags": []
      },
      "meta": {
        "archived": true,
        "hash": "8289007c7b10777d68d346e0ef02a58a44472cee41d5fb2f3bafaec4f1dd148b"
      }
    },
    {
      "id": "cleanObj",
      "type": "snippet",
      "attributes": {
        "fileName": "cleanObj.md",
        "text": "Removes any properties except the ones specified from a JSON object.\n\nUse `Object.keys()` method to loop over given JSON object and deleting keys that are not included in given array.\nIf you pass a special key,`childIndicator`, it will search deeply apply the function to inner objects, too.",
        "codeBlocks": {
          "es6": "const cleanObj = (obj, keysToKeep = [], childIndicator) => {\n  Object.keys(obj).forEach(key => {\n    if (key === childIndicator) {\n      cleanObj(obj[key], keysToKeep, childIndicator);\n    } else if (!keysToKeep.includes(key)) {\n      delete obj[key];\n    }\n  });\n  return obj;\n};",
          "es5": "var cleanObj = function cleanObj(obj) {\n  var keysToKeep = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];\n  var childIndicator = arguments.length > 2 ? arguments[2] : undefined;\n  Object.keys(obj).forEach(function (key) {\n    if (key === childIndicator) {\n      cleanObj(obj[key], keysToKeep, childIndicator);\n    } else if (!keysToKeep.includes(key)) {\n      delete obj[key];\n    }\n  });\n  return obj;\n};",
          "example": "const testObj = { a: 1, b: 2, children: { a: 1, b: 2 } };\ncleanObj(testObj, ['a'], 'children'); // { a: 1, children : { a: 1}}"
        },
        "tags": []
      },
      "meta": {
        "archived": true,
        "hash": "ec33abb9423c49520400becb5183d87b37bbf6eb60012673c8df5a0a672a6af0"
      }
    },
    {
      "id": "collatz",
      "type": "snippet",
      "attributes": {
        "fileName": "collatz.md",
        "text": "Applies the Collatz algorithm.\n\nIf `n` is even, return `n/2`. Otherwise, return `3n+1`.",
        "codeBlocks": {
          "es6": "const collatz = n => (n % 2 === 0 ? n / 2 : 3 * n + 1);",
          "es5": "var collatz = function collatz(n) {\n  return n % 2 === 0 ? n / 2 : 3 * n + 1;\n};",
          "example": "collatz(8); // 4"
        },
        "tags": []
      },
      "meta": {
        "archived": true,
        "hash": "650c91d557244ee0e3f64a00d457d63b47271aa0b963728bfc37dc5c3c88c67e"
      }
    },
    {
      "id": "countVowels",
      "type": "snippet",
      "attributes": {
        "fileName": "countVowels.md",
        "text": "Retuns `number` of vowels in provided string.\n\nUse a regular expression to count the number of vowels `(A, E, I, O, U)` in a `string`.",
        "codeBlocks": {
          "es6": "const countVowels = str => (str.match(/[aeiou]/gi) || []).length;",
          "es5": "var countVowels = function countVowels(str) {\n  return (str.match(/[aeiou]/gi) || []).length;\n};",
          "example": "countVowels('foobar'); // 3\ncountVowels('gym'); // 0"
        },
        "tags": []
      },
      "meta": {
        "archived": true,
        "hash": "333c7a72864d3249f1f409dee1f23214ec47701a54d561a69078e0092137fa4c"
      }
    },
    {
      "id": "factors",
      "type": "snippet",
      "attributes": {
        "fileName": "factors.md",
        "text": "Returns the array of factors of the given `num`.\nIf the second argument is set to `true` returns only the prime factors of `num`.\nIf `num` is `1` or `0` returns an empty array.\nIf `num` is less than `0` returns all the factors of `-int` together with their additive inverses.\n\nUse `Array.from()`, `Array.prototype.map()` and `Array.prototype.filter()` to find all the factors of `num`.\nIf given `num` is negative, use `Array.prototype.reduce()` to add the additive inverses to the array.\nReturn all results if `primes` is `false`, else determine and return only the prime factors using `isPrime` and `Array.prototype.filter()`.\nOmit the second argument, `primes`, to return prime and non-prime factors by default.\n\n**Note**:- _Negative numbers are not considered prime._",
        "codeBlocks": {
          "es6": "const factors = (num, primes = false) => {\n  const isPrime = num => {\n    const boundary = Math.floor(Math.sqrt(num));\n    for (var i = 2; i <= boundary; i++) if (num % i === 0) return false;\n    return num >= 2;\n  };\n  const isNeg = num < 0;\n  num = isNeg ? -num : num;\n  let array = Array.from({ length: num - 1 })\n    .map((val, i) => (num % (i + 2) === 0 ? i + 2 : false))\n    .filter(val => val);\n  if (isNeg)\n    array = array.reduce((acc, val) => {\n      acc.push(val);\n      acc.push(-val);\n      return acc;\n    }, []);\n  return primes ? array.filter(isPrime) : array;\n};",
          "es5": "var factors = function factors(num) {\n  var primes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n\n  var isPrime = function isPrime(num) {\n    var boundary = Math.floor(Math.sqrt(num));\n\n    for (var i = 2; i <= boundary; i++) {\n      if (num % i === 0) return false;\n    }\n\n    return num >= 2;\n  };\n\n  var isNeg = num < 0;\n  num = isNeg ? -num : num;\n  var array = Array.from({\n    length: num - 1\n  }).map(function (val, i) {\n    return num % (i + 2) === 0 ? i + 2 : false;\n  }).filter(function (val) {\n    return val;\n  });\n  if (isNeg) array = array.reduce(function (acc, val) {\n    acc.push(val);\n    acc.push(-val);\n    return acc;\n  }, []);\n  return primes ? array.filter(isPrime) : array;\n};",
          "example": "factors(12); // [2,3,4,6,12]\nfactors(12, true); // [2,3]\nfactors(-12); // [2, -2, 3, -3, 4, -4, 6, -6, 12, -12]\nfactors(-12, true); // [2,3]"
        },
        "tags": []
      },
      "meta": {
        "archived": true,
        "hash": "e0056bb031e8df0565daddb6200df1fa9675e2c538e71f354ceeeee164c2b8a9"
      }
    },
    {
      "id": "fahrenheitToCelsius",
      "type": "snippet",
      "attributes": {
        "fileName": "fahrenheitToCelsius.md",
        "text": "Fahrenheit to Celsius temperature conversion.\n\nFollows the conversion formula `C = (F - 32) * 5/9`.",
        "codeBlocks": {
          "es6": "const fahrenheitToCelsius = degrees => (degrees - 32) * 5/9;",
          "es5": "var fahrenheitToCelsius = function fahrenheitToCelsius(degrees) {\n  return (degrees - 32) * 5 / 9;\n};",
          "example": "fahrenheitToCelsius(32); // 0"
        },
        "tags": []
      },
      "meta": {
        "archived": true,
        "hash": "89d58eda3d03f8fc8d2fe61fb36376f92a0443435552d063d4fbf5b623fc4314"
      }
    },
    {
      "id": "fibonacciCountUntilNum",
      "type": "snippet",
      "attributes": {
        "fileName": "fibonacciCountUntilNum.md",
        "text": "Returns the number of fibonnacci numbers up to `num`(`0` and `num` inclusive).\n\nUse a mathematical formula to calculate the number of fibonacci numbers until `num`.",
        "codeBlocks": {
          "es6": "const fibonacciCountUntilNum = num =>\n  Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));",
          "es5": "var fibonacciCountUntilNum = function fibonacciCountUntilNum(num) {\n  return Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));\n};",
          "example": "fibonacciCountUntilNum(10); // 7"
        },
        "tags": []
      },
      "meta": {
        "archived": true,
        "hash": "d93d0af81aeca41981ed58548672652f9c5ca4b2a6bb887c2c7e0595112dd035"
      }
    },
    {
      "id": "fibonacciUntilNum",
      "type": "snippet",
      "attributes": {
        "fileName": "fibonacciUntilNum.md",
        "text": "Generates an array, containing the Fibonacci sequence, up until the nth term.\n\nCreate an empty array of the specific length, initializing the first two values (`0` and `1`).\nUse `Array.prototype.reduce()` to add values into the array, using the sum of the last two values, except for the first two.\nUses a mathematical formula to calculate the length of the array required.",
        "codeBlocks": {
          "es6": "const fibonacciUntilNum = num => {\n  let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));\n  return Array.from({ length: n }).reduce(\n    (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),\n    []\n  );\n};",
          "es5": "var fibonacciUntilNum = function fibonacciUntilNum(num) {\n  var n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));\n  return Array.from({\n    length: n\n  }).reduce(function (acc, val, i) {\n    return acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i);\n  }, []);\n};",
          "example": "fibonacciUntilNum(10); // [ 0, 1, 1, 2, 3, 5, 8 ]"
        },
        "tags": []
      },
      "meta": {
        "archived": true,
        "hash": "9de50bed5b8c247176570f743c8154a5ec4093432f8a09ba91c423d78af47169"
      }
    },
    {
      "id": "heronArea",
      "type": "snippet",
      "attributes": {
        "fileName": "heronArea.md",
        "text": "Returns the area of a triangle using only the 3 side lengths, Heron's formula. Assumes that the sides define a valid triangle. Does NOT assume it is a right triangle.\n\nMore information on what Heron's formula is and why it works available here: https://en.wikipedia.org/wiki/Heron%27s_formula.\n\nUses `Math.sqrt()` to find the square root of a value.",
        "codeBlocks": {
          "es6": "const heronArea = (side_a, side_b, side_c) => {\n    const p = (side_a + side_b + side_c) / 2\n    return Math.sqrt(p * (p-side_a) * (p-side_b) * (p-side_c))\n  };",
          "es5": "var heronArea = function heronArea(side_a, side_b, side_c) {\n  var p = (side_a + side_b + side_c) / 2;\n  return Math.sqrt(p * (p - side_a) * (p - side_b) * (p - side_c));\n};",
          "example": "heronArea(3, 4, 5); // 6"
        },
        "tags": []
      },
      "meta": {
        "archived": true,
        "hash": "594721a84a8fe31c32482e9f475f5126b7cf499462d9408b3cfaee2021a96a30"
      }
    },
    {
      "id": "howManyTimes",
      "type": "snippet",
      "attributes": {
        "fileName": "howManyTimes.md",
        "text": "Returns the number of times `num` can be divided by `divisor` (integer or fractional) without getting a fractional answer.\nWorks for both negative and positive integers.\n\nIf `divisor` is `-1` or `1` return `Infinity`.\nIf `divisor` is `-0` or `0` return `0`.\nOtherwise, keep dividing `num` with `divisor` and incrementing `i`, while the result is an integer.\nReturn the number of times the loop was executed, `i`.",
        "codeBlocks": {
          "es6": "const howManyTimes = (num, divisor) => {\n  if (divisor === 1 || divisor === -1) return Infinity;\n  if (divisor === 0) return 0;\n  let i = 0;\n  while (Number.isInteger(num / divisor)) {\n    i++;\n    num = num / divisor;\n  }\n  return i;\n};",
          "es5": "var howManyTimes = function howManyTimes(num, divisor) {\n  if (divisor === 1 || divisor === -1) return Infinity;\n  if (divisor === 0) return 0;\n  var i = 0;\n\n  while (Number.isInteger(num / divisor)) {\n    i++;\n    num = num / divisor;\n  }\n\n  return i;\n};",
          "example": "howManyTimes(100, 2); // 2\nhowManyTimes(100, 2.5); // 2\nhowManyTimes(100, 0); // 0\nhowManyTimes(100, -1); // Infinity"
        },
        "tags": []
      },
      "meta": {
        "archived": true,
        "hash": "41f76138f7e673020c6eecd592baea18016869d7d0161edd9d7669f3a991c398"
      }
    },
    {
      "id": "httpDelete",
      "type": "snippet",
      "attributes": {
        "fileName": "httpDelete.md",
        "text": "Makes a `DELETE` request to the passed URL.\n\nUse `XMLHttpRequest` web api to make a `delete` request to the given `url`.\nHandle the `onload` event, by running the provided `callback` function.\nHandle the `onerror` event, by running the provided `err` function.\nOmit the third argument, `err` to log the request to the console's error stream by default.",
        "codeBlocks": {
          "es6": "const httpDelete = (url, callback, err = console.error) => {\n  const request = new XMLHttpRequest();\n  request.open('DELETE', url, true);\n  request.onload = () => callback(request);\n  request.onerror = () => err(request);\n  request.send();\n};",
          "es5": "var httpDelete = function httpDelete(url, callback) {\n  var err = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : console.error;\n  var request = new XMLHttpRequest();\n  request.open('DELETE', url, true);\n\n  request.onload = function () {\n    return callback(request);\n  };\n\n  request.onerror = function () {\n    return err(request);\n  };\n\n  request.send();\n};",
          "example": "httpDelete('https://website.com/users/123', request => {\n  console.log(request.responseText);\n}); // 'Deletes a user from the database'"
        },
        "tags": []
      },
      "meta": {
        "archived": true,
        "hash": "0b543697856c3c91e3e0a58d3928d743dbe8a369e7263fbc9806aedf487ff723"
      }
    },
    {
      "id": "httpPut",
      "type": "snippet",
      "attributes": {
        "fileName": "httpPut.md",
        "text": "Makes a `PUT` request to the passed URL.\n\nUse `XMLHttpRequest` web api to make a `put` request to the given `url`.\nSet the value of an `HTTP` request header with `setRequestHeader` method.\nHandle the `onload` event, by running the provided `callback` function.\nHandle the `onerror` event, by running the provided `err` function.\nOmit the last argument, `err` to log the request to the console's error stream by default.",
        "codeBlocks": {
          "es6": "const httpPut = (url, data, callback, err = console.error) => {\n  const request = new XMLHttpRequest();\n  request.open(\"PUT\", url, true);\n  request.setRequestHeader('Content-type','application/json; charset=utf-8');\n  request.onload = () => callback(request);\n  request.onerror = () => err(request);\n  request.send(data);\n};",
          "es5": "var httpPut = function httpPut(url, data, callback) {\n  var err = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : console.error;\n  var request = new XMLHttpRequest();\n  request.open(\"PUT\", url, true);\n  request.setRequestHeader('Content-type', 'application/json; charset=utf-8');\n\n  request.onload = function () {\n    return callback(request);\n  };\n\n  request.onerror = function () {\n    return err(request);\n  };\n\n  request.send(data);\n};",
          "example": "const password = \"fooBaz\";\nconst data = JSON.stringify(password);\nhttpPut('https://website.com/users/123', data, request => {\n  console.log(request.responseText);\n}); // 'Updates a user's password in database'"
        },
        "tags": []
      },
      "meta": {
        "archived": true,
        "hash": "59572ee267c7f0bc7c4e411ebde24834a2f5e8e928e2e50c16ac787034b1a53a"
      }
    },
    {
      "id": "isArmstrongNumber",
      "type": "snippet",
      "attributes": {
        "fileName": "isArmstrongNumber.md",
        "text": "Checks if the given number is an Armstrong number or not.\n\nConvert the given number into an array of digits. Use the exponent operator (`**`) to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return `true` otherwise `false`.",
        "codeBlocks": {
          "es6": "const isArmstrongNumber = digits =>\n  (arr => arr.reduce((a, d) => a + parseInt(d) ** arr.length, 0) == digits)(\n    (digits + '').split('')\n  );",
          "es5": "var isArmstrongNumber = function isArmstrongNumber(digits) {\n  return function (arr) {\n    return arr.reduce(function (a, d) {\n      return a + Math.pow(parseInt(d), arr.length);\n    }, 0) == digits;\n  }((digits + '').split(''));\n};",
          "example": "isArmstrongNumber(1634); // true\nisArmstrongNumber(56); // false"
        },
        "tags": []
      },
      "meta": {
        "archived": true,
        "hash": "28a3c44cfc4ec7d34e00b2866b67bff9b3fb100f6f72c767b893159b869fd8f4"
      }
    },
    {
      "id": "isSimilar",
      "type": "snippet",
      "attributes": {
        "fileName": "isSimilar.md",
        "text": "Determines if the `pattern` matches with `str`.\n\nUse `String.toLowerCase()` to convert both strings to lowercase, then loop through `str` and determine if it contains all characters of `pattern` and in the correct order.\nAdapted from [here](https://github.com/forrestthewoods/lib_fts/blob/80f3f8c52db53428247e741b9efe2cde9667050c/code/fts_fuzzy_match.js#L18).",
        "codeBlocks": {
          "es6": "const isSimilar = (pattern, str) =>\n  [...str].reduce(\n      (matchIndex, char) =>\n          char.toLowerCase() === (pattern[matchIndex] || '').toLowerCase()\n              ? matchIndex + 1\n              : matchIndex,\n      0\n  ) === pattern.length;",
          "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 isSimilar = function isSimilar(pattern, str) {\n  return _toConsumableArray(str).reduce(function (matchIndex, char) {\n    return char.toLowerCase() === (pattern[matchIndex] || '').toLowerCase() ? matchIndex + 1 : matchIndex;\n  }, 0) === pattern.length;\n};",
          "example": "isSimilar('rt','Rohit'); // true\nisSimilar('tr','Rohit'); // false"
        },
        "tags": []
      },
      "meta": {
        "archived": true,
        "hash": "7a3643ea48d34cc34e33f256cb41ca6a8ad1b8a8830ba2ed3e2354aea3a7bb52"
      }
    },
    {
      "id": "JSONToDate",
      "type": "snippet",
      "attributes": {
        "fileName": "JSONToDate.md",
        "text": "Converts a JSON object to a date.\n\nUse `Date()`, to convert dates in JSON format to readable format (`dd/mm/yyyy`).",
        "codeBlocks": {
          "es6": "const JSONToDate = arr => {\n  const dt = new Date(parseInt(arr.toString().substr(6)));\n  return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`;\n};",
          "es5": "var JSONToDate = function JSONToDate(arr) {\n  var dt = new Date(parseInt(arr.toString().substr(6)));\n  return \"\".concat(dt.getDate(), \"/\").concat(dt.getMonth() + 1, \"/\").concat(dt.getFullYear());\n};",
          "example": "JSONToDate(/Date(1489525200000)/); // \"14/3/2017\""
        },
        "tags": []
      },
      "meta": {
        "archived": true,
        "hash": "eb80d886a67c11c9395bcb414beb1e684c875b1318025609b7e12c44a58d99e9"
      }
    },
    {
      "id": "kmphToMph",
      "type": "snippet",
      "attributes": {
        "fileName": "kmphToMph.md",
        "text": "Convert kilometers/hour to miles/hour.\n\nMultiply the constant of proportionality with the argument.",
        "codeBlocks": {
          "es6": "const kmphToMph = (kmph) => 0.621371192 * kmph;",
          "es5": "var kmphToMph = function kmphToMph(kmph) {\n  return 0.621371192 * kmph;\n};",
          "example": "kmphToMph(10); // 16.09344000614692\nkmphToMph(345.4); // 138.24264965280207"
        },
        "tags": []
      },
      "meta": {
        "archived": true,
        "hash": "eb96ed6f8063723296da25db7282ad732b35c21cfef2bb1424068ff6a789311c"
      }
    },
    {
      "id": "levenshteinDistance",
      "type": "snippet",
      "attributes": {
        "fileName": "levenshteinDistance.md",
        "text": "Calculates the [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) between two strings.\n\nCalculates the number of changes (substitutions, deletions or additions) required to convert `string1` to `string2`. \nCan also be used to compare two strings as shown in the second example.",
        "codeBlocks": {
          "es6": "``` js\nconst levenshteinDistance = (string1, string2) => {\n  if (string1.length === 0) return string2.length;\n  if (string2.length === 0) return string1.length;\n  let matrix = Array(string2.length + 1)\n    .fill(0)\n    .map((x, i) => [i]);\n  matrix[0] = Array(string1.length + 1)\n    .fill(0)\n    .map((x, i) => i);\n  for (let i = 1; i <= string2.length; i++) {\n    for (let j = 1; j <= string1.length; j++) {\n      if (string2[i - 1] === string1[j - 1]) {\n        matrix[i][j] = matrix[i - 1][j - 1];\n      } else {\n        matrix[i][j] = Math.min(\n          matrix[i - 1][j - 1] + 1,\n          matrix[i][j - 1] + 1,\n          matrix[i - 1][j] + 1\n        );\n      }\n    }\n  }\n  return matrix[string2.length][string1.length];\n};\n```",
          "es5": "function _templateObject2() {\n  var data = _taggedTemplateLiteral([\" js\\nconst levenshteinDistance = (string1, string2) => {\\n  if (string1.length === 0) return string2.length;\\n  if (string2.length === 0) return string1.length;\\n  let matrix = Array(string2.length + 1)\\n    .fill(0)\\n    .map((x, i) => [i]);\\n  matrix[0] = Array(string1.length + 1)\\n    .fill(0)\\n    .map((x, i) => i);\\n  for (let i = 1; i <= string2.length; i++) {\\n    for (let j = 1; j <= string1.length; j++) {\\n      if (string2[i - 1] === string1[j - 1]) {\\n        matrix[i][j] = matrix[i - 1][j - 1];\\n      } else {\\n        matrix[i][j] = Math.min(\\n          matrix[i - 1][j - 1] + 1,\\n          matrix[i][j - 1] + 1,\\n          matrix[i - 1][j] + 1\\n        );\\n      }\\n    }\\n  }\\n  return matrix[string2.length][string1.length];\\n};\\n\"]);\n\n  _templateObject2 = function _templateObject2() {\n    return data;\n  };\n\n  return data;\n}\n\nfunction _templateObject() {\n  var data = _taggedTemplateLiteral([\"\"]);\n\n  _templateObject = function _templateObject() {\n    return data;\n  };\n\n  return data;\n}\n\nfunction _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); }\n\n\"\"(_templateObject2())(_templateObject());",
          "example": "levenshteinDistance('30-seconds-of-code','30-seconds-of-python-code'); // 7\nconst compareStrings = (string1,string2) => (100 - levenshteinDistance(string1,string2) / Math.max(string1.length,string2.length));\ncompareStrings('30-seconds-of-code', '30-seconds-of-python-code'); // 99.72 (%)"
        },
        "tags": []
      },
      "meta": {
        "archived": true,
        "hash": "3cc34a842404de0aea2752a6b1398b8a0825cb1a359ff36ab5275f7d15eff107"
      }
    },
    {
      "id": "mphToKmph",
      "type": "snippet",
      "attributes": {
        "fileName": "mphToKmph.md",
        "text": "Convert miles/hour to kilometers/hour.\n\nMultiply the constant of proportionality with the argument.",
        "codeBlocks": {
          "es6": "const mphToKmph = (mph) => 1.6093440006146922 * mph;",
          "es5": "var mphToKmph = function mphToKmph(mph) {\n  return 1.6093440006146922 * mph;\n};",
          "example": "mphToKmph(10); // 16.09344000614692\nmphToKmph(85.9); // 138.24264965280207"
        },
        "tags": []
      },
      "meta": {
        "archived": true,
        "hash": "174fc1687b3d809f2984e6e7e3e73af321c2bc0030ab1c05c1b1e2a817664e95"
      }
    },
    {
      "id": "pipeLog",
      "type": "snippet",
      "attributes": {
        "fileName": "pipeLog.md",
        "text": "Logs a value and returns it.\n\nUse `console.log` to log the supplied value, combined with the `||` operator to return it.",
        "codeBlocks": {
          "es6": "const pipeLog = data => console.log(data) || data;",
          "es5": "var pipeLog = function pipeLog(data) {\n  return console.log(data) || data;\n};",
          "example": "pipeLog(1); // logs `1` and returns `1`"
        },
        "tags": []
      },
      "meta": {
        "archived": true,
        "hash": "da9808c8ba24ab48b5407ccf48053281bf12627cbe6e24c1b820bfb1216384cb"
      }
    },
    {
      "id": "quickSort",
      "type": "snippet",
      "attributes": {
        "fileName": "quickSort.md",
        "text": "QuickSort an Array (ascending sort by default).\n\nUse recursion.\nUse `Array.prototype.filter` and spread operator (`...`) to create an array that all elements with values less than the pivot come before the pivot, and all elements with values greater than the pivot come after it.\nIf the parameter `desc` is truthy, return array sorts in descending order.",
        "codeBlocks": {
          "es6": "const quickSort = ([n, ...nums], desc) =>\n  isNaN(n)\n    ? []\n    : [\n        ...quickSort(nums.filter(v => (desc ? v > n : v <= n)), desc),\n        n,\n        ...quickSort(nums.filter(v => (!desc ? v > n : v <= n)), desc)\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 _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\nfunction _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 quickSort = function quickSort(_ref, desc) {\n  var _ref2 = _toArray(_ref),\n      n = _ref2[0],\n      nums = _ref2.slice(1);\n\n  return isNaN(n) ? [] : _toConsumableArray(quickSort(nums.filter(function (v) {\n    return desc ? v > n : v <= n;\n  }), desc)).concat([n], _toConsumableArray(quickSort(nums.filter(function (v) {\n    return !desc ? v > n : v <= n;\n  }), desc)));\n};",
          "example": "quickSort([4, 1, 3, 2]); // [1,2,3,4]\nquickSort([4, 1, 3, 2], true); // [4,3,2,1]"
        },
        "tags": []
      },
      "meta": {
        "archived": true,
        "hash": "5495d306c24323a8b16d5706180208f3828b043eb07d19014774cfe7f8c5b00e"
      }
    },
    {
      "id": "README",
      "type": "snippet",
      "attributes": {
        "fileName": "README.md",
        "text": "Converts a JSON object to a date.\n\nUse `Date()`, to convert dates in JSON format to readable format (`dd/mm/yyyy`).",
        "codeBlocks": {
          "es6": "const JSONToDate = arr => {\n  const dt = new Date(parseInt(arr.toString().substr(6)));\n  return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`;\n};",
          "es5": "var JSONToDate = function JSONToDate(arr) {\n  var dt = new Date(parseInt(arr.toString().substr(6)));\n  return \"\".concat(dt.getDate(), \"/\").concat(dt.getMonth() + 1, \"/\").concat(dt.getFullYear());\n};",
          "example": "JSONToDate(/Date(1489525200000)/); // \"14/3/2017\""
        },
        "tags": []
      },
      "meta": {
        "archived": true,
        "hash": "7af37e0984b5c8bd78d6b224cdc155f8c2bf687e38b5cfee27f32c7c29dcddf5"
      }
    },
    {
      "id": "removeVowels",
      "type": "snippet",
      "attributes": {
        "fileName": "removeVowels.md",
        "text": "Returns all the vowels in a `str` replaced by `repl`.\n\nUse `String.prototype.replace()` with a regexp to replace all vowels in `str`.\nOmot `repl` to use a default value of `''`.",
        "codeBlocks": {
          "es6": "const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi, repl);",
          "es5": "var removeVowels = function removeVowels(str) {\n  var repl = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';\n  return str.replace(/[aeiou]/gi, repl);\n};",
          "example": "removeVowels(\"foobAr\"); // \"fbr\"\nremoveVowels(\"foobAr\",\"*\"); // \"f**b*r\""
        },
        "tags": []
      },
      "meta": {
        "archived": true,
        "hash": "62de33e07d133fc89d71a5091f3f350c007fc60a681e1211ee192b2fb58a2b82"
      }
    },
    {
      "id": "solveRPN",
      "type": "snippet",
      "attributes": {
        "fileName": "solveRPN.md",
        "text": "Solves the given mathematical expression in [reverse polish notation](https://en.wikipedia.org/wiki/Reverse_Polish_notation).\nThrows appropriate errors if there are unrecognized symbols or the expression is wrong. The valid operators are :- `+`,`-`,`*`,`/`,`^`,`**` (`^`&`**` are the exponential symbols and are same). This snippet does not supports any unary operators.\n\nUse a dictionary, `OPERATORS` to specify each operator's matching mathematical operation.\nUse `String.prototype.replace()` with a regular expression to replace `^` with `**`, `String.prototype.split()` to tokenize the string and `Array.prototype.filter()` to remove empty tokens.\nUse `Array.prototype.forEach()` to parse each `symbol`, evaluate it as a numeric value or operator and solve the mathematical expression.\nNumeric values are converted to floating point numbers and pushed to a `stack`, while operators are evaluated using the `OPERATORS` dictionary and pop elements from the `stack` to apply operations.",
        "codeBlocks": {
          "es6": "const solveRPN = rpn => {\n  const OPERATORS = {\n    '*': (a, b) => a * b,\n    '+': (a, b) => a + b,\n    '-': (a, b) => a - b,\n    '/': (a, b) => a / b,\n    '**': (a, b) => a ** b\n  };\n  const [stack, solve] = [\n    [],\n    rpn\n      .replace(/\\^/g, '**')\n      .split(/\\s+/g)\n      .filter(el => !/\\s+/.test(el) && el !== '')\n  ];\n  solve.forEach(symbol => {\n    if (!isNaN(parseFloat(symbol)) && isFinite(symbol)) {\n      stack.push(symbol);\n    } else if (Object.keys(OPERATORS).includes(symbol)) {\n      const [a, b] = [stack.pop(), stack.pop()];\n      stack.push(OPERATORS[symbol](parseFloat(b), parseFloat(a)));\n    } else {\n      throw `${symbol} is not a recognized symbol`;\n    }\n  });\n  if (stack.length === 1) return stack.pop();\n  else throw `${rpn} is not a proper RPN. Please check it and try again`;\n};",
          "es5": "var solveRPN = function solveRPN(rpn) {\n  var OPERATORS = {\n    '*': function _(a, b) {\n      return a * b;\n    },\n    '+': function _(a, b) {\n      return a + b;\n    },\n    '-': function _(a, b) {\n      return a - b;\n    },\n    '/': function _(a, b) {\n      return a / b;\n    },\n    '**': function _(a, b) {\n      return Math.pow(a, b);\n    }\n  };\n  var _ref = [[], rpn.replace(/\\^/g, '**').split(/\\s+/g).filter(function (el) {\n    return !/\\s+/.test(el) && el !== '';\n  })],\n      stack = _ref[0],\n      solve = _ref[1];\n  solve.forEach(function (symbol) {\n    if (!isNaN(parseFloat(symbol)) && isFinite(symbol)) {\n      stack.push(symbol);\n    } else if (Object.keys(OPERATORS).includes(symbol)) {\n      var _ref2 = [stack.pop(), stack.pop()],\n          a = _ref2[0],\n          b = _ref2[1];\n      stack.push(OPERATORS[symbol](parseFloat(b), parseFloat(a)));\n    } else {\n      throw \"\".concat(symbol, \" is not a recognized symbol\");\n    }\n  });\n  if (stack.length === 1) return stack.pop();else throw \"\".concat(rpn, \" is not a proper RPN. Please check it and try again\");\n};",
          "example": "solveRPN('15 7 1 1 + - / 3 * 2 1 1 + + -'); // 5\nsolveRPN('2 3 ^'); // 8"
        },
        "tags": []
      },
      "meta": {
        "archived": true,
        "hash": "89dc909e8dc0dfbfcafc60e99a3b895370fc20d1930b21717a8125db3777d6f1"
      }
    },
    {
      "id": "speechSynthesis",
      "type": "snippet",
      "attributes": {
        "fileName": "speechSynthesis.md",
        "text": "Performs speech synthesis (experimental).\n\nUse `SpeechSynthesisUtterance.voice` and `window.speechSynthesis.getVoices()` to convert a message to speech.\nUse `window.speechSynthesis.speak()` to play the message.\n\nLearn more about the [SpeechSynthesisUtterance interface of the Web Speech API](https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisUtterance).",
        "codeBlocks": {
          "es6": "const speechSynthesis = message => {\n  const msg = new SpeechSynthesisUtterance(message);\n  msg.voice = window.speechSynthesis.getVoices()[0];\n  window.speechSynthesis.speak(msg);\n};",
          "es5": "var speechSynthesis = function speechSynthesis(message) {\n  var msg = new SpeechSynthesisUtterance(message);\n  msg.voice = window.speechSynthesis.getVoices()[0];\n  window.speechSynthesis.speak(msg);\n};",
          "example": "speechSynthesis('Hello, World'); // // plays the message"
        },
        "tags": []
      },
      "meta": {
        "archived": true,
        "hash": "21409f3b5ea7aaa9ad0041508b14c64dcaeff234121aca148e14fe26cf8b5f93"
      }
    },
    {
      "id": "squareSum",
      "type": "snippet",
      "attributes": {
        "fileName": "squareSum.md",
        "text": "Squares each number in an array and then sums the results together.\n\nUse `Array.prototype.reduce()` in combination with `Math.pow()` to iterate over numbers and sum their squares into an accumulator.",
        "codeBlocks": {
          "es6": "const squareSum = (...args) => args.reduce((squareSum, number) => squareSum + Math.pow(number, 2), 0);",
          "es5": "var squareSum = function squareSum() {\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.reduce(function (squareSum, number) {\n    return squareSum + Math.pow(number, 2);\n  }, 0);\n};",
          "example": "squareSum(1, 2, 2); // 9"
        },
        "tags": []
      },
      "meta": {
        "archived": true,
        "hash": "5d7d8623e504377f07ac9827eaec17c309a37aefc2346f0dd0a889f4f716f499"
      }
    }
  ],
  "meta": {
    "specification": "http://jsonapi.org/format/"
  }
}