[
  {
    "path": ".gitignore",
    "content": ".DS_Store\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2020 phuoc-ng\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE."
  },
  {
    "path": "README.md",
    "content": "# Favorite single line of code\n\nWhat's your favorite JavaScript single LOC (line of code)? Let me know!\n\n## Contributing\n\nPull requests are welcomed. To submit your favorite JavaScript single line of code, please create a markdown file, and put it in the [contents](contents) folder.\n\n## About\n\nThis project is developed by _Nguyen Huu Phuoc_. I love building products and sharing knowledge.\n\nBe my friend on\n\n-   [Twitter](https://twitter.com/_phuocng)\n-   [Github](https://github.com/phuocng)\n"
  },
  {
    "path": "contents/add-am-pm-suffix-to-an-hour.mdx",
    "content": "---\ncategory: Date Time\ncreated: '2021-02-20'\ntitle: Add AM PM suffix to an hour\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js suffixAmPm.js\n// `h` is an hour number between 0 and 23\nconst suffixAmPm = (h) => `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? 'am' : 'pm'}`;\n```\n\n**TypeScript version**\n\n```ts suffixAmPm.ts\nconst suffixAmPm = (h: number): string => `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? 'am' : 'pm'}`;\n```\n\n**Examples**\n\n```js examples.js\nsuffixAmPm(0); // '12am'\nsuffixAmPm(5); // '5am'\nsuffixAmPm(12); // '12pm'\nsuffixAmPm(15); // '3pm'\nsuffixAmPm(23); // '11pm'\n```\n"
  },
  {
    "path": "contents/add-an-ordinal-suffix-to-a-number.mdx",
    "content": "---\ncategory: Number\ncreated: '2020-05-16'\ntitle: Add an ordinal suffix to a number\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js addOrdinal.js\n// `n` is a position number\nconst addOrdinal = (n) => `${n}${['st', 'nd', 'rd'][((((n + 90) % 100) - 10) % 10) - 1] || 'th'}`;\n```\n\n**TypeScript version**\n\n```ts addOrdinal.ts\nconst addOrdinal = (n: number): string => `${n}${['st', 'nd', 'rd'][((((n + 90) % 100) - 10) % 10) - 1] || 'th'}`;\n```\n\n**Examples**\n\n```js examples.js\naddOrdinal(1); // '1st'\naddOrdinal(2); // '2nd'\naddOrdinal(3); // '3rd'\naddOrdinal(11); // '11th'\naddOrdinal(12); // '13th'\naddOrdinal(13); // '13th'\n```\n"
  },
  {
    "path": "contents/box-handler.mdx",
    "content": "---\ncategory: Function\ncontributors:\n    - Valeriy Arbachakov\ncreated: '2020-07-15'\ntitle: Box handler\nupdated: '2020-08-18'\n---\n\n**JavaScript version**\n\n```js boxHandler.js\nconst boxHandler = (x) => ({ next: (f) => boxHandler(f(x)), done: (f) => f(x) });\n```\n\n**Examples**\n\n```js examples.js\n// First example\nconst getPercentNumber = (str) =>\n    boxHandler(str)\n        .next((str) => str.replace(/\\%/, ''))\n        .next((str) => parseFloat(str))\n        .done((res) => res * 0.01);\n\ngetPercentNumber('50%'); // 0.5\n\n// Second example\nconst getMoney = (price) => Number.parseFloat(price.replace(/\\$/, ''));\nconst getPercent = (percent) => Number.parseFloat(percent.replace(/\\%/)) * 0.01;\n\nconst getDiscountPrice = (price, discount) =>\n    boxHandler(getMoney(price))\n        .done((cents) => boxHandler(getPercent(discount)).next((save) => cents - cents * save))\n        .done((res) => res);\n\ngetDiscountPrice('$6.00', '20%'); // 4.8\n```\n"
  },
  {
    "path": "contents/calculate-fibonacci-numbers.mdx",
    "content": "---\ncategory: Number\ncreated: '2020-05-16'\ntitle: Calculate Fibonacci numbers\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js fibo.js\nconst fibo = (n, memo = {}) => memo[n] || (n <= 2 ? 1 : (memo[n] = fibo(n - 1, memo) + fibo(n - 2, memo)));\n```\n\n**TypeScript version**\n\n```ts fibo.ts\nconst fibo = (n: number, memo: Record<string, number> = {}): number =>\n    memo[n] || (n <= 2 ? 1 : (memo[n] = fibo(n - 1, memo) + fibo(n - 2, memo)));\n```\n\n**Examples**\n\n```js examples.js\nfibo(1); // 1\nfibo(2); // 1\nfibo(3); // 2\nfibo(4); // 3\nfibo(5); // 5\nfibo(6); // 8\n```\n"
  },
  {
    "path": "contents/calculate-the-angle-of-a-line-defined-by-two-points.mdx",
    "content": "---\ncategory: Math\ncreated: '2021-04-08'\ntitle: Calculate the angle of a line defined by two points\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js radiansAngle.js\n// In radians\nconst radiansAngle = (p1, p2) => Math.atan2(p2.y - p1.y, p2.x - p1.x);\n\n// In degrees\nconst degreesAngle = (p1, p2) => (Math.atan2(p2.y - p1.y, p2.x - p1.x) * 180) / Math.PI;\n```\n\n**TypeScript version**\n\n```ts radiansAngle.ts\ninterface Point {\n    x: number;\n    y: number;\n}\n\nconst radiansAngle = (p1: Point, p2: Point): number => Math.atan2(p2.y - p1.y, p2.x - p1.x);\n\nconst degreesAngle = (p1: Point, p2: Point): number => (Math.atan2(p2.y - p1.y, p2.x - p1.x) * 180) / Math.PI;\n```\n"
  },
  {
    "path": "contents/calculate-the-average-of-arguments.mdx",
    "content": "---\ncategory: Number\ncreated: '2020-05-05'\ntitle: Calculate the average of arguments\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js average.js\nconst average = (...args) => args.reduce((a, b) => a + b) / args.length;\n```\n\n**TypeScript version**\n\n```ts average.ts\nconst average = (...args: number[]): number => args.reduce((a, b) => a + b) / args.length;\n```\n\n**Examples**\n\n```js examples.js\naverage(1, 2, 3, 4); // 2.5\n```\n"
  },
  {
    "path": "contents/calculate-the-distance-between-two-points.mdx",
    "content": "---\ncategory: Math\ncreated: '2021-04-05'\ntitle: Calculate the distance between two points\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js distance.js\nconst distance = (p1, p2) => Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));\n```\n\n**TypeScript version**\n\n```js distance.ts\ninterface Point {\n    x: number;\n    y: number;\n}\n\nconst distance = (p1: Point, p2: Point): number => Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));\n```\n"
  },
  {
    "path": "contents/calculate-the-distance-to-the-bottom-of-a-page.mdx",
    "content": "---\ncategory: DOM\ncreated: '2023-08-23'\ndescription: one-liner function to calculate how far you are from the bottom of the page\nopenGraphCover: /og/1-loc/distance-to-bottom.png\ntitle: Calculate the distance to the bottom of a page\n---\n\nThe following snippet calculates how far you are from the bottom of the page.\n\nHere's how it works: it takes the total height of the page (`document.body.scrollHeight`), subtracts the height of your screen (`window.innerHeight`), and then subtracts how far down you've already scrolled (`window.scrollY`).\n\nThe result is the distance from your current position to the bottom of the page.\n\n**JavaScript version**\n\n```js distanceToBottom.js\nconst distanceToBottom = document.body.scrollHeight - window.innerHeight - window.scrollY;\n```\n\n**TypeScript version**\n\n```js distanceToBottom.ts\nconst distanceToBottom: number = document.body.scrollHeight - window.innerHeight - window.scrollY;\n```\n"
  },
  {
    "path": "contents/calculate-the-division-of-arguments.mdx",
    "content": "---\ncategory: Number\ncreated: '2020-05-05'\ntitle: Calculate the division of arguments\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js division.js\nconst division = (...args) => args.reduce((a, b) => a / b);\n```\n\n**TypeScript version**\n\n```ts division.ts\nconst division = (...args: number): number => args.reduce((a, b) => a / b);\n```\n\n**Examples**\n\n```js examples.js\ndivision(1, 2, 3, 4); // 0.04166666666666666\n```\n"
  },
  {
    "path": "contents/calculate-the-factorial-of-a-number.mdx",
    "content": "---\ncategory: Number\ncreated: '2020-05-19'\ntitle: Calculate the factorial of a number\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js factorial.js\nconst factorial = (n) => (n <= 1 ? 1 : n * factorial(n - 1));\n```\n\n**TypeScript version**\n\n```ts factorial.ts\nconst factorial = (n: number): number => (n <= 1 ? 1 : n * factorial(n - 1));\n```\n\n**Examples**\n\n```js examples.js\nfactorial(2); // 2\nfactorial(3); // 6\nfactorial(4); // 24\nfactorial(5); // 120\nfactorial(6); // 720\n```\n"
  },
  {
    "path": "contents/calculate-the-linear-interpolation-between-two-numbers.mdx",
    "content": "---\ncategory: Math\ncreated: '2021-05-24'\ntitle: Calculate the linear interpolation between two numbers\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js lerp.js\nconst lerp = (a, b, amount) => (1 - amount) * a + amount * b;\n```\n\n**TypeScript version**\n\n```ts lerp.ts\nconst lerp = (a: number, b: number, amount: number): number => (1 - amount) * a + amount * b;\n```\n\n## See also\n\n-   [Linear scale of a number between two ranges](https://phuoc.ng/collection/1-loc/linear-scale-of-a-number-between-two-ranges/)\n-   [Normalize the ratio of a number in a range](https://phuoc.ng/collection/1-loc/normalize-the-ratio-of-a-number-in-a-range/)\n"
  },
  {
    "path": "contents/calculate-the-midpoint-between-two-points.mdx",
    "content": "---\ncategory: Math\ncreated: '2021-04-10'\nopenGraphCover: /og/1-loc/calculate-midpoint-two-points.png\ntitle: Calculate the midpoint between two points\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js midpoint.js\nconst midpoint = (p1, p2) => [(p1.x + p2.x) / 2, (p1.y + p2.y) / 2];\n```\n\n**TypeScript version**\n\n```ts midpoint.ts\ninterface Point {\n    x: number;\n    y: number;\n}\n\nconst midpoint = (p1: Point, p2: Point): number[] => [(p1.x + p2.x) / 2, (p1.y + p2.y) / 2];\n```\n\n## See also\n\n-   [Calculate the midpoint of a given range](https://phuoc.ng/collection/1-loc/calculate-the-midpoint-of-a-given-range/)\n"
  },
  {
    "path": "contents/calculate-the-midpoint-of-a-given-range.mdx",
    "content": "---\ncategory: Math\ncreated: '2023-12-08'\nopenGraphCover: /og/1-loc/calculate-midpoint-given-range.png\ntitle: Calculate the midpoint of a given range\n---\n\n**JavaScript version**\n\n```js midpoint.js\nconst midpoint = ([from, to]) => (from + to) / 2;\n```\n\n**TypeScript version**\n\n```ts midpoint.ts\nconst midpoint = ([from, to]: [number, number]): number => (from + to) / 2;\n```\n\n## See also\n\n-   [Calculate the midpoint between two points](https://phuoc.ng/collection/1-loc/calculate-the-midpoint-between-two-points/)\n"
  },
  {
    "path": "contents/calculate-the-mod-of-collection-index.mdx",
    "content": "---\ncategory: Number\ncontributors:\n    - marcobiedermann\ncreated: '2020-05-08'\ntitle: Calculate the mod of collection index\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js mod.js\nconst mod = (a, b) => ((a % b) + b) % b;\n```\n\n**TypeScript version**\n\n```ts mod.ts\nconst mod = (a: number, b: number): number => ((a % b) + b) % b;\n```\n\n**Examples**\n\n```js examples.js\nmod(-1, 5); // 4\nmod(3, 5); // 3\nmod(6, 5); // 1\n```\n"
  },
  {
    "path": "contents/calculate-the-number-of-difference-days-between-two-dates.mdx",
    "content": "---\ncategory: Date Time\ncreated: '2020-04-19'\ntitle: Calculate the number of difference days between two dates\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js diffDays.js\nconst diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));\n```\n\n**TypeScript version**\n\n```ts diffDays.ts\nconst diffDays = (date: Date, otherDate: Date): number =>\n    Math.ceil(Math.abs(date.valueOf() - otherDate.valueOf()) / (1000 * 60 * 60 * 24));\n```\n\n**Examples**\n\n```js examples.js\ndiffDays(new Date('2014-12-19'), new Date('2020-01-01')); // 1839\n```\n"
  },
  {
    "path": "contents/calculate-the-number-of-months-between-two-dates.mdx",
    "content": "---\ncategory: Date Time\ncontributors:\n    - kwaimind\ncreated: '2020-07-27'\ntitle: Calculate the number of months between two dates\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js monthDiff.js\nconst monthDiff = (startDate, endDate) =>\n    Math.max(0, (endDate.getFullYear() - startDate.getFullYear()) * 12 - startDate.getMonth() + endDate.getMonth());\n```\n\n**TypeScript version**\n\n```ts monthDiff.ts\nconst monthDiff = (startDate: Date, endDate: Date): number =>\n    Math.max(0, (endDate.getFullYear() - startDate.getFullYear()) * 12 - startDate.getMonth() + endDate.getMonth());\n```\n\n**Example**\n\n```js example.js\nmonthDiff(new Date('2020-01-01'), new Date('2021-01-01')); // 12\n```\n"
  },
  {
    "path": "contents/calculate-the-remainder-of-division-of-arguments.mdx",
    "content": "---\ncategory: Number\ncreated: '2020-05-05'\ntitle: Calculate the remainder of division of arguments\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js remainder.js\nconst remainder = (...args) => args.reduce((a, b) => a % b);\n```\n\n**TypeScript version**\n\n```ts remainder.ts\nconst remainder = (...args: number[]): number => args.reduce((a, b) => a % b);\n```\n\n**Examples**\n\n```js examples.js\nremainder(1, 2, 3, 4); // 1\n```\n"
  },
  {
    "path": "contents/calculate-the-sum-of-arguments.mdx",
    "content": "---\ncategory: Number\ncreated: '2020-05-05'\ntitle: Calculate the sum of arguments\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js sum.js\nconst sum = (...args) => args.reduce((a, b) => a + b);\n```\n\n**TypeScript version**\n\n```ts sum.ts\nconst sum = (...args: number[]): number => args.reduce((a, b) => a + b);\n```\n\n**Examples**\n\n```js examples.js\nsum(1, 2, 3, 4); // 10\n```\n"
  },
  {
    "path": "contents/capitalize-a-string.mdx",
    "content": "---\ncategory: String\ncontributors:\n    - Edmon Narmetov\n    - fahimfaisaal\ncreated: '2023-04-11'\ntitle: Capitalize a string\nupdated: '2020-04-19'\n---\n\n**JavaScript version**\n\n```js capitalize.js\nconst capitalize = (str) => `${str.charAt(0).toUpperCase()}${str.slice(1)}`;\n\n// Or\nconst capitalize = ([first, ...rest]) => `${first.toUpperCase()}${rest.join('')}`;\n\n// Or\nconst capitalize = (str) => str.replace(/^([a-z])/, (first) => first.toUpperCase());\n```\n\n**TypeScript version**\n\n```ts capitalize.ts\nconst capitalize = (str: string): string => `${str.charAt(0).toUpperCase()}${str.slice(1)}`;\n\n// Or\nconst capitalize = ([first, ...rest]: string): string => `${first.toUpperCase()}${rest.join('')}`;\n\n// Or\nconst capitalize = (str: string): string => str.replace(/^([a-z])/, (first) => first.toUpperCase());\n```\n\n**Examples**\n\n```js examples.js\ncapitalize('hello world'); // 'Hello world'\n```\n"
  },
  {
    "path": "contents/cast-a-value-as-an-array.mdx",
    "content": "---\ncategory: Array\ntitle: Cast a value as an array\ncreated: '2021-04-04'\nupdated: '2021-10-22'\n---\n\n**JavaScript version**\n\n```js castArray.js\nconst castArray = (value) => (Array.isArray(value) ? value : [value]);\n```\n\n**TypeScript version**\n\n```ts castArray.ts\nconst castArray = <T,_>(value: T | T[]): T[] => (Array.isArray(value) ? value : [value]);\n```\n\n**Examples**\n\n```js examples.js\ncastArray(1); // [1]\ncastArray([1, 2, 3]); // [1, 2, 3]\n```\n"
  },
  {
    "path": "contents/check-if-a-character-is-a-digit.mdx",
    "content": "---\ncategory: Validator\ncreated: '2021-10-22'\ntitle: Check if a character is a digit\n---\n\n**JavaScript version**\n\n```js isDigit.js\nconst isDigit = (char) => char < 10;\n\n// Or\nconst isDigit = (char) => char.length === 1 && c >= '0' && c <= '9';\n\n// Or\nconst isDigit = (char) => Boolean([true, true, true, true, true, true, true, true, true, true][char]);\n```\n\n**TypeScript version**\n\n```ts isDigit.ts\nconst isDigit = (char: string): boolean => char < 10;\n\n// Or\nconst isDigit = (char: string): boolean => char.length === 1 && c >= '0' && c <= '9';\n\n// Or\nconst isDigit = (char: string): boolean => Boolean([true, true, true, true, true, true, true, true, true, true][char]);\n```\n\n**Examples**\n\n```js examples.js\nisDigit('a'); // false\nisDigit('abc'); // false\nisDigit(10); // false\nisDigit('10'); // false\n\nisDigit('2'); // true\nisDigit(2); // true\n```\n"
  },
  {
    "path": "contents/check-if-a-date-is-a-weekday.mdx",
    "content": "---\ncategory: Validator\ncreated: '2021-02-25'\ntitle: Check if a date is a weekday\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isWeekday.js\n// `date` is a Date object\nconst isWeekday = (date = new Date()) => date.getDay() % 6 !== 0;\n```\n\n**TypeScript version**\n\n```ts isWeekday.ts\nconst isWeekday = (date = new Date()): boolean => date.getDay() % 6 !== 0;\n```\n"
  },
  {
    "path": "contents/check-if-a-date-is-a-weekend.mdx",
    "content": "---\ncategory: Validator\ncreated: '2021-02-25'\ntitle: Check if a date is a weekend\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isWeekend.js\n// `date` is a Date object\nconst isWeekend = (date = new Date()) => date.getDay() % 6 === 0;\n```\n\n**TypeScript version**\n\n```ts isWeekend.ts\nconst isWeekend = (date = new Date()): boolean => date.getDay() % 6 === 0;\n```\n"
  },
  {
    "path": "contents/check-if-a-date-is-between-two-dates.mdx",
    "content": "---\ncategory: Validator\ncreated: '2020-04-19'\ntitle: Check if a date is between two dates\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isBetween.js\n// `min`, `max` and `date` are `Date` instances\nconst isBetween = (date, min, max) => date.getTime() >= min.getTime() && date.getTime() <= max.getTime();\n```\n\n**TypeScript version**\n\n```ts isBetween.ts\nconst isBetween = (date: Date, min: Date, max: Date): boolean =>\n    date.getTime() >= min.getTime() && date.getTime() <= max.getTime();\n```\n"
  },
  {
    "path": "contents/check-if-a-date-is-today.mdx",
    "content": "---\ncategory: Validator\ncreated: '2020-05-05'\ntitle: Check if a date is today\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isToday.js\n// `date` is a Date object\nconst isToday = (date) => date.toISOString().slice(0, 10) === new Date().toISOString().slice(0, 10);\n```\n\n**TypeScript version**\n\n```ts isToday.ts\nconst isToday = (date: Date): boolean => date.toISOString().slice(0, 10) === new Date().toISOString().slice(0, 10);\n```\n"
  },
  {
    "path": "contents/check-if-a-date-occurs-in-the-current-year.mdx",
    "content": "---\ncategory: Validator\ncreated: '2021-04-13'\ntitle: Check if a date occurs in the current year\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isCurrentYear.js\n// `date` is a Date object\nconst isCurrentYear = (date) => date.getUTCFullYear() === new Date().getUTCFullYear();\n```\n\n**TypeScript version**\n\n```ts isCurrentYear.ts\nconst isCurrentYear = (date: Date): boolean => date.getUTCFullYear() === new Date().getUTCFullYear();\n```\n"
  },
  {
    "path": "contents/check-if-a-flat-array-has-duplicate-values.mdx",
    "content": "---\ncategory: Validator\ncreated: '2021-02-25'\ntitle: Check if a flat array has duplicate values\nupdated: '2022-01-26'\n---\n\n**JavaScript version**\n\n```js hasDuplicateValues.js\nconst hasDuplicateValues = (arr) => new Set(arr).size !== arr.length;\n\n// Or\nconst hasDuplicateValues = (arr) => arr.some((item, index, arr) => arr.indexOf(item) !== index);\n```\n\n**TypeScript version**\n\n```ts hasDuplicateValues.ts\nconst hasDuplicateValues = <T,_>(arr: T[]): boolean => new Set(arr).size !== arr.length;\n\n// Or\nconst hasDuplicateValues = <T,_>(arr: T[]): boolean => arr.some((item, index, arr) => arr.indexOf(item) !== index);\n```\n\n**Examples**\n\n```js examples.js\nhasDuplicateValues(['h', 'e', 'l', 'l', 'o']); // true\nhasDuplicateValues(['w', 'o', 'r', 'd']); // false\n```\n"
  },
  {
    "path": "contents/check-if-a-given-dom-rect-is-contained-within-another-dom-rect.mdx",
    "content": "---\ncategory: DOM\ncreated: '2023-12-11'\nopenGraphCover: /og/1-loc/check-given-dom-rect-contained-within-another-dom-rect.png\ntitle: Check if a given DOMRect is contained within another DOMRect\n---\n\n**JavaScript version**\n\n```js isContained.js\nconst isContained = (target, container) => (\n    target.left >= container.left &&\n    target.left + target.width <= container.left + container.width &&\n    target.top >= container.top &&\n    target.top + target.height <= container.top + container.height\n);\n```\n\n**TypeScript version**\n\n```ts isContained.ts\nconst isContained = (target: DOMRect, container: DOMRect): boolean => (\n    target.left >= container.left &&\n    target.left + target.width <= container.left + container.width &&\n    target.top >= container.top &&\n    target.top + target.height <= container.top + container.height\n);\n```\n\n**Example**\n\n```js example.js\nconst target = new DOMRect(10, 10, 20, 20);\nconst container = new DOMRect(0, 0, 40, 40);\nisContained(target, container);     // true\n```\n\n## See also\n\n-   [Check if two DOMRects intersect](https://phuoc.ng/collection/1-loc/check-if-two-dom-rects-intersect/)\n"
  },
  {
    "path": "contents/check-if-a-given-integer-is-a-prime-number.mdx",
    "content": "---\ncategory: Validator\ncreated: '2020-04-19'\ntitle: Check if a given integer is a prime number\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isPrime.js\nconst isPrime = (n) =>\n    n > 1 &&\n    Array(Math.floor(Math.sqrt(n)) - 1)\n        .fill(0)\n        .map((_, i) => i + 2)\n        .every((i) => n % i !== 0);\n```\n\n**TypeScript version**\n\n```ts isPrime.ts\nconst isPrime = (n: number): boolean =>\n    n > 1 &&\n    Array(Math.floor(Math.sqrt(n)) - 1)\n        .fill(0)\n        .map((_, i) => i + 2)\n        .every((i) => n % i !== 0);\n```\n"
  },
  {
    "path": "contents/check-if-a-number-is-a-power-of-2.mdx",
    "content": "---\ncategory: Validator\ncreated: '2020-04-19'\ntitle: Check if a number is a power of 2\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isPowerOfTwo.js\nconst isPowerOfTwo = (n) => (n & (n - 1)) === 0;\n```\n\n**TypeScript version**\n\n```ts isPowerOfTwo.ts\nconst isPowerOfTwo = (n: number): boolean => (n & (n - 1)) === 0;\n```\n\n**Examples**\n\n```js examples.js\nisPowerOfTwo(256); // true\nisPowerOfTwo(129); // false\n```\n"
  },
  {
    "path": "contents/check-if-a-number-is-even.mdx",
    "content": "---\ncategory: Validator\ncontributors:\n    - chety\n    - ietienam\n    - Vadim-Moshev\n    - marcobiedermann\ncreated: '2020-05-06'\ntitle: Check if a number is even\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isEven.js\nconst isEven = (n) => n % 2 === 0;\n\n// Or\nconst isEven = (n) => (n & 1) === 0;\n\n// Or\nconst isEven = (n) => !(n & 1);\n\n// Or\nconst isEven = (n) => Number.isInteger(n / 2);\n```\n\n**TypeScript version**\n\n```ts isEven.ts\nconst isEven = (n: number): boolean => n % 2 === 0;\n\n// Or\nconst isEven = (n: number): boolean => (n & 1) === 0;\n\n// Or\nconst isEven = (n: number): boolean => !(n & 1);\n\n// Or\nconst isEven = (n: number): boolean => Number.isInteger(n / 2);\n```\n\n**Examples**\n\n```js examples.js\nisEven(1); // false\nisEven(2); // true\n```\n"
  },
  {
    "path": "contents/check-if-a-number-is-in-a-given-range.mdx",
    "content": "---\ncategory: Validator\ncreated: '2020-06-04'\ntitle: Check if a number is in a given range\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js inRange.js\nconst inRange = (num, a, b, threshold = 0) => Math.min(a, b) - threshold <= num && num <= Math.max(a, b) + threshold;\n```\n\n**TypeScript version**\n\n```ts inRange.ts\nconst inRange = (num: number, a: number, b: number, threshold: number = 0): boolean =>\n    Math.min(a, b) - threshold <= num && num <= Math.max(a, b) + threshold;\n```\n\n**Examples**\n\n```js examples.js\ninRange(10, 5, 15); // true\ninRange(10, 5, 6); // false\ninRange(10, 15, 5); // true\ninRange(-10, -5, -15); // true\n```\n"
  },
  {
    "path": "contents/check-if-a-number-is-negative.mdx",
    "content": "---\ncategory: Validator\ncontributors:\n    - sadirde\n    - tugsanunlu\ncreated: '2020-05-07'\ntitle: Check if a number is negative\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isNegative.js\nconst isNegative = (n) => Math.sign(n) === -1;\n\n// Or\nconst isNegative = (n) => n < 0;\n```\n\n**TypeScript version**\n\n```ts isNegative.ts\nconst isNegative = (n: number): boolean => Math.sign(n) === -1;\n\n// Or\nconst isNegative = (n: number): boolean => n < 0;\n```\n\n**Examples**\n\n```js examples.js\nisNegative(-3); // true\nisNegative(8); // false\n```\n"
  },
  {
    "path": "contents/check-if-a-number-is-odd.mdx",
    "content": "---\ncategory: Validator\ncontributors:\n    - ietienam\n    - Namysh\n    - marcobiedermann\ncreated: '2020-05-06'\ntitle: Check if a number is odd\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isOdd.js\nconst isOdd = (n) => n % 2 !== 0;\n\n// Or\nconst isOdd = (n) => !!(n & 1);\n\n// Or\nconst isOdd = (n) => !Number.isInteger(n / 2);\n```\n\n**TypeScript version**\n\n```ts isOdd.ts\nconst isOdd = (n: number): boolean => n % 2 !== 0;\n\n// Or\nconst isOdd = (n: number): boolean => !!(n & 1);\n\n// Or\nconst isOdd = (n: number): boolean => !Number.isInteger(n / 2);\n```\n\n**Examples**\n\n```js examples.js\nisOdd(1); // true\nisOdd(2); // false\n```\n"
  },
  {
    "path": "contents/check-if-a-number-is-positive.mdx",
    "content": "---\ncategory: Validator\ncontributors:\n    - tugsanunlu\ncreated: '2020-05-07'\ntitle: Check if a number is positive\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isPositive.js\nconst isPositive = (n) => Math.sign(n) === 1;\n```\n\n**TypeScript version**\n\n```ts isPositive.ts\nconst isPositive = (n: number): boolean => Math.sign(n) === 1;\n```\n\n**Examples**\n\n```js examples.js\nisPositive(3); // true\nisPositive(-8); // false\n```\n"
  },
  {
    "path": "contents/check-if-a-path-is-relative.mdx",
    "content": "---\ncategory: String\ncreated: '2020-05-15'\ntitle: Check if a path is relative\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isRelative.js\nconst isRelative = (path) => !/^([a-z]+:)?[\\\\/]/i.test(path);\n```\n\n**TypeScript version**\n\n```ts isRelative.ts\nconst isRelative = (path: string): boolean => !/^([a-z]+:)?[\\\\/]/i.test(path);\n```\n\n**Examples**\n\n```js examples.js\nisRelative('/foo/bar/baz'); // false\nisRelative('C:\\\\foo\\\\bar\\\\baz'); // false\nisRelative('foo/bar/baz.txt'); // true\nisRelative('foo.md'); // true\n```\n"
  },
  {
    "path": "contents/check-if-a-point-is-inside-a-rectangle.mdx",
    "content": "---\ncategory: Math\ncreated: '2021-04-05'\ntitle: Check if a point is inside a rectangle\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isInside.js\nconst isInside = (point, rect) =>\n    point.x > rect.left && point.x < rect.right && point.y > rect.top && point.y < rect.bottom;\n```\n\n**TypeScript version**\n\n```ts isInside.ts\ninterface Point {\n    x: number;\n    y: number;\n}\n\ninterface Rect {\n    bottom: number;\n    left: number;\n    top: number;\n    right: number;\n}\n\nconst isInside = (point: Point, rect: Rect): boolean =>\n    point.x > rect.left && point.x < rect.right && point.y > rect.top && point.y < rect.bottom;\n```\n"
  },
  {
    "path": "contents/check-if-a-rectangle-contains-other-one.mdx",
    "content": "---\ncategory: Math\ncreated: '2021-04-08'\ntitle: Check if a rectangle contains other one\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js contains.js\n// Returns true if `a` contains `b`\n// (x1, y1) and (x2, y2) are top-left and bottom-right corners\nconst contains = (a, b) => a.x1 <= b.x1 && a.y1 <= b.y1 && a.x2 >= b.x2 && a.y2 >= b.y2;\n```\n\n**TypeScript version**\n\n```ts contains.ts\ninterface Rect {\n    x1: number;\n    x2: number;\n    y1: number;\n    y2: number;\n}\n\nconst contains = (a: Rect, b: Rect): boolean => a.x1 <= b.x1 && a.y1 <= b.y1 && a.x2 >= b.x2 && a.y2 >= b.y2;\n```\n"
  },
  {
    "path": "contents/check-if-a-rectangle-overlaps-other-one.mdx",
    "content": "---\ncategory: Math\ncreated: '2021-04-08'\ntitle: Check if a rectangle overlaps other one\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js overlaps.js\n// Returns true if `a` overlaps `b`\n// (x1, y1) and (x2, y2) are top-left and bottom-right corners\nconst overlaps = (a, b) => (a.x1 < b.x2 && b.x1 < a.x2) || (a.y1 < b.y2 && b.y1 < a.y2);\n```\n\n**TypeScript version**\n\n```ts overlaps.ts\ninterface Rect {\n    x1: number;\n    x2: number;\n    y1: number;\n    y2: number;\n}\n\nconst overlaps = (a: Rect, b: Rect): boolean => (a.x1 < b.x2 && b.x1 < a.x2) || (a.y1 < b.y2 && b.y1 < a.y2);\n```\n"
  },
  {
    "path": "contents/check-if-a-string-consists-of-a-repeated-character-sequence.mdx",
    "content": "---\ncategory: String\ncreated: '2021-04-21'\ntitle: Check if a string consists of a repeated character sequence\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js consistsRepeatedSubstring.js\nconst consistsRepeatedSubstring = (str) => `${str}${str}`.indexOf(str, 1) !== str.length;\n```\n\n**TypeScript version**\n\n```ts consistsRepeatedSubstring.ts\nconst consistsRepeatedSubstring = (str: string): boolean => `${str}${str}`.indexOf(str, 1) !== str.length;\n```\n\n**Examples**\n\n```js examples.js\nconsistsRepeatedSubstring('aa'); // true\nconsistsRepeatedSubstring('aaa'); // true\nconsistsRepeatedSubstring('ababab'); // true\nconsistsRepeatedSubstring('abc'); // false\n```\n"
  },
  {
    "path": "contents/check-if-a-string-contains-lower-case-characters.mdx",
    "content": "---\ncategory: Validator\ncreated: '2020-05-16'\ntitle: Check if a string contains lower case characters\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js containsLowerCase.js\nconst containsLowerCase = (str) => str !== str.toUpperCase();\n```\n\n**TypeScript version**\n\n```ts containsLowerCase.ts\nconst containsLowerCase = (str: string): boolean => str !== str.toUpperCase();\n```\n\n**Examples**\n\n```js examples.js\ncontainsLowerCase('Hello World'); // true\ncontainsLowerCase('HELLO WORLD'); // false\n```\n"
  },
  {
    "path": "contents/check-if-a-string-contains-only-ascii-characters.mdx",
    "content": "---\ncategory: Validator\ncreated: '2020-06-09'\ntitle: Check if a string contains only ASCII characters\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isAscii.js\nconst isAscii = (str) => /^[\\x00-\\x7F]+$/.test(str);\n```\n\n**TypeScript version**\n\n```ts isAscii.ts\nconst isAscii = (str: string): boolean => /^[\\x00-\\x7F]+$/.test(str);\n```\n"
  },
  {
    "path": "contents/check-if-a-string-contains-only-digits.mdx",
    "content": "---\ncategory: Validator\ncreated: '2020-05-09'\ntitle: Check if a string contains only digits\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isNumeric.js\nconst isNumeric = (str) => !/[^0-9]/.test(str);\n```\n\n**TypeScript version**\n\n```ts isNumeric.ts\nconst isNumeric = (str: string): boolean => !/[^0-9]/.test(str);\n```\n\n**Examples**\n\n```js examples.js\nisNumeric(2); // true\nisNumeric('23'); // true\nisNumeric('00123'); // true\n\nisNumeric('1.23'); // false\nisNumeric('-Infinity'); // false\nisNumeric('Infinity'); // false\nisNumeric('NaN'); // false\n```\n"
  },
  {
    "path": "contents/check-if-a-string-contains-only-letters-and-numbers.mdx",
    "content": "---\ncategory: Validator\ncreated: '2020-06-08'\ntitle: Check if a string contains only letters and numbers\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isAlphanumeric.js\nconst isAlphanumeric = (str) => /^[0-9A-Z]+$/i.test(str);\n```\n\n**TypeScript version**\n\n```ts isAlphanumeric.ts\nconst isAlphanumeric = (str: string): boolean => /^[0-9A-Z]+$/i.test(str);\n```\n\n**Examples**\n\n```js examples.js\nisAlphanumeric('helloworld'); // true\nisAlphanumeric('HelloWorld'); // true\nisAlphanumeric('hello world'); // false\nisAlphanumeric('hello123'); // true\nisAlphanumeric('hello 123'); // false\n```\n"
  },
  {
    "path": "contents/check-if-a-string-contains-only-letters.mdx",
    "content": "---\ncategory: Validator\ncreated: '2020-06-07'\ntitle: Check if a string contains only letters\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isAlpha.js\nconst isAlpha = (str) => /^[A-Z]+$/i.test(str);\n```\n\n**TypeScript version**\n\n```ts isAlpha.ts\nconst isAlpha = (str: string): boolean => /^[A-Z]+$/i.test(str);\n```\n\n**Examples**\n\n```js examples.js\nisAlpha('helloworld'); // true\nisAlpha('HelloWorld'); // true\nisAlpha('hello world'); // false\nisAlpha('0123456789'); // false\n```\n"
  },
  {
    "path": "contents/check-if-a-string-contains-upper-case-characters.mdx",
    "content": "---\ncategory: Validator\ncreated: '2020-05-16'\ntitle: Check if a string contains upper case characters\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js containsUpperCase.js\nconst containsUpperCase = (str) => str !== str.toLowerCase();\n```\n\n**TypeScript version**\n\n```ts containsUpperCase.ts\nconst containsUpperCase = (str: string): boolean => str !== str.toLowerCase();\n```\n\n**Examples**\n\n```js examples.js\ncontainsUpperCase('Hello World'); // true\ncontainsUpperCase('hello world'); // false\n```\n"
  },
  {
    "path": "contents/check-if-a-string-contains-whitespace.mdx",
    "content": "---\ncategory: Validator\ncreated: '2020-04-19'\ntitle: Check if a string contains whitespace\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js containsWhitespace.js\nconst containsWhitespace = (str) => (str) => /\\s/.test(str);\n```\n\n**TypeScript version**\n\n```ts containsWhitespace.ts\nconst containsWhitespace =\n    (str: string): boolean =>\n    (str) =>\n        /\\s/.test(str);\n```\n\n**Examples**\n\n```js examples.js\ncontainsWhitespace('hello world'); // true\n```\n"
  },
  {
    "path": "contents/check-if-a-string-is-a-hexadecimal-color.mdx",
    "content": "---\ncategory: Validator\ncreated: '2020-06-09'\ntitle: Check if a string is a hexadecimal color\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isHexColor.js\nconst isHexColor = (color) => /^#([0-9A-F]{3}|[0-9A-F]{4}|[0-9A-F]{6}|[0-9A-F]{8})$/i.test(color);\n```\n\n**TypeScript version**\n\n```ts isHexColor.ts\nconst isHexColor = (color: string): boolean => /^#([0-9A-F]{3}|[0-9A-F]{4}|[0-9A-F]{6}|[0-9A-F]{8})$/i.test(color);\n```\n\n**Examples**\n\n```js examples.js\nisHexColor('#012'); // true\nisHexColor('#A1B2C3'); // true\nisHexColor('012'); // false\nisHexColor('#GHIJKL'); // false\n```\n"
  },
  {
    "path": "contents/check-if-a-string-is-a-hexadecimal-number.mdx",
    "content": "---\ncategory: Validator\ncreated: '2020-06-10'\ntitle: Check if a string is a hexadecimal number\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isHexadecimal.js\nconst isHexadecimal = (str) => /^[A-F0-9]+$/i.test(str);\n\n// Or\nconst isHexadecimal = (str) => str.split('').every((c) => '0123456789ABCDEFabcdef'.indexOf(c) !== -1);\n```\n\n**TypeScript version**\n\n```ts isHexadecimal.ts\nconst isHexadecimal = (str: string): boolean => /^[A-F0-9]+$/i.test(str);\n\n// Or\nconst isHexadecimal = (str: string): boolean => str.split('').every((c) => '0123456789ABCDEFabcdef'.indexOf(c) !== -1);\n```\n\n**Examples**\n\n```js examples.js\nisHexadecimal('123'); // true\nisHexadecimal('A1B2C3'); // true\nisHexadecimal('#123'); // false\n```\n"
  },
  {
    "path": "contents/check-if-a-string-is-a-mongo-db-object-id.mdx",
    "content": "---\ncategory: Validator\ncreated: '2021-04-10'\ntitle: Check if a string is a MongoDB ObjectId\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isMongoId.js\nconst isMongoId = (str) => str.length === 24 && /^[A-F0-9]+$/i.test(str);\n\n// Or\nconst isMongoId = (str) => str.length === 24 && str.split('').every((c) => '0123456789ABCDEFabcdef'.indexOf(c) !== -1);\n```\n\n**TypeScript version**\n\n```ts isMongoId.ts\nconst isMongoId = (str: string): boolean => str.length === 24 && /^[A-F0-9]+$/i.test(str);\n\n// Or\nconst isMongoId = (str: string): boolean =>\n    str.length === 24 && str.split('').every((c) => '0123456789ABCDEFabcdef'.indexOf(c) !== -1);\n```\n"
  },
  {
    "path": "contents/check-if-a-string-is-a-palindrome.mdx",
    "content": "---\ncategory: String\ncontributors:\n    - marcobiedermann\ncreated: '2020-05-18'\ntitle: Check if a string is a palindrome\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isPalindrome.js\nconst isPalindrome = (str) => str === str.split('').reverse().join('');\n```\n\n**TypeScript version**\n\n```ts isPalindrome.ts\nconst isPalindrome = (str: string): boolean => str === str.split('').reverse().join('');\n```\n\n**Examples**\n\n```js examples.js\nisPalindrome('abc'); // false\nisPalindrom('abcba'); // true\n```\n"
  },
  {
    "path": "contents/check-if-a-string-is-an-octal-number.mdx",
    "content": "---\ncategory: Validator\ncreated: '2021-04-10'\ntitle: Check if a string is an octal number\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isOctal.js\nconst isOctal = (str) => /^(0o)?[0-7]+$/i.test(str);\n```\n\n**TypeScript version**\n\n```ts isOctal.ts\nconst isOctal = (str: string): boolean => /^(0o)?[0-7]+$/i.test(str);\n```\n"
  },
  {
    "path": "contents/check-if-a-string-is-lower-case.mdx",
    "content": "---\ncategory: Validator\ncreated: '2020-04-19'\ntitle: Check if a string is lower case\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isLowerCase.js\nconst isLowerCase = (str) => str === str.toLowerCase();\n```\n\n**TypeScript version**\n\n```ts isLowerCase.ts\nconst isLowerCase = (str: string): boolean => str === str.toLowerCase();\n```\n"
  },
  {
    "path": "contents/check-if-a-string-is-upper-case.mdx",
    "content": "---\ncategory: Validator\ncreated: '2020-04-19'\ntitle: Check if a string is upper case\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isUpperCase.js\nconst isUpperCase = (str) => str === str.toUpperCase();\n```\n\n**TypeScript version**\n\n```ts isUpperCase.ts\nconst isUpperCase = (str: string): boolean => str === str.toUpperCase();\n```\n"
  },
  {
    "path": "contents/check-if-a-url-is-absolute.mdx",
    "content": "---\ncategory: String\ncreated: '2020-05-15'\ntitle: Check if a URL is absolute\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isAbsoluteUrl.js\nconst isAbsoluteUrl = (url) => /^[a-z][a-z0-9+.-]*:/.test(url);\n```\n\n**TypeScript version**\n\n```ts isAbsoluteUrl.ts\nconst isAbsoluteUrl = (url: string): boolean => /^[a-z][a-z0-9+.-]*:/.test(url);\n```\n\n**Examples**\n\n```js examples.js\nisAbsoluteUrl('https://phuoc.ng'); // true\nisAbsoluteUrl('https://phuoc.ng/collection/1-loc'); // true\nisAbsoluteUrl('phuoc.ng'); // false\nisAbsoluteUrl('//phuoc.ng'); // false\n```\n"
  },
  {
    "path": "contents/check-if-a-value-is-a-business-identifier-code.mdx",
    "content": "---\ncategory: Validator\ncreated: '2021-04-10'\ntitle: Check if a value is a business identifier code\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isBIC.js\nconst isBIC = (value) => /^[a-zA-Z]{6}[a-zA-Z0-9]{2}([a-zA-Z0-9]{3})?$/.test(value);\n```\n\n**TypeScript version**\n\n```ts isBIC.ts\nconst isBIC = (value: string): boolean => /^[a-zA-Z]{6}[a-zA-Z0-9]{2}([a-zA-Z0-9]{3})?$/.test(value);\n```\n"
  },
  {
    "path": "contents/check-if-a-value-is-a-function.mdx",
    "content": "---\ncategory: Function\ncreated: '2020-05-15'\ntitle: Check if a value is a function\n---\n\n**JavaScript version**\n\n```js isFunction.js\nconst isFunction = (v) =>\n    ['[object Function]', '[object GeneratorFunction]', '[object AsyncFunction]', '[object Promise]'].includes(\n        Object.prototype.toString.call(v)\n    );\n```\n\n**Examples**\n\n```js examples.js\nisFunction(function () {}); // true\nisFunction(function* () {}); // true\nisFunction(async function () {}); // true\n```\n"
  },
  {
    "path": "contents/check-if-a-value-is-a-generator-function.mdx",
    "content": "---\ncategory: Function\ncreated: '2020-05-15'\ntitle: Check if a value is a generator function\n---\n\n**JavaScript version**\n\n```js isGeneratorFunction.js\nconst isGeneratorFunction = (v) => Object.prototype.toString.call(v) === '[object GeneratorFunction]';\n```\n\n**Examples**\n\n```js examples.js\nisGeneratorFunction(function () {}); // false\nisGeneratorFunction(function* () {}); // true\n```\n"
  },
  {
    "path": "contents/check-if-a-value-is-a-number.mdx",
    "content": "---\ncategory: Validator\ncontributors:\n    - nbayramberdiyev\ncreated: '2020-04-23'\ntitle: Check if a value is a number\nupdated: '2021-11-03'\n---\n\n**JavaScript version**\n\n```js isNumber.js\nconst isNumber = (value) => !isNaN(parseFloat(value)) && isFinite(value);\n```\n\n**TypeScript version**\n\n```ts isNumber.ts\nconst isNumber = (value: any): number => !isNaN(parseFloat(value)) && isFinite(value);\n```\n"
  },
  {
    "path": "contents/check-if-a-value-is-a-plain-object.mdx",
    "content": "---\ncategory: Validator\ncreated: '2020-05-13'\ntitle: Check if a value is a plain object\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isPlainObject.js\nconst isPlainObject = (v) => !!v && typeof v === 'object' && (v.__proto__ === null || v.__proto__ === Object.prototype);\n```\n\n**TypeScript version**\n\n```ts isPlainObject.ts\nconst isPlainObject = (v: any): boolean =>\n    !!v && typeof v === 'object' && (v.__proto__ === null || v.__proto__ === Object.prototype);\n```\n\n**Examples**\n\n```js examples.js\nisPlainObject(null); // false\nisPlainObject('hello world'); // false\nisPlainObject([]); // false\nisPlainObject(Object.create(null)); // false\nisPlainObject(function () {}); // false\n\nisPlainObject({}); // true\nisPlainObject({ a: '1', b: '2' }); // true\n```\n"
  },
  {
    "path": "contents/check-if-a-value-is-a-regular-expression.mdx",
    "content": "---\ncategory: Validator\ncreated: '2020-05-14'\ntitle: Check if a value is a regular expression\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isRegExp.js\nconst isRegExp = (value) => Object.prototype.toString.call(value) === '[object RegExp]';\n```\n\n**TypeScript version**\n\n```ts isRegExp.ts\nconst isRegExp = (value: any): boolean => Object.prototype.toString.call(value) === '[object RegExp]';\n```\n"
  },
  {
    "path": "contents/check-if-a-value-is-a-string.mdx",
    "content": "---\ncategory: Validator\ncreated: '2020-06-05'\ntitle: Check if a value is a string\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isString.js\nconst isString = (value) => Object.prototype.toString.call(value) === '[object String]';\n```\n\n**TypeScript version**\n\n```ts isString.ts\nconst isString = (value: any): boolean => Object.prototype.toString.call(value) === '[object String]';\n```\n\n**Examples**\n\n```js examples.js\nisString('hello world'); // true\nisString(new String('hello world')); // true\nisString(10); // false\n```\n"
  },
  {
    "path": "contents/check-if-a-value-is-an-async-function.mdx",
    "content": "---\ncategory: Function\ncreated: '2020-05-15'\ntitle: Check if a value is an async function\n---\n\n**JavaScript version**\n\n```js isAsyncFunction.js\nconst isAsyncFunction = (v) => Object.prototype.toString.call(v) === '[object AsyncFunction]';\n```\n\n**Examples**\n\n```js examples.js\nisAsyncFunction(function () {}); // false\nisAsyncFunction(function* () {}); // false\nisAsyncFunction(async function () {}); // true\n```\n"
  },
  {
    "path": "contents/check-if-a-value-is-an-object.mdx",
    "content": "---\ncategory: Validator\ncreated: '2020-05-13'\ntitle: Check if a value is an object\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isObject.js\nconst isObject = (v) => v !== null && typeof v === 'object';\n```\n\n**TypeScript version**\n\n```ts isObject.ts\nconst isObject = (v: any): boolean => v !== null && typeof v === 'object';\n```\n\n**Examples**\n\n```js examples.js\nisObject(null); // false\nisObject('hello world'); // false\n\nisObject({}); // true\nisObject([]); // true\n```\n"
  },
  {
    "path": "contents/check-if-a-value-is-base32-encoded.mdx",
    "content": "---\ncategory: Validator\ncreated: '2021-04-10'\ntitle: Check if a value is base32 encoded\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isBase32.js\nconst isBase32 = (value) => value.length % 8 === 0 && /^[A-Z2-7]+=*$/.test(value);\n```\n\n**TypeScript version**\n\n```ts isBase32.ts\nconst isBase32 = (value: string): boolean => value.length % 8 === 0 && /^[A-Z2-7]+=*$/.test(value);\n```\n"
  },
  {
    "path": "contents/check-if-a-value-is-base58-encoded.mdx",
    "content": "---\ncategory: Validator\ncreated: '2021-04-10'\ntitle: Check if a value is base58 encoded\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isBase58.js\n// It doesn't accept the I, O, l characters\nconst isBase58 = (value) => /^[A-HJ-NP-Za-km-z1-9]*$/.test(value);\n```\n\n**TypeScript version**\n\n```ts isBase58.ts\nconst isBase58 = (value: string): boolean => /^[A-HJ-NP-Za-km-z1-9]*$/.test(value);\n```\n"
  },
  {
    "path": "contents/check-if-a-value-is-base64-encoded.mdx",
    "content": "---\ncategory: Validator\ncreated: '2021-04-10'\ntitle: Check if a value is base64 encoded\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isBase64.js\nconst isBase64 = (value) =>\n    /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/.test(value);\n```\n\n**TypeScript version**\n\n```ts isBase64.ts\nconst isBase64 = (value: string): boolean =>\n    /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/.test(value);\n```\n"
  },
  {
    "path": "contents/check-if-a-value-is-nil.mdx",
    "content": "---\ncategory: Validator\ncontributors:\n    - JeromeDeLeon\ncreated: '2020-05-06'\ntitle: Check if a value is nil\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isNil.js\nconst isNil = (value) => value == null;\n```\n\n**TypeScript version**\n\n```ts isNil.ts\nconst isNil = (value: any): boolean => value == null;\n```\n"
  },
  {
    "path": "contents/check-if-a-year-is-leap-year.mdx",
    "content": "---\ncategory: Validator\ncreated: '2020-04-19'\ntitle: Check if a year is leap year\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isLeapYear.js\nconst isLeapYear = (year) => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\n\n// Or\n// Get the number of days in February\nconst isLeapYear = (year) => new Date(year, 1, 29).getDate() === 29;\n```\n\n**TypeScript version**\n\n```ts isLeapYear.ts\nconst isLeapYear = (year: number): boolean => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\n\n// Or\nconst isLeapYear = (year: number): boolean => new Date(year, 1, 29).getDate() === 29;\n```\n"
  },
  {
    "path": "contents/check-if-all-array-elements-are-equal-to-a-given-value.mdx",
    "content": "---\ncategory: Validator\ncontributors:\n    - contributorpw\n    - tugsanunlu\ncreated: '2020-05-08'\ntitle: Check if all array elements are equal to a given value\nupdated: '2021-10-22'\n---\n\n**JavaScript version**\n\n```js isEqual.js\nconst isEqual = (arr, value) => arr.every((item) => item === value);\n\n// Or\n// Ends earlier for false arrays\nconst isEqual = (arr, value) => !arr.some((item) => item !== value);\n```\n\n**TypeScript version**\n\n```ts isEqual.ts\nconst isEqual = <T,_>(arr: T[], value: T): boolean => arr.every((item) => item === value);\n\n// Or\nconst isEqual = <T,_>(arr: T[], value: T): boolean => !arr.some((item) => item !== value);\n```\n\n**Examples**\n\n```js examples.js\nisEqual(['foo', 'foo'], 'foo'); // true\nisEqual(['foo', 'bar'], 'foo'); // false\nisEqual(['bar', 'bar'], 'foo'); // false\n```\n"
  },
  {
    "path": "contents/check-if-all-items-in-an-array-are-equal.mdx",
    "content": "---\ncategory: Validator\ncontributors:\n    - manu2504\n    - glennfaison\ncreated: '2020-04-19'\ntitle: Check if all items in an array are equal\nupdated: '2021-10-22'\n---\n\n**JavaScript version**\n\n```js areEqual.js\nconst areEqual = (arr) => arr.length > 0 && arr.every((item) => item === arr[0]);\n\n// Or\nconst areEqual = (arr) => new Set(arr).size === 1;\n```\n\n**TypeScript version**\n\n```ts areEqual.ts\nconst areEqual = <T,_>(arr: T[]): boolean => arr.length > 0 && arr.every((item) => item === arr[0]);\n\n// Or\nconst areEqual = <T,_>(arr: T[]): boolean => new Set(arr).size === 1;\n```\n\n**Examples**\n\n```js examples.js\nareEqual([1, 2, 3, 4]); // false\nareEqual(['hello', 'hello', 'hello']); // true\n```\n"
  },
  {
    "path": "contents/check-if-an-array-contains-a-value-matching-some-criterias.mdx",
    "content": "---\ncategory: Validator\ncontributors:\n    - chety\n    - nemanjapesic\n    - 31piy\n    - aethernet\ncreated: '2020-05-10'\ntitle: Check if an array contains a value matching some criterias\nupdated: '2021-10-22'\n---\n\n**JavaScript version**\n\n```js contains.js\nconst contains = (arr, criteria) => arr.some((v) => criteria(v));\n\n// Or\nconst contains = (arr, criteria) => arr.some(criteria);\n\n// Or\nconst contains = (arr, criteria) => arr.filter(criteria).length > 0;\n```\n\n**TypeScript version**\n\n```ts contains.ts\nconst contains = <T,_>(arr: T[], criteria: (a: T) => boolean): boolean => arr.some((v) => criteria(v));\n\n// Or\nconst contains = <T,_>(arr: T[], criteria: (a: T) => boolean): boolean => arr.some(criteria);\n\n// Or\nconst contains = <T,_>(arr: T[], criteria: (a: T) => boolean): boolean => arr.filter(criteria).length > 0;\n```\n\n**Examples**\n\n```js examples.js\ncontains([10, 20, 30], (v) => v > 25); // true\ncontains([10, 20, 30], (v) => v > 100 || v < 15); // true\ncontains([10, 20, 30], (v) => v > 100); // false\n```\n"
  },
  {
    "path": "contents/check-if-an-array-is-empty.mdx",
    "content": "---\ncategory: Array\ncontributors:\n    - inoyakaigor\n    - elkarouani\ncreated: '2020-06-23'\ntitle: Check if an array is empty\nupdated: '2021-12-21'\n---\n\n**JavaScript version**\n\n```js isEmpty.js\n// `arr` is an array\nconst isEmpty = (arr) => Array.isArray(arr) && !arr.length;\n```\n\n**TypeScript version**\n\n```ts isEmpty.ts\nconst isEmpty = <T,_>(arr: T[]): boolean => Array.isArray(arr) && !arr.length;\n```\n\n**Examples**\n\n```js examples.js\nisEmpty([]); // true\nisEmpty([1, 2, 3]); // false\n```\n"
  },
  {
    "path": "contents/check-if-an-array-is-not-empty.mdx",
    "content": "---\ncategory: Validator\ncontributors:\n    - fenilgandhi\n    - marcobiedermann\ncreated: '2020-05-06'\ntitle: Check if an array is not empty\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isNotEmpty.js\nconst isNotEmpty = (arr) => Array.isArray(arr) && Object.keys(arr).length > 0;\n```\n\n**TypeScript version**\n\n```ts isNotEmpty.ts\nconst isNotEmpty = (arr: any): boolean => Array.isArray(arr) && Object.keys(arr).length > 0;\n```\n\n**Examples**\n\n```js examples.js\nisNotEmpty([]); // false\nisNotEmpty([1, 2, 3]); // true\n```\n"
  },
  {
    "path": "contents/check-if-an-array-is-subset-of-other-array.mdx",
    "content": "---\ncategory: Validator\ncontributors:\n    - lupu60\n    - Rupesh Jaiswal\ncreated: '2020-05-10'\ntitle: Check if an array is subset of other array\nupdated: '2021-10-22'\n---\n\n**JavaScript version**\n\n```js isSubset.js\n// Check if `b` is subset of `a`\nconst isSubset = (a, b) => new Set(b).size === new Set(b.concat(a)).size;\n\n// Or\nconst isSubset = (a, b) => b.join('|').includes(a.join('|'));\n```\n\n**TypeScript version**\n\n```ts isSubset.ts\nconst isSubset = <T,_>(a: T[], b: T[]): boolean => new Set(b).size === new Set(b.concat(a)).size;\n\n// Or\nconst isSubset = <T,_>(a: T[], b: T[]): boolean => b.join('|').includes(a.join('|'));\n```\n\n**Examples**\n\n```js examples.js\nisSubset([1, 2], [1, 2, 3, 4]); // true\nisSubset([1, 2, 5], [1, 2, 3, 4]); // false\nisSubset([6], [1, 2, 3, 4]); // false\n```\n"
  },
  {
    "path": "contents/check-if-an-element-has-css-overflow.mdx",
    "content": "---\ncategory: DOM\ncreated: '2023-12-15'\nopenGraphCover: /og/1-loc/check-element-has-css-overflow.png\ntags: CSS overflow, getComputedStyle\ntitle: Check if an element has CSS overflow\n---\n\n**JavaScript version**\n\n```js hasCssOverflow.js\nconst hasCssOverflow = (ele) => [\"auto\", \"scroll\"].includes(window.getComputedStyle(ele)[\"overflow\"]);\n```\n\n**TypeScript version**\n\n```ts hasCssOverflow.ts\nconst hasCssOverflow = (ele: HTMLElement) => [\"auto\", \"scroll\"].includes(window.getComputedStyle(ele)[\"overflow\"]);\n```\n\nThe `hasCssOverflow` function checks if an HTML element has CSS overflow. First, it gets the element's computed styles using `window.getComputedStyle`. This method returns an object with all the CSS properties applied to the element.\n\nNext, we check the `overflow` property of this object and see if it's either `auto` or `scroll`. If it is, we know the element has CSS overflow and return `true`.\n\nIf neither of these values is present in the `overflow` property, we know there's no CSS overflow on the element and return `false`.\n\n## See also\n\n-   [Check if an element has overflow](https://phuoc.ng/collection/1-loc/check-if-an-element-has-overflow/)\n"
  },
  {
    "path": "contents/check-if-an-element-has-overflow.mdx",
    "content": "---\ncategory: DOM\ncreated: '2023-12-16'\nopenGraphCover: /og/1-loc/check-element-has-overflow.png\ntitle: Check if an element has overflow\n---\n\n**JavaScript version**\n\n```js hasOverflow.js\nconst hasOverflow = (ele) => ele.scrollHeight > ele.clientHeight || ele.scrollWidth > ele.clientWidth;\n```\n\n**TypeScript version**\n\n```ts hasOverflow.ts\nconst hasOverflow = (ele: HTMLElement) => ele.scrollHeight > ele.clientHeight || ele.scrollWidth > ele.clientWidth;\n```\n\nThe `hasOverflow` function checks if an HTML element has overflow in its content. It does this by comparing the element's `scrollHeight` and `scrollWidth` properties to its `clientHeight` and `clientWidth` properties, respectively.\n\nIf the scroll height or width is greater than the client height or width, it means there's overflow in the content. In this case, the function returns `true`, indicating overflow. If there's no overflow, the function returns `false`.\n\nThis function is useful when you want to check if an element needs scrolling. You can use it to determine whether a scroll bar should be displayed for an element based on whether it has overflow or not.\n\n## See also\n\n-   [Check if an element has CSS overflow](https://phuoc.ng/collection/1-loc/check-if-an-element-has-css-overflow/)\n"
  },
  {
    "path": "contents/check-if-an-element-is-a-descendant-of-another.mdx",
    "content": "---\ncategory: DOM\ncreated: '2020-04-19'\ntitle: Check if an element is a descendant of another\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isDescendant.js\nconst isDescendant = (child, parent) => parent.contains(child);\n```\n\n**TypeScript version**\n\n```ts isDescendant.ts\nconst isDescendant = (child: Node, parent: Node): boolean => parent.contains(child);\n```\n"
  },
  {
    "path": "contents/check-if-an-element-is-focused.mdx",
    "content": "---\ncategory: DOM\ncreated: '2020-04-19'\ntitle: Check if an element is focused\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js hasFocus.js\nconst hasFocus = (ele) => ele === document.activeElement;\n```\n\n**TypeScript version**\n\n```ts hasFocus.ts\nconst hasFocus = (ele: Node): boolean => ele === document.activeElement;\n```\n"
  },
  {
    "path": "contents/check-if-an-object-is-a-promise.mdx",
    "content": "---\ncategory: Validator\ncontributors:\n    - quantumsheep\ncreated: '2020-05-06'\ntitle: Check if an object is a Promise\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isPromise.js\nconst isPromise = (obj) =>\n    !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';\n```\n\n**TypeScript version**\n\n```ts isPromise.ts\nconst isPromise = (obj: any): boolean =>\n    !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';\n```\n"
  },
  {
    "path": "contents/check-if-an-object-is-an-array.mdx",
    "content": "---\ncategory: Validator\ncreated: '2020-04-19'\ntitle: Check if an object is an array\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isArray.js\nconst isArray = (obj) => Array.isArray(obj);\n```\n\n**TypeScript version**\n\n```ts isArray.ts\nconst isArray = (obj: any): boolean => Array.isArray(obj);\n```\n"
  },
  {
    "path": "contents/check-if-an-object-is-empty.mdx",
    "content": "---\ncategory: Validator\ncontributors:\n    - robinpokorny\ncreated: '2020-04-19'\ntitle: Check if an object is empty\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isEmpty.js\nconst isEmpty = (obj) => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;\n\n// Or for enumerable property names only\nconst isEmpty = (obj) => JSON.stringify(obj) === '{}';\n```\n\n**TypeScript version**\n\n```ts isEmpty.ts\nconst isEmpty = (obj: object): boolean => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;\n\nconst isEmpty = (obj: object): boolean => JSON.stringify(obj) === '{}';\n```\n"
  },
  {
    "path": "contents/check-if-multiple-objects-are-equal.mdx",
    "content": "---\ncategory: Object\ncontributors:\n    - tugsanunlu\ncreated: '2020-05-20'\ntitle: Check if multiple objects are equal\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isEqual.js\nconst isEqual = (...objects) => objects.every((obj) => JSON.stringify(obj) === JSON.stringify(objects[0]));\n```\n\n**TypeScript version**\n\n```ts isEqual.ts\nconst isEqual = (...objects: object[]): boolean =>\n    objects.every((obj) => JSON.stringify(obj) === JSON.stringify(objects[0]));\n```\n\n**Examples**\n\n```js examples.js\nisEqual({ foo: 'bar' }, { foo: 'bar' }); // true\nisEqual({ foo: 'bar' }, { bar: 'foo' }); // false\n```\n"
  },
  {
    "path": "contents/check-if-the-code-is-running-in-jest.mdx",
    "content": "---\ncategory: Misc\ncreated: '2022-06-18'\ntitle: Check if the code is running in Jest\n---\n\n**JavaScript version**\n\n```js isRunningInJest.js\nconst isRunningInJest = typeof process !== 'undefined' && process.env.JEST_WORKER_ID !== undefined;\n```\n\n**TypeScript version**\n\n```ts isRunningInJest.ts\nconst isRunningInJest: boolean = typeof process !== 'undefined' && process.env.JEST_WORKER_ID !== undefined;\n```\n"
  },
  {
    "path": "contents/check-if-the-code-is-running-in-node-js.mdx",
    "content": "---\ncategory: Misc\ncreated: '2020-05-02'\ntitle: Check if the code is running in NodeJS\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isNode.js\nconst isNode = typeof process !== 'undefined' && process.versions != null && process.versions.node != null;\n```\n\n**TypeScript version**\n\n```ts isNode.ts\nconst isNode: boolean = typeof process !== 'undefined' && process.versions != null && process.versions.node != null;\n```\n"
  },
  {
    "path": "contents/check-if-the-code-is-running-in-the-browser.mdx",
    "content": "---\ncategory: Misc\ncreated: '2020-05-02'\ntitle: Check if the code is running in the browser\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isBrowser.js\nconst isBrowser = typeof window === 'object' && typeof document === 'object';\n```\n\n**TypeScript version**\n\n```ts isBrowser.ts\nconst isBrowser: boolean = typeof window === 'object' && typeof document === 'object';\n```\n"
  },
  {
    "path": "contents/check-if-the-touch-events-are-supported.mdx",
    "content": "---\ncategory: DOM\ncreated: '2020-04-25'\ntitle: Check if the touch events are supported\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js touchSupported.js\nconst touchSupported = () =>\n    'ontouchstart' in window || (window.DocumentTouch && document instanceof window.DocumentTouch);\n```\n\n**TypeScript version**\n\n```ts touchSupported.ts\nconst touchSupported = (): boolean => (\n    'ontouchstart' in window || (window as any)['DocumentTouch'] && document instanceof (window as any)['DocumentTouch']\n);\n```\n"
  },
  {
    "path": "contents/check-if-two-dom-rects-intersect.mdx",
    "content": "---\ncategory: DOM\ncreated: '2023-12-12'\nopenGraphCover: /og/1-loc/check-two-dom-rects-intersect.png\ntitle: Check if two DOMRects intersect\n---\n\n**JavaScript version**\n\n```js intersect.js\nconst intersect = (a, b) => (b.right >= a.left && b.left <= a.right && b.top <= a.bottom && b.bottom >= a.top);\n```\n\n**TypeScript version**\n\n```ts intersect.ts\nconst intersect = (a: DOMRect, b: DOMRect): boolean => (b.right >= a.left && b.left <= a.right && b.top <= a.bottom && b.bottom >= a.top);\n```\n\n**Example**\n\n```js example.js\nconst a = new DOMRect(0, 0, 40, 40);\nconst b = new DOMRect(10, 10, 20, 20);\nintersect(a, b);        // true\n```\n\n## See also\n\n-   [Check if a given DOMRect is contained within another DOMRect](https://phuoc.ng/collection/1-loc/check-if-a-given-dom-rect-is-contained-within-another-dom-rect/)\n"
  },
  {
    "path": "contents/check-if-two-strings-are-anagram.mdx",
    "content": "---\ncategory: String\ncontributors:\n    - mahdiyar\ncreated: '2020-05-07'\ntitle: Check if two strings are anagram\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js areAnagram.js\nconst areAnagram = (str1, str2) =>\n    str1.toLowerCase().split('').sort().join('') === str2.toLowerCase().split('').sort().join('');\n```\n\n**TypeScript version**\n\n```ts areAnagram.ts\nconst areAnagram = (str1: string, str2: string): boolean =>\n    str1.toLowerCase().split('').sort().join('') === str2.toLowerCase().split('').sort().join('');\n```\n\n**Examples**\n\n```js examples.js\nareAnagram('listen', 'silent'); // true\nareAnagram('they see', 'the eyes'); // true\nareAnagram('node', 'deno'); // true\n```\n"
  },
  {
    "path": "contents/check-if-user-scrolls-to-the-bottom-of-the-page.mdx",
    "content": "---\ncategory: DOM\ncreated: '2021-04-10'\ntitle: Check if user scrolls to the bottom of the page\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isAtBottom.js\nconst isAtBottom = () =>\n    document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;\n```\n\n**TypeScript version**\n\n```ts isAtBottom.ts\nconst isAtBottom = (): boolean =>\n    document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;\n```\n"
  },
  {
    "path": "contents/clamp-a-number-between-two-values.mdx",
    "content": "---\ncategory: Number\ncontributors:\n    - r-i-c-h\ncreated: '2020-05-05'\ntitle: Clamp a number between two values\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js clamp.js\nconst clamp = (val, min = 0, max = 1) => Math.max(min, Math.min(max, val));\n```\n\n**TypeScript version**\n\n```ts clamp.ts\nconst clamp = (val: number, min: number = 0, max: number = 1): number => Math.max(min, Math.min(max, val));\n```\n\n**Examples**\n\n```js examples.js\nclamp(199, 10, 25); // 25\n```\n\n## See also\n\n-   [Build a spin input](https://phuoc.ng/collection/html-dom/build-a-spin-input/)\n-   [Wrap a number between two values](https://phuoc.ng/collection/1-loc/wrap-a-number-between-two-values/)\n"
  },
  {
    "path": "contents/clear-all-cookies.mdx",
    "content": "---\ncategory: Misc\ncontributors:\n    - iamandrewluca\ncreated: '2021-04-20'\ntitle: Clear all cookies\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js clearCookies.js\nconst clearCookies = () =>\n    document.cookie\n        .split(';')\n        .forEach(\n            (c) =>\n                (document.cookie = c.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`))\n        );\n```\n\n**TypeScript version**\n\n```ts clearCookies.ts\nconst clearCookies = (): void =>\n    document.cookie\n        .split(';')\n        .forEach(\n            (c) =>\n                (document.cookie = c.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`))\n        );\n```\n\n**Examples**\n\n```js examples.js\nclearCookies();\n```\n"
  },
  {
    "path": "contents/clone-an-array.mdx",
    "content": "---\ncategory: Array\ncontributors:\n    - tahseenio\ncreated: '2020-05-07'\ntitle: Clone an array\nupdated: '2022-06-27'\n---\n\n**JavaScript version**\n\n```js clone.js\n// `arr` is an array\nconst clone = (arr) => arr.slice(0);\n\n// Or\nconst clone = (arr) => [...arr];\n\n// Or\nconst clone = (arr) => Array.from(arr);\n\n// Or\nconst clone = (arr) => arr.map((x) => x);\n\n// Or\nconst clone = (arr) => JSON.parse(JSON.stringify(arr));\n\n// Or\nconst clone = (arr) => arr.concat([]);\n\n// Or\nconst clone = (arr) => structuredClone(arr);\n```\n\n**TypeScript version**\n\n```ts clone.ts\n// `arr` is an array\nconst clone = <T,_>(arr: T[]): T[] => arr.slice(0);\n\n// Or\nconst clone = <T,_>(arr: T[]): T[] => [...arr];\n\n// Or\nconst clone = <T,_>(arr: T[]): T[] => Array.from(arr);\n\n// Or\nconst clone = <T,_>(arr: T[]): T[] => arr.map((x) => x);\n\n// Or\nconst clone = <T,_>(arr: T[]): T[] => JSON.parse(JSON.stringify(arr));\n\n// Or\nconst clone = <T,_>(arr: T[]): T[] => arr.concat([]);\n\n// Or\nconst clone = <T,_>(arr: T[]): T[] => structuredClone(arr);\n```\n"
  },
  {
    "path": "contents/compare-two-arrays-regardless-of-order.mdx",
    "content": "---\ncategory: Array\ncontributors:\n    - Rupesh Jaiswal\n    - robinpokorny\n    - dauom\n    - elkarouani\ncreated: '2020-05-11'\ntitle: Compare two arrays regardless of order\nupdated: '2021-12-23'\n---\n\n**JavaScript version**\n\n```js isEqual.js\n// `a` and `b` are arrays\nconst isEqual = (a, b) => JSON.stringify([...new Set(a)].sort()) === JSON.stringify([...new Set(b)].sort());\n```\n\n**TypeScript version**\n\n```ts isEqual.ts\nconst isEqual = <T,_>(a: T[], b: T[]): boolean => JSON.stringify([...(new Set(a))].sort()) === JSON.stringify([...(new Set(b))].sort());\n```\n\n**Examples**\n\n```js examples.js\nisEqual([1, 2, 3], [1, 2, 3]); // true\nisEqual([1, 2, 3], [1, 3, 2]); // true\nisEqual([1, 2, 3], [1, '2', 3]); // false\n```\n"
  },
  {
    "path": "contents/compare-two-arrays.mdx",
    "content": "---\ncategory: Array\ncreated: '2020-05-05'\ntitle: Compare two arrays\nupdated: '2021-10-22'\n---\n\n**JavaScript version**\n\n```js isEqual.js\n// `a` and `b` are arrays\nconst isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);\n\n// Or\nconst isEqual = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);\n```\n\n**TypeScript version**\n\n```ts isEqual.ts\nconst isEqual = <T,_>(a: T[], b: T[]): boolean => JSON.stringify(a) === JSON.stringify(b);\n\n// Or\nconst isEqual = <T,_>(a: T[], b: T[]): boolean => a.length === b.length && a.every((v, i) => v === b[i]);\n```\n\n**Examples**\n\n```js examples.js\nisEqual([1, 2, 3], [1, 2, 3]); // true\nisEqual([1, 2, 3], [1, '2', 3]); // false\n```\n"
  },
  {
    "path": "contents/compare-two-dates.mdx",
    "content": "---\ncategory: Date Time\ncreated: '2020-04-19'\ntitle: Compare two dates\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js compare.js\n// `a` and `b` are `Date` instances\nconst compare = (a, b) => a.getTime() > b.getTime();\n```\n\n**TypeScript version**\n\n```ts compare.ts\nconst compare = (a: Date, b: Date): boolean => a.getTime() > b.getTime();\n```\n\n**Example**\n\n```js example.js\ncompare(new Date('2020-03-30'), new Date('2020-01-01')); // true\n```\n"
  },
  {
    "path": "contents/compare-two-dom-rects-for-size-and-position-match.mdx",
    "content": "---\ncategory: DOM\ncreated: '2023-12-10'\nopenGraphCover: /og/1-loc/compare-two-dom-rects-size-position-match.png\ntitle: Compare two DOMRects for size and position match\n---\n\n**JavaScript version**\n\n```js compare.js\nconst compare = (a, b) => ['top', 'left', 'width', 'height'].every(key => a[key] === b[key]);\n```\n\n**Example**\n\n```js example.js\nconst a = new DOMRect(0, 0, 100, 200);\nconst b = new DOMRect(0, 0, 100, 200);\ncompare(a, b);  // true\n```\n"
  },
  {
    "path": "contents/compose-functions-from-left-to-right.mdx",
    "content": "---\ncategory: Function\ncreated: '2020-05-12'\ntitle: Compose functions from left to right\n---\n\n**JavaScript version**\n\n```js pipe.js\n// Compose functions from left to right\nconst pipe =\n    (...fns) =>\n    (x) =>\n        fns.reduce((y, f) => f(y), x);\n```\n\n**Examples**\n\n```js examples.js\nconst lowercase = (str) => str.toLowerCase();\nconst capitalize = (str) => `${str.charAt(0).toUpperCase()}${str.slice(1)}`;\nconst reverse = (str) => str.split('').reverse().join('');\n\nconst fn = pipe(lowercase, capitalize, reverse);\n\n// We will execute `lowercase`, `capitalize` and `reverse` in order\nfn('Hello World') === 'dlrow olleH';\n```\n"
  },
  {
    "path": "contents/compose-functions.mdx",
    "content": "---\ncategory: Function\ncreated: '2020-05-07'\ntitle: Compose functions\n---\n\n**JavaScript version**\n\n```js compose.js\n// Compose functions from right to left\nconst compose =\n    (...fns) =>\n    (x) =>\n        fns.reduceRight((y, f) => f(y), x);\n```\n\n**Examples**\n\n```js examples.js\nconst lowercase = (str) => str.toLowerCase();\nconst capitalize = (str) => `${str.charAt(0).toUpperCase()}${str.slice(1)}`;\nconst reverse = (str) => str.split('').reverse().join('');\n\nconst fn = compose(reverse, capitalize, lowercase);\n\n// We will execute `lowercase`, `capitalize` and `reverse` in order\nfn('Hello World') === 'dlrow olleH';\n```\n"
  },
  {
    "path": "contents/compute-the-greatest-common-divisor-between-two-numbers.mdx",
    "content": "---\ncategory: Number\ncreated: '2020-04-23'\ntitle: Compute the greatest common divisor between two numbers\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js gcd.js\nconst gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));\n```\n\n**TypeScript version**\n\n```ts gcd.ts\nconst gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));\n```\n\n**Examples**\n\n```js examples.js\ngcd(10, 15); // 5\n```\n"
  },
  {
    "path": "contents/convert-3-digits-color-to-6-digits-color.mdx",
    "content": "---\ncategory: Misc\ncreated: '2021-02-20'\ntitle: Convert 3 digits color to 6 digits color\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js toFullHexColor.js\nconst toFullHexColor = (color) =>\n    `#${(color.startsWith('#') ? color.slice(1) : color)\n        .split('')\n        .map((c) => `${c}${c}`)\n        .join('')}`;\n```\n\n**TypeScript version**\n\n```ts toFullHexColor.ts\nconst toFullHexColor = (color: string): string =>\n    `#${(color.startsWith('#') ? color.slice(1) : color)\n        .split('')\n        .map((c) => `${c}${c}`)\n        .join('')}`;\n```\n\n**Examples**\n\n```js examples.js\ntoFullHexColor('123'); // '#112233'\ntoFullHexColor('#123'); // '#112233'\ntoFullHexColor('#abc'); // '#aabbcc'\n```\n"
  },
  {
    "path": "contents/convert-a-base64-encoded-string-to-an-uint8-array.mdx",
    "content": "---\ncategory: String\ncreated: '2021-11-11'\ntitle: Convert a base64 encoded string to an uint8 array\n---\n\n**JavaScript version**\n\n```js base64ToUint8.js\nconst base64ToUint8 = (str) => Uint8Array.from(atob(str), (c) => c.charCodeAt(0));\n```\n\n**TypeScript version**\n\n```ts base64ToUint8.ts\nconst base64ToUint8 = (str: string): Uint8Array => Uint8Array.from(atob(str), (c) => c.charCodeAt(0));\n```\n\n## See also\n\n-   [Convert an uint8 array to a base64 encoded string](https://phuoc.ng/collection/1-loc/convert-an-uint8-array-to-a-base64-encoded-string/)\n"
  },
  {
    "path": "contents/convert-a-date-to-yyyy-mm-dd-format.mdx",
    "content": "---\ncategory: Date Time\ncontributors:\n    - ValchanOficial\ncreated: '2020-04-19'\ntitle: 'Convert a date to YYYY-MM-DD format'\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js formatYmd.js\n// `date` is a `Date` object\nconst formatYmd = (date) => date.toISOString().slice(0, 10);\n```\n\n**TypeScript version**\n\n```ts formatYmd.ts\nconst formatYmd = (date: Date): string => date.toISOString().slice(0, 10);\n```\n\n**Example**\n\n```js example.js\nformatYmd(new Date()); // 2020-05-06\n```\n"
  },
  {
    "path": "contents/convert-a-lab-color-to-an-lch-color.mdx",
    "content": "---\ncategory: Misc\ncreated: '2023-11-10'\nopenGraphCover: /og/1-loc/convert-lab-color-lch-color.png\ntitle: Convert a LAB color to an LCH color\n---\n\n**JavaScript version**\n\n```js labToLch.js\nconst labToLch = (l, a, b) => [\n    l,\n    Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2)),\n    Math.atan2(b, a) * 180 / Math.PI,\n];\n```\n\n**TypeScript version**\n\n```ts labToLch.ts\nconst labToLch = (l: number, a: number, b: number): number[] => [\n    l,\n    Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2)),\n    Math.atan2(b, a) * 180 / Math.PI,\n];\n```\n\n## See also\n\n-   [Convert an LCH color to a LAB color](https://phuoc.ng/collection/1-loc/convert-an-lch-color-to-a-lab-color/)\n"
  },
  {
    "path": "contents/convert-a-letter-to-associate-emoji.mdx",
    "content": "---\ncategory: String\ncreated: '2020-08-02'\ntitle: Convert a letter to associate emoji\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js letterToEmoji.js\nconst letterToEmoji = (c) => String.fromCodePoint(c.toLowerCase().charCodeAt(0) + 127365);\n```\n\n**TypeScript version**\n\n```ts letterToEmoji.ts\nconst letterToEmoji = (c: string): string => String.fromCodePoint(c.toLowerCase().charCodeAt(0) + 127365);\n```\n\n**Examples**\n\n```js examples.js\nletterToEmoji('a'); // 🇦\nletterToEmoji('b'); // 🇧\n```\n"
  },
  {
    "path": "contents/convert-a-number-to-equivalent-characters.mdx",
    "content": "---\ncategory: Number\ncreated: '2020-05-27'\ntitle: Convert a number to equivalent characters\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js toChars.js\nconst toChars = (n) => `${n >= 26 ? toChars(Math.floor(n / 26) - 1) : ''}${'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[n % 26]}`;\n```\n\n**TypeScript version**\n\n```ts toChars.ts\nconst toChars = (n: number): string =>\n    `${n >= 26 ? toChars(Math.floor(n / 26) - 1) : ''}${'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[n % 26]}`;\n```\n\n**Examples**\n\n```js examples.js\ntoChars(0); // A\ntoChars(1); // B\ntoChars(25); // Z\n\ntoChars(26); // AA\ntoChars(27); // AB\ntoChars(51); // AZ\n\ntoChars(701); // ZZ\ntoChars(702); // AAA\ntoChars(703); // AAB\n```\n"
  },
  {
    "path": "contents/convert-a-string-to-camel-case.mdx",
    "content": "---\ncategory: String\ncreated: '2020-05-16'\ntitle: Convert a string to camelCase\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js toCamelCase.js\nconst toCamelCase = (str) => str.trim().replace(/[-_\\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''));\n```\n\n**TypeScript version**\n\n```ts toCamelCase.ts\nconst toCamelCase = (str: string): string => str.trim().replace(/[-_\\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''));\n```\n\n**Examples**\n\n```js examples.js\ntoCamelCase('background-color'); // backgroundColor\ntoCamelCase('-webkit-scrollbar-thumb'); // WebkitScrollbarThumb\ntoCamelCase('_hello_world'); // HelloWorld\ntoCamelCase('hello_world'); // helloWorld\n```\n"
  },
  {
    "path": "contents/convert-a-string-to-number.mdx",
    "content": "---\ncategory: Number\ncreated: '2020-04-19'\ntitle: Convert a string to number\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js toNumber.js\nconst toNumber = (str) => +str;\n```\n\n**TypeScript version**\n\n```ts toNumber.ts\nconst toNumber = (str: string): number => +str;\n```\n\n**Examples**\n\n```js examples.js\ntoNumber('42'); // 42\n```\n"
  },
  {
    "path": "contents/convert-a-string-to-pascal-case.mdx",
    "content": "---\ncategory: String\ncreated: '2020-05-15'\ntitle: Convert a string to PascalCase\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js toPascalCase.js\nconst toPascalCase = (str) =>\n    (str.match(/[a-zA-Z0-9]+/g) || []).map((w) => `${w.charAt(0).toUpperCase()}${w.slice(1)}`).join('');\n```\n\n**TypeScript version**\n\n```ts toPascalCase.ts\nconst toPascalCase = (str: string): string =>\n    (str.match(/[a-zA-Z0-9]+/g) || []).map((w) => `${w.charAt(0).toUpperCase()}${w.slice(1)}`).join('');\n```\n\n**Examples**\n\n```js examples.js\ntoPascalCase('hello world'); // 'HelloWorld'\ntoPascalCase('hello.world'); // 'HelloWorld'\ntoPascalCase('foo_bar-baz'); // FooBarBaz\n```\n"
  },
  {
    "path": "contents/convert-a-string-to-url-slug.mdx",
    "content": "---\ncategory: String\ncreated: '2020-05-04'\ntitle: Convert a string to URL slug\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js slugify.js\nconst slugify = (str) =>\n    str\n        .toLowerCase()\n        .replace(/\\s+/g, '-')\n        .replace(/[^\\w-]+/g, '');\n```\n\n**TypeScript version**\n\n```ts slugify.ts\nconst slugify = (str: string): string =>\n    str\n        .toLowerCase()\n        .replace(/\\s+/g, '-')\n        .replace(/[^\\w-]+/g, '');\n```\n\n**Examples**\n\n```js examples.js\nslugify('Chapter One: Once upon a time...'); // 'chapter-one-once-upon-a-time'\n```\n"
  },
  {
    "path": "contents/convert-a-windows-file-path-to-unix-path.mdx",
    "content": "---\ncategory: String\ncreated: '2020-05-15'\ntitle: Convert a Windows file path to Unix path\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js toUnixPath.js\nconst toUnixPath = (path) => path.replace(/[\\\\/]+/g, '/').replace(/^([a-zA-Z]+:|\\.\\/)/, '');\n```\n\n**TypeScript version**\n\n```ts toUnixPath.ts\nconst toUnixPath = (path: string): string => path.replace(/[\\\\/]+/g, '/').replace(/^([a-zA-Z]+:|\\.\\/)/, '');\n```\n\n**Examples**\n\n```js examples.js\ntoUnixPath('./foo/bar/baz'); // foo/bar/baz\ntoUnixPath('C:\\\\foo\\\\bar\\\\baz'); // /foo/bar/baz\n```\n"
  },
  {
    "path": "contents/convert-an-array-of-objects-to-a-single-object.mdx",
    "content": "---\ncategory: Array\ncontributors:\n    - ChoukseyKhushbu\n    - wenyangliu\ncreated: '2020-05-04'\ntitle: Convert an array of objects to a single object\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js toObject.js\nconst toObject = (arr, key) => arr.reduce((a, b) => ({ ...a, [b[key]]: b }), {});\n\n// Or\nconst toObject = (arr, key) => Object.fromEntries(arr.map((it) => [it[key], it]));\n```\n\n**TypeScript version**\n\n```ts toObject.ts\nconst toObject = <T extends Record<string, any>, K extends keyof T>(arr: T[], key: K): Record<string, T> => (\n    arr.reduce((a, b) => ({ ...a, [b[key]]: b }), {})\n);\n\nconst toObject = <T extends Record<string, any>, K extends keyof T>(arr: T[], key: K): Record<string, T> => (\n    Object.fromEntries(arr.map((it) => [it[key], it]))\n);\n```\n\n**Example**\n\n```js example.js\ntoObject(\n    [\n        { id: '1', name: 'Alpha', gender: 'Male' },\n        { id: '2', name: 'Bravo', gender: 'Male' },\n        { id: '3', name: 'Charlie', gender: 'Female' },\n    ],\n    'id'\n);\n/*\n{\n    '1': { id: '1', name: 'Alpha', gender: 'Male' },\n    '2': { id: '2', name: 'Bravo', gender: 'Male' },\n    '3': { id: '3', name: 'Charlie', gender: 'Female' },\n}\n*/\n```\n"
  },
  {
    "path": "contents/convert-an-array-of-strings-to-numbers.mdx",
    "content": "---\ncategory: Array\ncontributors:\n    - jonrandy\ncreated: '2020-04-23'\ntitle: Convert an array of strings to numbers\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js toNumbers.js\nconst toNumbers = (arr) => arr.map(Number);\n\n// Or\nconst toNumbers = (arr) => arr.map((x) => +x);\n```\n\n**TypeScript version**\n\n```ts toNumbers.ts\nconst toNumbers = (arr: string[]): number[] => arr.map(Number);\n\n// Or\nconst toNumbers = (arr: string[]): number[] => arr.map((x) => +x);\n```\n\n**Example**\n\n```js example.js\ntoNumbers(['2', '3', '4']); // [2, 3, 4]\n```\n"
  },
  {
    "path": "contents/convert-an-lch-color-to-a-lab-color.mdx",
    "content": "---\ncategory: Misc\ncreated: '2023-11-10'\nopenGraphCover: /og/1-loc/convert-lch-color-lab-color.png\ntitle: Convert an LCH color to a LAB color\n---\n\n**JavaScript version**\n\n```js lchToLab.js\nconst lchToLab = (l, c, h) => [\n    l,\n    Math.cos(h * Math.PI / 180) * c,\n    Math.sin(h * Math.PI / 180) * c,\n];\n```\n\n**TypeScript version**\n\n```ts lchToLab.ts\nconst lchToLab = (l: number, c: number, h: number): number[] => [\n    l,\n    Math.cos(h * Math.PI / 180) * c,\n    Math.sin(h * Math.PI / 180) * c,\n];\n```\n\n## See also\n\n-   [Convert a LAB color to an LCH color](https://phuoc.ng/collection/1-loc/convert-a-lab-color-to-an-lch-color/)\n"
  },
  {
    "path": "contents/convert-an-uint8-array-to-a-base64-encoded-string.mdx",
    "content": "---\ncategory: String\ncreated: '2021-11-11'\ntitle: Convert an uint8 array to a base64 encoded string\n---\n\n**JavaScript version**\n\n```js uint8ToBase64.js\nconst uint8ToBase64 = (arr) =>\n    btoa(\n        Array(arr.length)\n            .fill('')\n            .map((_, i) => String.fromCharCode(arr[i]))\n            .join('')\n    );\n\n// For Node.js\nconst uint8ToBase64 = (arr) => Buffer.from(arr).toString('base64');\n```\n\n**TypeScript version**\n\n```ts uint8ToBase64.ts\nconst uint8ToBase64 = (arr: Uint8Array): string =>\n    btoa(\n        Array(arr.length)\n            .fill('')\n            .map((_, i) => String.fromCharCode(arr[i]))\n            .join('')\n    );\n\n// For Node.js\nconst uint8ToBase64 = (arr: Uint8Array): string => Buffer.from(arr).toString('base64');\n```\n\n## See also\n\n-   [Convert a base64 encoded string to an uint8 array](https://phuoc.ng/collection/1-loc/convert-a-base64-encoded-string-to-an-uint8-array/)\n"
  },
  {
    "path": "contents/convert-camel-case-to-kebab-case-and-vice-versa.mdx",
    "content": "---\ncategory: String\ncreated: '2020-05-12'\ntitle: 'Convert camelCase to kebab-case and vice versa'\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js kebabToCamel.js\nconst kebabToCamel = (str) => str.replace(/-./g, (m) => m.toUpperCase()[1]);\n\nconst camelToKebab = (str) => str.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();\n```\n\n**TypeScript version**\n\n```ts kebabToCamel.ts\nconst kebabToCamel = (str: string): string => str.replace(/-./g, (m) => m.toUpperCase()[1]);\n\nconst camelToKebab = (str: string): string => str.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();\n```\n\n**Examples**\n\n```js examples.js\nkebabToCamel('background-color'); // 'backgroundColor'\ncamelToKebab('backgroundColor'); // 'background-color'\n```\n"
  },
  {
    "path": "contents/convert-celsius-to-fahrenheit.mdx",
    "content": "---\ncategory: Misc\ncontributors:\n    - mizanmahi\ncreated: '2020-05-09'\ntitle: Convert Celsius to Fahrenheit\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js celsiusToFahrenheit.js\nconst celsiusToFahrenheit = (celsius) => (celsius * 9) / 5 + 32;\n```\n\n**TypeScript version**\n\n```ts celsiusToFahrenheit.ts\nconst celsiusToFahrenheit = (celsius: number): number => (celsius * 9) / 5 + 32;\n```\n\n**Examples**\n\n```js examples.js\ncelsiusToFahrenheit(15); // 59\ncelsiusToFahrenheit(0); // 32\ncelsiusToFahrenheit(-20); // -4\n```\n"
  },
  {
    "path": "contents/convert-cookie-to-object.mdx",
    "content": "---\ncategory: Misc\ncontributors:\n    - João Luís Ribeiro Augusto\ncreated: '2020-06-27'\ntitle: Convert cookie to object\n---\n\n**JavaScript version**\n\n```js cookies.js\nconst cookies = document.cookie\n    .split(';')\n    .map((item) => item.split('='))\n    .reduce((acc, [k, v]) => (acc[k.trim().replace('\"', '')] = v) && acc, {});\n```\n"
  },
  {
    "path": "contents/convert-decimal-to-binary-recursively.mdx",
    "content": "---\ncategory: Number\ncontributors:\n    - philosophercode\ncreated: '2020-12-11'\ntitle: Convert decimal to binary recursively\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js decToBi.js\nconst decToBi = (num) => (num === 0 ? 0 : (num % 2) + 10 * decToBi(~~(num / 2)));\n```\n\n**TypeScript version**\n\n```ts decToBi.ts\nconst decToBi = (num: number): number => (num === 0 ? 0 : (num % 2) + 10 * decToBi(~~(num / 2)));\n```\n\n**Examples**\n\n```js examples.js\ndecToBi(10); //1010\n```\n"
  },
  {
    "path": "contents/convert-degrees-to-radians.mdx",
    "content": "---\ncategory: Math\ncreated: '2020-05-16'\ntitle: Convert degrees to radians\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js degsToRads.js\nconst degsToRads = (deg) => (deg * Math.PI) / 180.0;\n```\n\n**TypeScript version**\n\n```ts degsToRads.ts\nconst degsToRads = (deg: number): number => (deg * Math.PI) / 180.0;\n```\n"
  },
  {
    "path": "contents/convert-fahrenheit-to-celsius.mdx",
    "content": "---\ncategory: Misc\ncreated: '2021-04-08'\ntitle: Convert Fahrenheit to Celsius\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js fahrenheitToCelsius.js\nconst fahrenheitToCelsius = (fahrenheit) => ((fahrenheit - 32) * 5) / 9;\n```\n\n**TypeScript version**\n\n```ts fahrenheitToCelsius.ts\nconst fahrenheitToCelsius = (fahrenheit: number): number => ((fahrenheit - 32) * 5) / 9;\n```\n\n**Examples**\n\n```js examples.js\nfahrenheitToCelsius(59); // 15\nfahrenheitToCelsius(32); // 0\n```\n"
  },
  {
    "path": "contents/convert-hex-to-rgb.mdx",
    "content": "---\ncategory: Misc\ncreated: '2020-04-19'\ntitle: Convert hex to rgb\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js hexToRgb.js\nconst hexToRgb = (hex) =>\n    hex\n        .replace(/^#?([a-f\\d])([a-f\\d])([a-f\\d])$/i, (_, r, g, b) => `#${r}${r}${g}${g}${b}${b}`)\n        .substring(1)\n        .match(/.{2}/g)\n        .map((x) => parseInt(x, 16));\n```\n\n**TypeScript version**\n\n```ts hexToRgb.ts\nconst hexToRgb = (hex: string): string =>\n    hex\n        .replace(/^#?([a-f\\d])([a-f\\d])([a-f\\d])$/i, (_, r, g, b) => `#${r}${r}${g}${g}${b}${b}`)\n        .substring(1)\n        .match(/.{2}/g)\n        .map((x) => parseInt(x, 16));\n```\n\n**Examples**\n\n```js examples.js\nhexToRgb('#00ffff'); // [0, 255, 255]\nhexToRgb('#0ff'); // [0, 255, 255]\n```\n\n## See also\n\n-   [Convert rgb color to hex](https://phuoc.ng/collection/1-loc/convert-rgb-color-to-hex/)\n-   [Create an RGB to HEX color converter](https://phuoc.ng/collection/react-drag-drop/create-an-rgb-to-hex-color-converter/)\n"
  },
  {
    "path": "contents/convert-radians-to-degrees.mdx",
    "content": "---\ncategory: Math\ncreated: '2021-04-05'\ntitle: Convert radians to degrees\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js radsToDegs.js\nconst radsToDegs = (rad) => (rad * 180) / Math.PI;\n```\n\n**TypeScript version**\n\n```ts radsToDegs.ts\nconst radsToDegs = (rad: number): number => (rad * 180) / Math.PI;\n```\n"
  },
  {
    "path": "contents/convert-rgb-color-to-hex.mdx",
    "content": "---\ncategory: Misc\ncreated: '2020-04-19'\ntitle: Convert rgb color to hex\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js rgbToHex.js\nconst rgbToHex = (red, green, blue) => `#${((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1)}`;\n\n// Or\nconst rgbToHex = (red, green, blue) => `#${[red, green, blue].map((v) => v.toString(16).padStart(2, '0')).join('')}`;\n```\n\n**TypeScript version**\n\n```ts rgbToHex.ts\nconst rgbToHex = (red: number, green: number, blue: number): string =>\n    `#${((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1)}`;\n\n// Or\nconst rgbToHex = (red: number, green: number, blue: number): string =>\n    `#${[red, green, blue].map((v) => v.toString(16).padStart(2, '0')).join('')}`;\n```\n\n**Examples**\n\n```js examples.js\nrgbToHex(0, 255, 255); // '#00ffff'\n```\n\n## See also\n\n-   [Convert hex to rgb](https://phuoc.ng/collection/1-loc/convert-hex-to-rgb/)\n-   [Create an RGB to HEX color converter](https://phuoc.ng/collection/react-drag-drop/create-an-rgb-to-hex-color-converter/)\n"
  },
  {
    "path": "contents/convert-seconds-to-hh-mm-ss-format.mdx",
    "content": "---\ncategory: Date Time\ncreated: '2020-05-15'\ntitle: 'Convert seconds to hh:mm:ss format'\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js formatSeconds.js\n// `s` is number of seconds\nconst formatSeconds = (s) => new Date(s * 1000).toISOString().substr(11, 8);\n\n// Or\nconst formatSeconds = (s) => new Date(s * 1000).toUTCString().match(/(\\d\\d:\\d\\d:\\d\\d)/)[0];\n\n// Or\nconst formatSeconds = (s) =>\n    [parseInt(s / 60 / 60), parseInt((s / 60) % 60), parseInt(s % 60)].join(':').replace(/\\b(\\d)\\b/g, '0$1');\n```\n\n**TypeScript version**\n\n```ts formatSeconds.ts\nconst formatSeconds = (s: number): string => new Date(s * 1000).toISOString().substr(11, 8);\n\n// Or\nconst formatSeconds = (s: number): string => (new Date(s * 1000).toUTCString().match(/(\\d\\d:\\d\\d:\\d\\d)/) as string[])[0];\n\n// Or\nconst formatSeconds = (s: number): string => (\n    [parseInt(`${s / 3600}`), parseInt(`${(s / 60) % 60}`), parseInt(`${s % 60}`)].join(':').replace(/\\b(\\d)\\b/g, '0$1')\n);\n```\n\n**Examples**\n\n```js examples.js\nformatSeconds(200); // 00:03:20\nformatSeconds(500); // 00:08:20\n```\n"
  },
  {
    "path": "contents/convert-snake-case-to-camel-case.mdx",
    "content": "---\ncategory: String\ncreated: '2020-05-12'\ntitle: 'Convert snake_case to camelCase'\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js snakeToCamel.js\nconst snakeToCamel = (str) => str.toLowerCase().replace(/(_\\w)/g, (m) => m.toUpperCase().substr(1));\n```\n\n**TypeScript version**\n\n```ts snakeToCamel.ts\nconst snakeToCamel = (str: string): string => str.toLowerCase().replace(/(_\\w)/g, (m) => m.toUpperCase().substr(1));\n```\n\n**Examples**\n\n```js examples.js\nsnakeToCamel('HELLO_world'); // 'helloWorld'\n```\n"
  },
  {
    "path": "contents/convert-the-name-of-an-excel-column-to-number.mdx",
    "content": "---\ncategory: String\ncreated: '2020-05-25'\ntitle: Convert the name of an Excel column to number\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js getIndex.js\nconst getIndex = (col) => col.split('').reduce((prev, next) => prev * 26 + parseInt(next, 36) - 9, 0);\n```\n\n**TypeScript version**\n\n```ts getIndex.ts\nconst getIndex = (col: string): number => col.split('').reduce((prev, next) => prev * 26 + parseInt(next, 36) - 9, 0);\n```\n\n**Examples**\n\n```js examples.js\ngetIndex('A'); // 1\ngetIndex('B'); // 2\ngetIndex('C'); // 3\ngetIndex('Z'); // 26\n\ngetIndex('AA'); // 27\ngetIndex('AB'); // 28\ngetIndex('AC'); // 29\ngetIndex('AZ'); // 52\n\ngetIndex('AAA'); // 703\ngetIndex('AAB'); // 704\n```\n"
  },
  {
    "path": "contents/convert-url-parameters-to-object.mdx",
    "content": "---\ncategory: Misc\ncreated: '2021-02-01'\ntitle: Convert URL parameters to object\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js getUrlParams.js\nconst getUrlParams = (query) =>\n    Array.from(new URLSearchParams(query)).reduce(\n        (p, [k, v]) => Object.assign({}, p, { [k]: p[k] ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v }),\n        {}\n    );\n```\n\n**TypeScript version**\n\n```ts getUrlParams.ts\nconst getUrlParams = (query: string): Record<string, string> => (\n    Array.from(new URLSearchParams(query)).reduce((p, [k, v]) => Object.assign({}, p, { [k]: p[k] ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v }), {} as Record<string, string>)\n);\n```\n\n**Examples**\n\n```js examples.js\ngetUrlParams(location.search); // Get the parameters of the current URL\n\ngetUrlParams('foo=Foo&bar=Bar'); // { foo: \"Foo\", bar: \"Bar\" }\n\n// Duplicate key\ngetUrlParams('foo=Foo&foo=Fuzz&bar=Bar'); // { foo: [\"Foo\", \"Fuzz\"], bar: \"Bar\" }\n```\n"
  },
  {
    "path": "contents/count-by-the-properties-of-an-array-of-objects.mdx",
    "content": "---\ncategory: Array\ncreated: '2020-06-14'\ntitle: Count by the properties of an array of objects\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js countBy.js\nconst countBy = (arr, prop) => arr.reduce((prev, curr) => ((prev[curr[prop]] = ++prev[curr[prop]] || 1), prev), {});\n```\n\n**TypeScript version**\n\n```ts countBy.ts\nconst countBy = <T extends Record<string, string>, K extends keyof T>(arr: T[], prop: K): Record<string, number> => (\n    arr.reduce((prev, curr) => ((prev[curr[prop]] = ++prev[curr[prop]] || 1), prev), {} as Record<string, number>)\n);\n```\n\n**Example**\n\n```js example.js\ncountBy(\n    [\n        { branch: 'audi', model: 'q8', year: '2019' },\n        { branch: 'audi', model: 'rs7', year: '2020' },\n        { branch: 'ford', model: 'mustang', year: '2019' },\n        { branch: 'ford', model: 'explorer', year: '2020' },\n        { branch: 'bmw', model: 'x7', year: '2020' },\n    ],\n    'branch'\n);\n\n// { 'audi': 2, 'ford': 2, 'bmw': 1 }\n```\n"
  },
  {
    "path": "contents/count-the-number-of-words-in-a-string.mdx",
    "content": "---\ncategory: String\ncreated: '2021-05-26'\ntitle: Count the number of words in a string\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js countWords.js\nconst countWords = (str) => str.trim().split(/\\s+/).length;\n```\n\n**TypeScript version**\n\n```ts countWords.ts\nconst countWords = (str: string): number => str.trim().split(/\\s+/).length;\n```\n\n**Examples**\n\n```js examples.js\ncountWords('Hello World'); // 2\ncountWords('Hello    World'); // 2\ncountWords('  Hello  World  '); // 2\n```\n"
  },
  {
    "path": "contents/count-the-occurrences-of-a-character-in-a-string.mdx",
    "content": "---\ncategory: String\ncreated: '2021-04-19'\ntitle: Count the occurrences of a character in a string\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js countOccurrences.js\nconst countOccurrences = (str, char) => [...str].reduce((a, v) => (v === char ? a + 1 : a), 0);\n\n// Or\nconst countOccurrences = (str, char) => str.split('').reduce((a, v) => (v === char ? a + 1 : a), 0);\n\n// Or\nconst countOccurrences = (str, char) => [...str].filter((item) => item === char).length;\n\n// Or\nconst countOccurrences = (str, char) => str.split('').filter((item) => item === char).length;\n```\n\n**TypeScript version**\n\n```ts countOccurrences.ts\nconst countOccurrences = (str: string, char: string): number => [...str].reduce((a, v) => (v === char ? a + 1 : a), 0);\n\n// Or\nconst countOccurrences = (str: string, char: string): number =>\n    str.split('').reduce((a, v) => (v === char ? a + 1 : a), 0);\n\n// Or\nconst countOccurrences = (str: string, char: string): number => [...str].filter((item) => item === char).length;\n\n// Or\nconst countOccurrences = (str: string, char: string): number => str.split('').filter((item) => item === char).length;\n```\n\n**Examples**\n\n```js examples.js\ncountOccurrences('a.b.c.d.e', '.'); // 4\n```\n"
  },
  {
    "path": "contents/count-the-occurrences-of-a-value-in-an-array.mdx",
    "content": "---\ncategory: Array\ncreated: '2020-06-11'\ntitle: Count the occurrences of a value in an array\nupdated: '2021-10-22'\n---\n\n**JavaScript version**\n\n```js countOccurrences.js\nconst countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);\n\n// Or\nconst countOccurrences = (arr, val) => arr.filter((item) => item === val).length;\n```\n\n**TypeScript version**\n\n```ts countOccurrences.ts\nconst countOccurrences = <T,_>(arr: T[], val: T): number => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);\n\n// Or\nconst countOccurrences = <T,_>(arr: T[], val: T): number => arr.filter((item) => item === val).length;\n```\n\n**Examples**\n\n```js examples.js\ncountOccurrences([2, 1, 3, 3, 2, 3], 2); // 2\ncountOccurrences(['a', 'b', 'a', 'c', 'a', 'b'], 'a'); // 3\n```\n"
  },
  {
    "path": "contents/count-the-occurrences-of-array-elements.mdx",
    "content": "---\ncategory: Array\ncreated: '2020-06-11'\ntitle: Count the occurrences of array elements\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js countOccurrences.js\nconst countOccurrences = (arr) => arr.reduce((prev, curr) => ((prev[curr] = ++prev[curr] || 1), prev), {});\n```\n\n**TypeScript version**\n\n```ts countOccurrences.ts\nconst countOccurrences = <T extends string | number,>(arr: T[]): Record<T, number> => (\n    arr.reduce((prev, curr) => ((prev[curr] = ++prev[curr] || 1), prev), {}as Record<T, number>)\n);\n```\n\n**Examples**\n\n```js examples.js\ncountOccurrences([2, 1, 3, 3, 2, 3]); // { '1': 1, '2': 2, '3': 3 }\ncountOccurrences(['a', 'b', 'a', 'c', 'a', 'b']); // { 'a': 3, 'b': 2, 'c': 1 }\n```\n"
  },
  {
    "path": "contents/create-a-function-that-accepts-a-single-argument.mdx",
    "content": "---\ncategory: Function\ncreated: '2021-03-13'\ntitle: Create a function that accepts a single argument\n---\n\n**JavaScript version**\n\n```js unary.js\nconst unary = (fn) => (arg) => fn(arg);\n```\n\n**Examples**\n\n```js examples.js\n['1', '2', '3', '4', '5'].map(unary(parseInt)); // [1, 2, 3, 4, 5]\n```\n"
  },
  {
    "path": "contents/create-an-array-of-cumulative-sum.mdx",
    "content": "---\ncategory: Array\ncreated: '2020-04-19'\ntitle: Create an array of cumulative sum\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js accumulate.js\nconst accumulate = (arr) =>\n    arr.map(\n        (\n            (sum) => (value) =>\n                (sum += value)\n        )(0)\n    );\n\n// Or\nconst accumulate = (arr) => arr.reduce((a, b, i) => (i === 0 ? [b] : [...a, b + a[i - 1]]), [0]);\n```\n\n**TypeScript version**\n\n```ts accumulate.ts\nconst accumulate = (arr: number[]): number[] =>\n    arr.map(\n        (\n            (sum) => (value: number) =>\n                (sum += value)\n        )(0)\n    );\n\n// Or\nconst accumulate = (arr: number[]): number[] => arr.reduce((a, b, i) => (i === 0 ? [b] : [...a, b + a[i - 1]]), [0]);\n```\n\n**Example**\n\n```js example.js\naccumulate([1, 2, 3, 4]); // [1, 3, 6, 10]\n// 1             = 1\n// 1 + 2         = 3\n// 1 + 2 + 3     = 6\n// 1 + 2 + 3 + 4 = 10\n```\n"
  },
  {
    "path": "contents/create-an-array-of-numbers-in-the-given-range.mdx",
    "content": "---\ncategory: Array\ncontributors:\n    - jonrandy\n    - Augusto Moura\n    - Tsvika10\ncreated: '2020-04-19'\ntitle: Create an array of numbers in the given range\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js range.js\nconst range = (min, max) => [...Array(max - min + 1).keys()].map((i) => i + min);\n\n// Or\nconst range = (min, max) =>\n    Array(max - min + 1)\n        .fill(0)\n        .map((_, i) => min + i);\n\n// Or\nconst range = (min, max) => Array.from({ length: max - min + 1 }, (_, i) => min + i);\n```\n\n**TypeScript version**\n\n```ts range.ts\nconst range = (min: number, max: number): number[] => [...Array(max - min + 1).keys()].map((i) => i + min);\n\n// Or\nconst range = (min: number, max: number): number[] =>\n    Array(max - min + 1)\n        .fill(0)\n        .map((_, i) => min + i);\n\n// Or\nconst range = (min: number, max: number): number[] => Array.from({ length: max - min + 1 }, (_, i) => min + i);\n```\n\n**Example**\n\n```js example.js\nrange(5, 10); // [5, 6, 7, 8, 9, 10]\n```\n"
  },
  {
    "path": "contents/create-an-empty-function.mdx",
    "content": "---\ncategory: Function\ncontributors:\n    - jnields\n    - naugtur\ncreated: '2020-05-07'\ntitle: Create an empty function\nupdated: '2020-05-27'\n---\n\n**JavaScript version**\n\n```js noop.js\nconst noop = () => {};\n\n// Or\nconst noop = Function();\n// calling Function() might be detected as using eval by some security tools\n```\n"
  },
  {
    "path": "contents/create-an-empty-map-that-does-not-have-properties.mdx",
    "content": "---\ncategory: Object\ncreated: '2020-04-19'\ntitle: Create an empty map that does not have properties\n---\n\n**JavaScript version**\n\n```js map.js\n// `map` doesn't have any properties\nconst map = Object.create(null);\n\n// The following `map` has `__proto__` property\n// const map = {};\n```\n"
  },
  {
    "path": "contents/create-an-object-from-the-pairs-of-key-and-value.mdx",
    "content": "---\ncategory: Object\ncontributors:\n    - robinpokorny\ncreated: '2020-05-18'\ntitle: Create an object from the pairs of key and value\nupdated: '2020-05-20'\n---\n\n**JavaScript version**\n\n```js toObj.js\nconst toObj = (arr) => Object.fromEntries(arr);\n\n// Or\nconst toObj = (arr) => arr.reduce((a, c) => ((a[c[0]] = c[1]), a), {});\n```\n\n**Examples**\n\n```js examples.js\ntoObj([\n    ['a', 1],\n    ['b', 2],\n    ['c', 3],\n]); // { a: 1, b: 2, c: 3 }\n```\n"
  },
  {
    "path": "contents/create-cartesian-product.mdx",
    "content": "---\ncategory: Array\ncontributors:\n    - robinpokorny\ncreated: '2020-12-02'\ntitle: Create cartesian product\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js cartesian.js\nconst cartesian = (...sets) => sets.reduce((acc, set) => acc.flatMap((x) => set.map((y) => [...x, y])), [[]]);\n```\n\n**Example**\n\n```js example.js\ncartesian([1, 2], [3, 4]); // [ [1, 3], [1, 4], [2, 3], [2, 4] ]\n\n/*\n       3       4\n   ---------------\n1 | [1, 3]  [1, 4]\n  |\n2 | [2, 3]  [2, 4]\n\n*/\n```\n"
  },
  {
    "path": "contents/curry-a-function.mdx",
    "content": "---\ncategory: Function\ncreated: '2020-05-15'\ntitle: Curry a function\n---\n\n**JavaScript version**\n\n```js curry.js\nconst curry = (fn, ...args) => (fn.length <= args.length ? fn(...args) : curry.bind(null, fn, ...args));\n```\n\n**Examples**\n\n```js examples.js\nconst sum = (a, b, c) => a + b + c;\ncurry(sum)(1)(2)(3); // 6\ncurry(sum)(1, 2, 3); // 6\ncurry(sum, 1)(2, 3); // 6\ncurry(sum, 1)(2)(3); // 6\ncurry(sum, 1, 2)(3); // 6\ncurry(sum, 1, 2, 3); // 6\n```\n"
  },
  {
    "path": "contents/decapitalize-a-string.mdx",
    "content": "---\ncategory: String\ncreated: '2021-02-21'\ntitle: Decapitalize a string\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js decapitalize.js\nconst decapitalize = (str) => `${str.charAt(0).toLowerCase()}${str.slice(1)}`;\n\n// Or\nconst decapitalize = ([first, ...rest]) => `${first.toLowerCase()}${rest.join('')}`;\n```\n\n**TypeScript version**\n\n```ts decapitalize.ts\nconst decapitalize = (str: string): string => `${str.charAt(0).toLowerCase()}${str.slice(1)}`;\n\n// Or\nconst decapitalize = ([first, ...rest]: string): string => `${first.toLowerCase()}${rest.join('')}`;\n```\n\n**Examples**\n\n```js examples.js\ndecapitalize('Hello world'); // 'hello world'\n```\n"
  },
  {
    "path": "contents/decode-a-jwt-token.mdx",
    "content": "---\ncategory: Misc\ncreated: '2020-05-23'\ntitle: Decode a JWT token\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js decode.js\nconst decode = (token) =>\n    decodeURIComponent(\n        atob(token.split('.')[1].replace('-', '+').replace('_', '/'))\n            .split('')\n            .map((c) => `%${('00' + c.charCodeAt(0).toString(16)).slice(-2)}`)\n            .join('')\n    );\n```\n\n**TypeScript version**\n\n```ts decode.ts\nconst decode = (token: string): string =>\n    decodeURIComponent(\n        atob(token.split('.')[1].replace('-', '+').replace('_', '/'))\n            .split('')\n            .map((c) => `%${('00' + c.charCodeAt(0).toString(16)).slice(-2)}`)\n            .join('')\n    );\n```\n\n**Examples**\n\n```js examples.js\ndecode(`\n    eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.\n    eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0I\n    joxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c\n`);\n\n// { \"sub\": \"1234567890\", \"name\": \"John Doe\", \"iat\": 1516239022 }\n```\n"
  },
  {
    "path": "contents/decode-html-entities.mdx",
    "content": "---\ncategory: String\ncreated: '2022-08-21'\ntitle: Decode HTML entities\n---\n\n**JavaScript version**\n\n```js decodeHtmlEntities.js\nconst decodeHtmlEntities = (str) => str.replace(/&#(\\w+)(^\\w|;)?/g, (_, dec) => String.fromCharCode(dec));\n```\n\n**TypeScript version**\n\n```ts decodeHtmlEntities.ts\nconst decodeHtmlEntities = (str: string): string =>\n    str.replace(/&#(\\w+)(^\\w|;)?/g, (_, dec) => String.fromCharCode(dec));\n```\n"
  },
  {
    "path": "contents/delay-the-evaluation-of-a-function.mdx",
    "content": "---\ncategory: Function\ncreated: '2020-05-12'\ntitle: Delay the evaluation of a function\n---\n\n**JavaScript version**\n\n```js thunkfy.js\n// returns a new version of `fn` that returns values as lazy evaluable\nconst thunkfy =\n    (fn) =>\n    (...args) =>\n    () =>\n        fn(...args);\n```\n\n**Examples**\n\n```js examples.js\nconst heavyComputation = (x) => doStuff(x);\nconst unnecessarySlow = manyThings.map(heavyComputation).find((result) => result.criteria);\nconst probablyFaster = manyThings.map(thunkfy(heavyComputation)).find((thunk) => thunk().criteria);\n```\n"
  },
  {
    "path": "contents/detect-dark-mode.mdx",
    "content": "---\ncategory: Misc\ncreated: '2020-05-02'\ntitle: Detect dark mode\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isDarkMode.js\nconst isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;\n```\n\n**TypeScript version**\n\n```ts isDarkMode.ts\nconst isDarkMode: boolean = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;\n```\n"
  },
  {
    "path": "contents/detect-internet-explorer-browser.mdx",
    "content": "---\ncategory: DOM\ncreated: '2020-05-09'\ntitle: Detect Internet Explorer browser\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isIE.js\nconst isIE = !!document.documentMode;\n```\n\n**TypeScript version**\n\n```ts isIE.ts\nconst isIE = !!(document as any).documentMode;\n```\n"
  },
  {
    "path": "contents/detect-macos-browser.mdx",
    "content": "---\ncategory: DOM\ncreated: '2020-04-19'\ntitle: Detect macOS browser\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js isMacBrowser.js\nconst isMacBrowser = /Mac|iPod|iPhone|iPad/.test(navigator.platform);\n```\n\n**TypeScript version**\n\n```ts isMacBrowser.ts\nconst isMacBrowser: boolean = /Mac|iPod|iPhone|iPad/.test(navigator.platform);\n```\n"
  },
  {
    "path": "contents/determine-one-year-from-now.mdx",
    "content": "---\ncategory: Date Time\ncreated: '2022-08-21'\ntitle: Determine one year from now\n---\n\n**JavaScript version**\n\n```js plusOneYear.js\nconst plusOneYear = ((d) => new Date(d.setFullYear(d.getFullYear() + 1)))(new Date());\n```\n\n**TypeScript version**\n\n```ts plusOneYear.ts\nconst plusOneYear: Date = ((d) => new Date(d.setFullYear(d.getFullYear() + 1)))(new Date());\n```\n\n## See also\n\n-   [Get the tomorrow date](https://phuoc.ng/collection/1-loc/get-the-tomorrow-date/)\n-   [Get the yesterday date](https://phuoc.ng/collection/1-loc/get-the-yesterday-date/)\n"
  },
  {
    "path": "contents/easing-functions.mdx",
    "content": "---\ncategory: Misc\ncreated: '2020-04-25'\ntitle: Easing functions\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js\n// Some easing functions\n// See https://gist.github.com/gre/1650294 and https://easings.net\n\nconst linear = (t) => t;\n\nconst easeInQuad = (t) => t * t;\nconst easeOutQuad = (t) => t * (2 - t);\nconst easeInOutQuad = (t) => (t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t);\n\nconst easeInCubic = (t) => t * t * t;\nconst easeOutCubic = (t) => --t * t * t + 1;\nconst easeInOutCubic = (t) => (t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1);\n\nconst easeInQuart = (t) => t * t * t * t;\nconst easeOutQuart = (t) => 1 - --t * t * t * t;\nconst easeInOutQuart = (t) => (t < 0.5 ? 8 * t * t * t * t : 1 - 8 * --t * t * t * t);\n\nconst easeInQuint = (t) => t * t * t * t * t;\nconst easeOutQuint = (t) => 1 + --t * t * t * t * t;\nconst easeInOutQuint = (t) => (t < 0.5 ? 16 * t * t * t * t * t : 1 + 16 * --t * t * t * t * t);\n\nconst easeInSine = (t) => 1 + Math.sin((Math.PI / 2) * t - Math.PI / 2);\nconst easeOutSine = (t) => Math.sin((Math.PI / 2) * t);\nconst easeInOutSine = (t) => (1 + Math.sin(Math.PI * t - Math.PI / 2)) / 2;\n\nconst easeInElastic = (t) => (0.04 - 0.04 / t) * Math.sin(25 * t) + 1;\nconst easeOutElastic = (t) => ((0.04 * t) / --t) * Math.sin(25 * t);\nconst easeInOutElastic = (t) =>\n    (t -= 0.5) < 0 ? (0.02 + 0.01 / t) * Math.sin(50 * t) : (0.02 - 0.01 / t) * Math.sin(50 * t) + 1;\n```\n\n**TypeScript version**\n\n```ts linear.ts\nconst linear = (t: number): number => t;\n\nconst easeInQuad = (t: number): number => t * t;\nconst easeOutQuad = (t: number): number => t * (2 - t);\nconst easeInOutQuad = (t: number): number => (t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t);\n\nconst easeInCubic = (t: number): number => t * t * t;\nconst easeOutCubic = (t: number): number => --t * t * t + 1;\nconst easeInOutCubic = (t: number): number => (t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1);\n\nconst easeInQuart = (t: number): number => t * t * t * t;\nconst easeOutQuart = (t: number): number => 1 - --t * t * t * t;\nconst easeInOutQuart = (t: number): number => (t < 0.5 ? 8 * t * t * t * t : 1 - 8 * --t * t * t * t);\n\nconst easeInQuint = (t: number): number => t * t * t * t * t;\nconst easeOutQuint = (t: number): number => 1 + --t * t * t * t * t;\nconst easeInOutQuint = (t: number): number => (t < 0.5 ? 16 * t * t * t * t * t : 1 + 16 * --t * t * t * t * t);\n\nconst easeInSine = (t: number): number => 1 + Math.sin((Math.PI / 2) * t - Math.PI / 2);\nconst easeOutSine = (t: number): number => Math.sin((Math.PI / 2) * t);\nconst easeInOutSine = (t: number): number => (1 + Math.sin(Math.PI * t - Math.PI / 2)) / 2;\n\nconst easeInElastic = (t: number): number => (0.04 - 0.04 / t) * Math.sin(25 * t) + 1;\nconst easeOutElastic = (t: number): number => ((0.04 * t) / --t) * Math.sin(25 * t);\nconst easeInOutElastic = (t: number): number =>\n    (t -= 0.5) < 0 ? (0.02 + 0.01 / t) * Math.sin(50 * t) : (0.02 - 0.01 / t) * Math.sin(50 * t) + 1;\n```\n"
  },
  {
    "path": "contents/empty-an-array.mdx",
    "content": "---\ncategory: Array\ncreated: '2020-04-19'\ntitle: Empty an array\nupdated: '2021-10-22'\n---\n\n**JavaScript version**\n\n```js empty.js\nconst empty = (arr) => (arr.length = 0);\n\n// Or\narr = [];\n```\n\n**TypeScript version**\n\n```ts empty.ts\nconst empty = <T,_>(arr: T[]) => (arr.length = 0);\n\n// Or\narr = [];\n```\n"
  },
  {
    "path": "contents/emulate-a-dice-throw.mdx",
    "content": "---\ncategory: Misc\ncontributors:\n    - codepo8\ncreated: '2020-05-01'\ntitle: Emulate a dice throw\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js throwdice.js\nconst throwdice = () => ~~(Math.random() * 6) + 1;\n```\n\n**TypeScript version**\n\n```ts throwdice.ts\nconst throwdice = (): number => ~~(Math.random() * 6) + 1;\n```\n\n**Examples**\n\n```js examples.js\nthrowdice(); // 4\nthrowdice(); // 1\nthrowdice(); // 6\n```\n"
  },
  {
    "path": "contents/encode-a-url.mdx",
    "content": "---\ncategory: Misc\ncreated: '2020-05-03'\ntitle: Encode a URL\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js encode.js\n// `encodeURIComponent` doesn't encode -_.!~*'()\nconst encode = (url) =>\n    encodeURIComponent(url)\n        .replace(/!/g, '%21')\n        .replace(/~/g, '%7E')\n        .replace(/\\*/g, '%2A')\n        .replace(/'/g, '%27')\n        .replace(/\\(/g, '%28')\n        .replace(/\\)/g, '%29')\n        .replace(/%20/g, '+');\n```\n\n**TypeScript version**\n\n```ts encode.ts\nconst encode = (url: string): string =>\n    encodeURIComponent(url)\n        .replace(/!/g, '%21')\n        .replace(/~/g, '%7E')\n        .replace(/\\*/g, '%2A')\n        .replace(/'/g, '%27')\n        .replace(/\\(/g, '%28')\n        .replace(/\\)/g, '%29')\n        .replace(/%20/g, '+');\n```\n"
  },
  {
    "path": "contents/escape-html-special-characters.mdx",
    "content": "---\ncategory: String\ncreated: '2020-05-29'\ntitle: Escape HTML special characters\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js escape.js\nconst escape = (str) =>\n    str\n        .replace(/&/g, '&amp;')\n        .replace(/</g, '&lt;')\n        .replace(/>/g, '&gt;')\n        .replace(/'/g, '&#39;')\n        .replace(/\"/g, '&quot;');\n\n// Or\nconst escape = (str) =>\n    str.replace(/[&<>\"']/g, (m) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;', \"'\": '&#39;' }[m]));\n```\n\n**TypeScript version**\n\n```ts escape.ts\nconst escape = (str: string): string =>\n    str\n        .replace(/&/g, '&amp;')\n        .replace(/</g, '&lt;')\n        .replace(/>/g, '&gt;')\n        .replace(/'/g, '&#39;')\n        .replace(/\"/g, '&quot;');\n\n// Or\nconst escape = (str: string): string =>\n    str.replace(/[&<>\"']/g, (m) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;', \"'\": '&#39;' }[m]));\n```\n"
  },
  {
    "path": "contents/execute-a-function-once.mdx",
    "content": "---\ncategory: Function\ncreated: '2020-05-13'\ntitle: Execute a function once\n---\n\n**JavaScript version**\n\n```js once.js\nconst once = (fn) =>\n    (\n        (ran = false) =>\n        () =>\n            ran ? fn : ((ran = !ran), (fn = fn()))\n    )();\n```\n\n**Examples**\n\n```js examples.js\nlet n = 0;\nconst incOnce = once(() => ++n);\nincOnce(); // n = 1\nincOnce(); // n = 1\nincOnce(); // n = 1\n```\n"
  },
  {
    "path": "contents/extract-values-of-a-property-from-an-array-of-objects.mdx",
    "content": "---\ncategory: Object\ncreated: '2020-06-02'\ntitle: Extract values of a property from an array of objects\n---\n\n**JavaScript version**\n\n```js pluck.js\nconst pluck = (objs, property) => objs.map((obj) => obj[property]);\n```\n\n**Examples**\n\n```js examples.js\npluck(\n    [\n        { name: 'John', age: 20 },\n        { name: 'Smith', age: 25 },\n        { name: 'Peter', age: 30 },\n    ],\n    'name'\n); // ['John', 'Smith', 'Peter']\n```\n"
  },
  {
    "path": "contents/extract-year-month-day-hour-minute-second-and-millisecond-from-a-date.mdx",
    "content": "---\ncategory: Date Time\ncreated: '2020-04-19'\ntitle: 'Extract year, month, day, hour, minute, second and millisecond from a date'\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js extract.js\n// `date` is a `Date` object\nconst extract = (date) =>\n    date\n        .toISOString()\n        .split(/[^0-9]/)\n        .slice(0, -1);\n\n// `extract` is an array of [year, month, day, hour, minute, second, millisecond]\n```\n\n**TypeScript version**\n\n```ts extract.ts\nconst extract = (date: Date): string[] =>\n    date\n        .toISOString()\n        .split(/[^0-9]/)\n        .slice(0, -1);\n```\n"
  },
  {
    "path": "contents/find-the-closest-number-from-an-array.mdx",
    "content": "---\ncategory: Array\ncreated: '2020-05-22'\ntitle: Find the closest number from an array\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js closest.js\n// Find the number from `arr` which is closest to `n`\nconst closest = (arr, n) => arr.reduce((prev, curr) => (Math.abs(curr - n) < Math.abs(prev - n) ? curr : prev));\n\n// Or\nconst closest = (arr, n) => arr.sort((a, b) => Math.abs(a - n) - Math.abs(b - n))[0];\n```\n\n**TypeScript version**\n\n```ts closest.ts\nconst closest = (arr: number[], n: number): number =>\n    arr.reduce((prev, curr) => (Math.abs(curr - n) < Math.abs(prev - n) ? curr : prev));\n\n// Or\nconst closest = (arr: number[], n: number): number => arr.sort((a, b) => Math.abs(a - n) - Math.abs(b - n))[0];\n```\n\n**Example**\n\n```js example.js\nclosest([29, 87, 8, 78, 97, 20, 75, 33, 24, 17], 50); // 33\n```\n"
  },
  {
    "path": "contents/find-the-index-of-the-last-matching-item-of-an-array.mdx",
    "content": "---\ncategory: Array\ncreated: '2020-12-31'\ntitle: Find the index of the last matching item of an array\nupdated: '2021-10-22'\n---\n\n**JavaScript version**\n\n```js lastIndex.js\nconst lastIndex = (arr, predicate) => arr.reduce((prev, curr, index) => (predicate(curr) ? index : prev), -1);\n\n// Or\nconst lastIndex = (arr, predicate) => arr.map((item) => predicate(item)).lastIndexOf(true);\n```\n\n**TypeScript version**\n\n```ts lastIndex.ts\nconst lastIndex = <T,_>(arr: T[], predicate: (a: T) => boolean): number => arr.reduce((prev, curr, index) => (predicate(curr) ? index : prev), -1);\n\n// Or\nconst lastIndex = <T,_>(arr: T[], predicate: (a: T) => boolean): number => arr.map((item) => predicate(item)).lastIndexOf(true);\n```\n\n**Examples**\n\n```js examples.js\nlastIndex([1, 3, 5, 7, 9, 2, 4, 6, 8], (i) => i % 2 === 1); // 4\nlastIndex([1, 3, 5, 7, 9, 8, 6, 4, 2], (i) => i > 6); // 5\n```\n"
  },
  {
    "path": "contents/find-the-index-of-the-maximum-item-of-an-array.mdx",
    "content": "---\ncategory: Array\ncreated: '2021-04-20'\ntitle: Find the index of the maximum item of an array\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js indexOfMax.js\nconst indexOfMax = (arr) => arr.reduce((prev, curr, i, a) => (curr > a[prev] ? i : prev), 0);\n```\n\n**TypeScript version**\n\n```ts indexOfMax.ts\nconst indexOfMax = (arr: number[]): number => arr.reduce((prev, curr, i, a) => (curr > a[prev] ? i : prev), 0);\n```\n\n**Examples**\n\n```js examples.js\nindexOfMax([1, 3, 9, 7, 5]); // 2\nindexOfMax([1, 3, 7, 7, 5]); // 2\n```\n"
  },
  {
    "path": "contents/find-the-index-of-the-minimum-item-of-an-array.mdx",
    "content": "---\ncategory: Array\ncreated: '2021-04-20'\ntitle: Find the index of the minimum item of an array\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js indexOfMin.js\nconst indexOfMin = (arr) => arr.reduce((prev, curr, i, a) => (curr < a[prev] ? i : prev), 0);\n```\n\n**TypeScript version**\n\n```ts indexOfMin.ts\nconst indexOfMin = (arr: number[]): number => arr.reduce((prev, curr, i, a) => (curr < a[prev] ? i : prev), 0);\n```\n\n**Examples**\n\n```js examples.js\nindexOfMin([6, 4, 8, 2, 10]); // 3\nindexOfMin([6, 4, 2, 2, 10]); // 2\n```\n"
  },
  {
    "path": "contents/find-the-length-of-the-longest-string-in-an-array.mdx",
    "content": "---\ncategory: Array\ncontributors:\n    - codepo8\ncreated: '2020-04-30'\ntitle: Find the length of the longest string in an array\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js findLongest.js\nconst findLongest = (words) => Math.max(...words.map((el) => el.length));\n```\n\n**TypeScript version**\n\n```ts findLongest.ts\nconst findLongest = (words: string[]): number => Math.max(...words.map((el) => el.length));\n```\n\n**Example**\n\n```js example.js\nfindLongest(['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']); // 6\n```\n"
  },
  {
    "path": "contents/find-the-maximum-item-of-an-array-by-given-key.mdx",
    "content": "---\ncategory: Array\ncreated: '2021-01-13'\ntitle: Find the maximum item of an array by given key\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js maxBy.js\nconst maxBy = (arr, key) => arr.reduce((a, b) => (a[key] >= b[key] ? a : b), {});\n```\n\n**TypeScript version**\n\n```ts maxBy.ts\nconst maxBy = <T extends Record<string, any>, K extends keyof T>(arr: T[], key: K): T => (\n    arr.reduce((a, b) => (a[key] >= b[key] ? a : b), {} as T)\n);\n```\n\n**Example**\n\n```js example.js\nconst people = [\n    { name: 'Bar', age: 24 },\n    { name: 'Baz', age: 32 },\n    { name: 'Foo', age: 42 },\n    { name: 'Fuzz', age: 36 },\n];\nmaxBy(people, 'age'); // { name: 'Foo', age: 42 }\n```\n"
  },
  {
    "path": "contents/find-the-maximum-item-of-an-array.mdx",
    "content": "---\ncategory: Array\ncreated: '2020-04-19'\ntitle: Find the maximum item of an array\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js max.js\nconst max = (arr) => Math.max(...arr);\n```\n\n**TypeScript version**\n\n```ts max.ts\nconst max = (arr: number[]): number => Math.max(...arr);\n```\n"
  },
  {
    "path": "contents/find-the-minimum-item-of-an-array-by-given-key.mdx",
    "content": "---\ncategory: Array\ncreated: '2021-01-13'\ntitle: Find the minimum item of an array by given key\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js minBy.js\nconst minBy = (arr, key) => arr.reduce((a, b) => (a[key] < b[key] ? a : b), {});\n```\n\n**TypeScript version**\n\n```ts minBy.ts\nconst minBy = <T extends Record<string, any>, K extends keyof T>(arr: T[], key: K): T => (\n    arr.reduce((a, b) => (a[key] < b[key] ? a : b), {} as T)\n);\n```\n\n**Example**\n\n```js example.js\nconst people = [\n    { name: 'Bar', age: 24 },\n    { name: 'Baz', age: 32 },\n    { name: 'Foo', age: 42 },\n    { name: 'Fuzz', age: 36 },\n];\nminBy(people, 'age'); // { name: 'Bar', age: 24 }\n```\n"
  },
  {
    "path": "contents/find-the-minimum-item-of-an-array.mdx",
    "content": "---\ncategory: Array\ncreated: '2020-04-19'\ntitle: Find the minimum item of an array\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js min.js\nconst min = (arr) => Math.min(...arr);\n```\n\n**TypeScript version**\n\n```ts min.ts\nconst min = (arr: number[]): number => Math.min(...arr);\n```\n"
  },
  {
    "path": "contents/flatten-an-array.mdx",
    "content": "---\ncategory: Array\ncontributors:\n    - nico2che\ncreated: '2020-05-01'\ntitle: Flatten an array\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js flat.js\nconst flat = (arr) =>\n    [].concat.apply(\n        [],\n        arr.map((a) => (Array.isArray(a) ? flat(a) : a))\n    );\n\n// Or\nconst flat = (arr) => arr.reduce((a, b) => (Array.isArray(b) ? [...a, ...flat(b)] : [...a, b]), []);\n\n// Or\n// See the browser compatibility at https://caniuse.com/#feat=array-flat\nconst flat = (arr) => arr.flat();\n```\n\n**Example**\n\n```js example.js\nflat(['cat', ['lion', 'tiger']]); // ['cat', 'lion', 'tiger']\n```\n"
  },
  {
    "path": "contents/flip-the-arguments-of-a-function.mdx",
    "content": "---\ncategory: Function\ncreated: '2020-05-12'\ntitle: Flip the arguments of a function\n---\n\n**JavaScript version**\n\n```js flip.js\n// Reverse the order of arguments\nconst flip =\n    (fn) =>\n    (...args) =>\n        fn(...args.reverse());\n\n// For binary functions\nconst flip = (fn) => (b, a) => fn(a, b);\n\n// Or for curried functions\nconst flip = (fn) => (b) => (a) => fn(a)(b);\n```\n\n**Examples**\n\n```js examples.js\nconst isParent = (parent, child) => parent.children.includes(child);\nconst isChild = flip(isParent);\n```\n"
  },
  {
    "path": "contents/format-a-date-for-the-given-locale.mdx",
    "content": "---\ncategory: Date Time\ncreated: '2020-05-06'\ntitle: Format a date for the given locale\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js\n// `date` is a `Date` object\n// `locale` is a locale (en-US, pt-BR, for example)\nconst format = (date, locale) => new Intl.DateTimeFormat(locale).format(date);\n```\n\n**TypeScript version**\n\n```ts format.ts\nconst format = (date: Date, locale: string): string => new Intl.DateTimeFormat(locale).format(date);\n```\n\n**Example**\n\n```js example.js\nformat(new Date(), 'pt-BR'); // 06/05/2020\n```\n"
  },
  {
    "path": "contents/format-a-string.mdx",
    "content": "---\ncategory: String\ncontributors:\n    - david-luna\ncreated: '2021-11-10'\ntitle: Format a string\n---\n\n**JavaScript version**\n\n```js format.js\nconst format = (str, ...vals) => vals.reduce((s, v, i) => s.replace(new RegExp('\\\\{' + i + '\\\\}', 'g'), v), str);\n```\n\n**TypeScript version**\n\n```ts\nconst format = (str: string, ...vals: unknown[]): string =>\n    vals.reduce((s, v, i) => s.replace(new RegExp('\\\\{' + i + '\\\\}', 'g'), v), str);\n```\n\n**Examples**\n\n```js examples.js\nconst template = 'My name is {0} and I am {1} years old';\n\nformat(template, 'John', 30));\n// My name is John and I am 30 years old\n\nformat(template, 'Jane', 20);\n// My name is Jane and I am 20 years old\n```\n"
  },
  {
    "path": "contents/generate-a-hash-of-a-string.mdx",
    "content": "---\ncategory: String\ncreated: '2021-03-21'\ntitle: Generate a hash of a string\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js hash.js\nconst hash = (str) => str.split('').reduce((prev, curr) => (Math.imul(31, prev) + curr.charCodeAt(0)) | 0, 0);\n\n// Or\nconst hash = (str) => str.split('').reduce((prev, curr) => ((prev << 5) - prev + curr.charCodeAt(0)) | 0, 0);\n```\n\n**TypeScript version**\n\n```ts hash.ts\nconst hash = (str: string): number =>\n    str.split('').reduce((prev, curr) => (Math.imul(31, prev) + curr.charCodeAt(0)) | 0, 0);\n\n// Or\nconst hash = (str: string): number =>\n    str.split('').reduce((prev, curr) => ((prev << 5) - prev + curr.charCodeAt(0)) | 0, 0);\n```\n\n**Examples**\n\n```js examples.js\nhash('hello'); // 99162322\n```\n"
  },
  {
    "path": "contents/generate-a-random-boolean.mdx",
    "content": "---\ncategory: Random\ncreated: '2020-05-05'\ntitle: Generate a random boolean\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js randomBoolean.js\nconst randomBoolean = () => Math.random() >= 0.5;\n```\n\n**TypeScript version**\n\n```ts randomBoolean.ts\nconst randomBoolean = (): boolean => Math.random() >= 0.5;\n```\n"
  },
  {
    "path": "contents/generate-a-random-floating-point-number-in-given-range.mdx",
    "content": "---\ncategory: Random\ncreated: '2020-05-05'\ntitle: Generate a random floating point number in given range\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js randomFloat.js\nconst randomFloat = (min, max) => Math.random() * (max - min) + min;\n```\n\n**TypeScript version**\n\n```ts randomFloat.ts\nconst randomFloat = (min: number, max: number): number => Math.random() * (max - min) + min;\n```\n\n## See also\n\n-   [Generate a random integer in given range](https://phuoc.ng/collection/1-loc/generate-a-random-integer-in-given-range/)\n-   [Generate a weighted random number in given range](https://phuoc.ng/collection/1-loc/generate-a-weighted-random-number-in-given-range/)\n"
  },
  {
    "path": "contents/generate-a-random-hex-color.mdx",
    "content": "---\ncategory: Random\ncontributors:\n    - robinpokorny\ncreated: '2020-04-19'\ntitle: Generate a random hex color\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js randomColor.js\nconst randomColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`;\n\n// Or\nconst randomColor = () => `#${(~~(Math.random() * (1 << 24))).toString(16)}`;\n```\n\n**TypeScript version**\n\n```ts randomColor.ts\nconst randomColor = (): string => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`;\n\n// Or\nconst randomColor = (): string => `#${(~~(Math.random() * (1 << 24))).toString(16)}`;\n```\n"
  },
  {
    "path": "contents/generate-a-random-integer-in-given-range.mdx",
    "content": "---\ncategory: Random\ncreated: '2020-05-05'\ntitle: Generate a random integer in given range\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js randomInteger.js\nconst randomInteger = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;\n```\n\n**TypeScript version**\n\n```ts randomInteger.ts\nconst randomInteger = (min: number, max: number): number => Math.floor(Math.random() * (max - min + 1)) + min;\n```\n\n## See also\n\n-   [Generate a random floating point number in given range](https://phuoc.ng/collection/1-loc/generate-a-random-floating-point-number-in-given-range/)\n-   [Generate a weighted random number in given range](https://phuoc.ng/collection/1-loc/generate-a-weighted-random-number-in-given-range/)\n"
  },
  {
    "path": "contents/generate-a-random-ip-address.mdx",
    "content": "---\ncategory: Random\ncontributors:\n    - PiyushSuthar\n    - Comet32\ncreated: '2020-08-10'\ntitle: Generate a random IP address\nupdated: '2023-08-09'\n---\n\n**JavaScript version**\n\n```js randomIp.js\nconst randomIp = () =>\n    Array(4)\n        .fill(0)\n        .map((_, i) => Math.floor(Math.random() * 255) + (i === 0 ? 1 : 0))\n        .join('.');\n```\n\n**TypeScript version**\n\n```ts randomIp.ts\nconst randomIp = (): string =>\n    Array(4)\n        .fill(0)\n        .map((_, i) => Math.floor(Math.random() * 255) + (i === 0 ? 1 : 0))\n        .join('.');\n```\n\n**Examples**\n\n```js examples.js\nrandomIp(); // 175.89.174.131\n```\n"
  },
  {
    "path": "contents/generate-a-random-sign.mdx",
    "content": "---\ncategory: Random\ncreated: '2021-04-10'\ntitle: Generate a random sign\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js randomSign.js\nconst randomSign = () => (Math.random() >= 0.5 ? 1 : -1);\n```\n\n**TypeScript version**\n\n```ts randomSign.ts\nconst randomSign = (): number => (Math.random() >= 0.5 ? 1 : -1);\n```\n"
  },
  {
    "path": "contents/generate-a-random-string-from-given-characters.mdx",
    "content": "---\ncategory: Random\ncreated: '2020-04-23'\ntitle: Generate a random string from given characters\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js generateString.js\nconst generateString = (length, chars) =>\n    Array(length)\n        .fill('')\n        .map((v) => chars[Math.floor(Math.random() * chars.length)])\n        .join('');\n```\n\n**TypeScript version**\n\n```ts generateString.ts\nconst generateString = (length: number, chars: string) =>\n    Array(length)\n        .fill('')\n        .map((v) => chars[Math.floor(Math.random() * chars.length)])\n        .join('');\n```\n\n**Examples**\n\n```js examples.js\ngenerateString(10, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');\n```\n"
  },
  {
    "path": "contents/generate-a-random-string-using-node-crypto-module.mdx",
    "content": "---\ncategory: Random\ncreated: '2020-07-28'\ntitle: Generate a random string using Node crypto module\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js randomStr.js\nconst randomStr = () => require('crypto').randomBytes(32).toString('hex');\n```\n\n**TypeScript version**\n\n```ts randomStr.ts\nconst randomStr = (): string => require('crypto').randomBytes(32).toString('hex');\n```\n"
  },
  {
    "path": "contents/generate-a-random-string-with-given-length.mdx",
    "content": "---\ncategory: Random\ncreated: '2020-04-23'\ntitle: Generate a random string with given length\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js generateString.js\nconst generateString = (length) =>\n    Array(length)\n        .fill('')\n        .map((v) => Math.random().toString(36).charAt(2))\n        .join('');\n```\n\n**TypeScript version**\n\n```ts generateString.ts\nconst generateString = (length: number): string =>\n    Array(length)\n        .fill('')\n        .map((v) => Math.random().toString(36).charAt(2))\n        .join('');\n```\n"
  },
  {
    "path": "contents/generate-a-random-uuid.mdx",
    "content": "---\ncategory: Random\ncontributors:\n    - w3bdesign\ncreated: '2020-05-05'\ntitle: Generate a random UUID\n---\n\n**JavaScript version**\n\n```js uuid.js\nconst uuid = (a) =>\n    a\n        ? (a ^ ((Math.random() * 16) >> (a / 4))).toString(16)\n        : ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, uuid);\n```\n"
  },
  {
    "path": "contents/generate-a-weighted-random-number-in-given-range.mdx",
    "content": "---\ncategory: Random\ncreated: '2023-08-22'\ndescription: one-liner function to generate a weighted random number in given range\nopenGraphCover: /og/1-loc/weighted-random.png\ntitle: Generate a weighted random number in given range\n---\n\n**JavaScript version**\n\n```js weightedRandom.js\nconst weightedRandom = (min, max) => ~~(Math.pow(Math.random(), 2) * (max - min)) + min;\n```\n\n**TypeScript version**\n\n```ts weightedRandom.ts\nconst weightedRandom = (min: number, max: number): number => ~~(Math.pow(Math.random(), 2) * (max - min)) + min;\n```\n\n**Examples**\n\n```js examples.js\nweightedRandom(2, 10);  // 7\nweightedRandom(2, 10);  // 6\nweightedRandom(2, 10);  // 4\nweightedRandom(2, 10);  // 3\nweightedRandom(2, 10);  // 5\n```\n\n## See also\n\n-   [Generate a random floating point number in given range](https://phuoc.ng/collection/1-loc/generate-a-random-floating-point-number-in-given-range/)\n-   [Generate a random integer in given range](https://phuoc.ng/collection/1-loc/generate-a-random-integer-in-given-range/)\n"
  },
  {
    "path": "contents/generate-an-array-of-alphabet-characters.mdx",
    "content": "---\ncategory: Array\ncreated: '2021-10-22'\ntitle: Generate an array of alphabet characters\nupdated: '2021-10-22'\n---\n\n**JavaScript version**\n\n```js alphabet.js\nconst alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');\n\n// Or\nconst alphabet = [...'abcdefghijklmnopqrstuvwxyz'];\n\n// Or\nconst alphabet = Array(26)\n    .fill(0)\n    .map((_, i) => String.fromCharCode(i + 97));\n\n// Or\nconst alphabet = [...Array(26).keys()].map((i) => String.fromCharCode(i + 97));\n\n// Or\nconst alphabet = [...Array(26)].map((_, i) => (i + 10).toString(36));\n\n// Or\nconst alphabet = String.fromCharCode(\n    ...' '\n        .repeat(26)\n        .split('')\n        .map((_, i) => i + 97)\n).split('');\n```\n\n**TypeScript version**\n\n```ts alphabet.ts\nconst alphabet: string[] = 'abcdefghijklmnopqrstuvwxyz'.split('');\n\n// Or\nconst alphabet: string[] = [...'abcdefghijklmnopqrstuvwxyz'];\n\n// Or\nconst alphabet: string[] = Array(26)\n    .fill(0)\n    .map((_, i) => String.fromCharCode(i + 97));\n\n// Or\nconst alphabet: string[] = [...Array(26).keys()].map((i) => String.fromCharCode(i + 97));\n\n// Or\nconst alphabet: string[] = [...Array(26)].map((_, i) => (i + 10).toString(36));\n\n// Or\nconst alphabet: string[] = String.fromCharCode(\n    ...' '\n        .repeat(26)\n        .split('')\n        .map((_, i) => i + 97)\n).split('');\n```\n"
  },
  {
    "path": "contents/generate-an-array-of-random-integers-in-a-given-range.mdx",
    "content": "---\ncategory: Random\ncreated: '2020-05-16'\ntitle: Generate an array of random integers in a given range\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js randomArrayInRange.js\nconst randomArrayInRange = (min, max, n) =>\n    Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min);\n```\n\n**TypeScript version**\n\n```ts randomArrayInRange.ts\nconst randomArrayInRange = (min: number, max: number, n: number): number[] =>\n    Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min);\n```\n\n**Examples**\n\n```js examples.js\nrandomArrayInRange(1, 100, 10); // [11, 82, 41, 35, 76, 83, 43, 15, 60, 54]\n```\n"
  },
  {
    "path": "contents/generate-an-unique-and-increment-id.mdx",
    "content": "---\ncategory: Misc\ncreated: '2021-04-05'\ntitle: Generate an unique and increment id\n---\n\n**JavaScript version**\n\n```js uid.js\nconst uid = (() => ((id = 0), () => id++))();\n```\n\n**Examples**\n\n```js examples.js\nuid(); // 0\nuid(); // 1\nuid(); // 2\nuid(); // 3\n```\n"
  },
  {
    "path": "contents/get-a-random-item-and-remove-it-from-an-array.mdx",
    "content": "---\ncategory: Random\ncreated: '2021-01-16'\ntitle: Get a random item and remove it from an array\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js randomItem.js\nconst randomItem = (arr) => arr.splice((Math.random() * arr.length) | 0, 1);\n```\n\n**TypeScript version**\n\n```ts randomItem.ts\nconst randomItem = <T,>(arr: T[]): T => arr.splice((Math.random() * arr.length) | 0, 1) as unknown as T;\n```\n\n**Examples**\n\n```js examples.js\nconst arr = [1, 3, 5, 7, 9];\nrandomItem(arr); // 7\n// arr = [1, 3, 5, 9]\n```\n"
  },
  {
    "path": "contents/get-a-random-item-from-an-array.mdx",
    "content": "---\ncategory: Random\ncontributors:\n    - jonrandy\ncreated: '2020-04-19'\ntitle: Get a random item from an array\nupdated: '2021-10-22'\n---\n\n**JavaScript version**\n\n```js randomItem.js\nconst randomItem = (arr) => arr[(Math.random() * arr.length) | 0];\n```\n\n**TypeScript version**\n\n```ts randomItem.ts\nconst randomItem = <T,_>(arr: T[]): T => arr[(Math.random() * arr.length) | 0];\n```\n"
  },
  {
    "path": "contents/get-all-arrays-of-consecutive-elements.mdx",
    "content": "---\ncategory: Array\ncreated: '2021-04-10'\ntitle: Get all arrays of consecutive elements\nupdated: '2021-10-22'\n---\n\n**JavaScript version**\n\n```js getConsecutiveArrays.js\nconst getConsecutiveArrays = (arr, size) =>\n    size > arr.length ? [] : arr.slice(size - 1).map((_, i) => arr.slice(i, size + i));\n```\n\n**TypeScript version**\n\n```ts getConsecutiveArrays.ts\nconst getConsecutiveArrays = <T,_>(arr: T[], size: number): T[][] => (size > arr.length ? [] : arr.slice(size - 1).map((_, i) => arr.slice(i, size + i)));\n```\n\n**Examples**\n\n```js examples.js\ngetConsecutiveArrays([1, 2, 3, 4, 5], 2); // [[1, 2], [2, 3], [3, 4], [4, 5]]\ngetConsecutiveArrays([1, 2, 3, 4, 5], 3); // [[1, 2, 3], [2, 3, 4], [3, 4, 5]]\ngetConsecutiveArrays([1, 2, 3, 4, 5], 6); // []\n```\n"
  },
  {
    "path": "contents/get-all-nth-items-of-an-array.mdx",
    "content": "---\ncategory: Array\ncreated: '2021-02-20'\ntitle: 'Get all n-th items of an array'\nupdated: '2021-10-22'\n---\n\n**JavaScript version**\n\n```js getNthItems.js\nconst getNthItems = (arr, nth) => arr.filter((_, i) => i % nth === nth - 1);\n```\n\n**TypeScript version**\n\n```ts getNthItems.ts\nconst getNthItems = <T,_>(arr: T[], nth: number): T[] => arr.filter((_, i) => i % nth === nth - 1);\n```\n\n**Examples**\n\n```js examples.js\ngetNthItems([1, 2, 3, 4, 5, 6, 7, 8, 9], 2); // [2, 4, 6, 8]\ngetNthItems([1, 2, 3, 4, 5, 6, 7, 8, 9], 3); // [3, 6, 9]\n```\n"
  },
  {
    "path": "contents/get-all-siblings-of-an-element.mdx",
    "content": "---\ncategory: DOM\ncreated: '2020-04-19'\ntitle: Get all siblings of an element\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js siblings.js\nconst siblings = (ele) => [].slice.call(ele.parentNode.children).filter((child) => child !== ele);\n```\n\n**TypeScript version**\n\n```ts siblings.ts\nconst siblings = (ele: Node): Node[] =>\n    ele.parentNode ? [].slice.call(ele.parentNode.children).filter((child) => child !== ele) : [];\n```\n"
  },
  {
    "path": "contents/get-all-subsets-of-an-array.mdx",
    "content": "---\ncategory: Array\ncreated: '2021-02-25'\ntitle: Get all subsets of an array\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js getSubsets.js\nconst getSubsets = (arr) => arr.reduce((prev, curr) => prev.concat(prev.map((k) => k.concat(curr))), [[]]);\n```\n\n**TypeScript version**\n\n```ts getSubsets.ts\nconst getSubsets = <T,>(arr: T[]): T[][] => (\n    arr.reduce((prev, curr) => prev.concat(prev.map((k) => k.concat(curr))), [[]] as T[][])\n);\n```\n\n**Examples**\n\n```js examples.js\ngetSubsets([1, 2]); // [[], [1], [2], [1, 2]]\ngetSubsets([1, 2, 3]); // [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]\n```\n"
  },
  {
    "path": "contents/get-hours-and-minutes-from-decimal-time.mdx",
    "content": "---\ncategory: Date Time\ncontributors:\n    - ognjenst\ncreated: '2022-12-27'\ntitle: Get the hours and minutes from the decimal time\n---\n\n**JavaScript version**\n\n```js getHoursAndMinutes.js\nconst getHoursAndMinutes = (value) => [Math.floor(value), Math.floor((value * 60) % 60)];\n```\n\n**TypeScript version**\n\n```ts getHoursAndMinutes.ts\nconst getHoursAndMinutes = (value: number): [number, number] => [Math.floor(value), Math.floor((value * 60) % 60)];\n```\n\n**Examples**\n\n```js examples.js\ngetHoursAndMinutes(4.5); //[4, 30]\ngetHoursAndMinutes(7.89); // [7, 53]\n```\n"
  },
  {
    "path": "contents/get-indices-of-a-value-in-an-array.mdx",
    "content": "---\ncategory: Array\ncreated: '2021-03-07'\ntitle: Get indices of a value in an array\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js indices.js\nconst indices = (arr, value) => arr.reduce((acc, v, i) => (v === value ? [...acc, i] : acc), []);\n\n// Or\nconst indices = (arr, value) => arr.map((v, i) => (v === value ? i : false)).filter(Boolean);\n```\n\n**TypeScript version**\n\n```ts indices.ts\nconst indices = <T,>(arr: T[], value: T): number[] => (\n    arr.reduce((acc, v, i) => (v === value ? [...acc, i] : acc), [] as number[])\n);\n\n// Or\nconst indices = <T,>(arr: T[], value: T): number[] => (\n    arr.map((v, i) => (v === value ? i : false)).filter(Boolean) as number[]\n);\n```\n\n**Examples**\n\n```js examples.js\nindices(['h', 'e', 'l', 'l', 'o'], 'l'); // [2, 3]\nindices(['h', 'e', 'l', 'l', 'o'], 'w'); // []\n```\n"
  },
  {
    "path": "contents/get-random-items-of-an-array.mdx",
    "content": "---\ncategory: Random\ncreated: '2021-01-16'\ntitle: Get random items of an array\n---\n\n**JavaScript version**\n\n```js randomItems.js\nconst randomItems = (arr, count) =>\n    arr\n        .concat()\n        .reduce(\n            (p, _, __, arr) =>\n                p[0] < count ? [p[0] + 1, p[1].concat(arr.splice((Math.random() * arr.length) | 0, 1))] : p,\n            [0, []]\n        )[1];\n```\n\n**Examples**\n\n```js examples.js\nrandomItems([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3); // [4, 8, 5]\nrandomItems(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'], 4); // ['e', 'c', 'h', 'j']\n```\n"
  },
  {
    "path": "contents/get-the-arrays-of-digits-from-a-number.mdx",
    "content": "---\ncategory: Number\ncreated: '2020-05-16'\ntitle: Get the arrays of digits from a number\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js digitize.js\nconst digitize = (n) => `${n}`.split('').map((v) => parseInt(v, 10));\n\n// Or\nconst digitize = (n) => [...`${n}`].map((v) => parseInt(v, 10));\n```\n\n**TypeScript version**\n\n```ts digitize.ts\nconst digitize = (n: number): number[] => `${n}`.split('').map((v) => parseInt(v, 10));\n\n// Or\nconst digitize = (n: number): number[] => [...`${n}`].map((v) => parseInt(v, 10));\n```\n\n**Examples**\n\n```js examples.js\ndigitize(123); // [1, 2, 3]\n```\n"
  },
  {
    "path": "contents/get-the-average-of-an-array.mdx",
    "content": "---\ncategory: Array\ncreated: '2020-04-19'\ntitle: Get the average of an array\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js average.js\nconst average = (arr) => arr.reduce((a, b) => a + b, 0) / arr.length;\n```\n\n**TypeScript version**\n\n```ts average.ts\nconst average = (arr: number[]): number => arr.reduce((a, b) => a + b, 0) / arr.length;\n```\n"
  },
  {
    "path": "contents/get-the-base-url-without-any-parameters.mdx",
    "content": "---\ncategory: String\ncontributors:\n    - shawphy\ncreated: '2020-06-20'\ntitle: Get the base URL without any parameters\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js baseUrl.js\nconst baseUrl = (url) => (url.indexOf('?') === -1 ? url : url.slice(0, url.indexOf('?')));\n\n// Or\n// Note that `includes` isn't supported in IE 11\nconst baseUrl = (url) => (url.includes('?') ? url.slice(0, url.indexOf('?')) : url);\n\n// Or\nconst baseUrl = (url) => url.split('?')[0];\n```\n\n**TypeScript version**\n\n```ts baseUrl.ts\nconst baseUrl = (url: string): string => (url.indexOf('?') === -1 ? url : url.slice(0, url.indexOf('?')));\n\n// Or\n// Note that `includes` isn't supported in IE 11\nconst baseUrl = (url: string): string => (url.includes('?') ? url.slice(0, url.indexOf('?')) : url);\n\n// Or\nconst baseUrl = (url: string): string => url.split('?')[0];\n```\n\n**Examples**\n\n```js examples.js\nbaseUrl('https://domain.com/path/sub/path?foo=bar&hello=world'); // 'https://domain.com/path/sub/path'\n```\n"
  },
  {
    "path": "contents/get-the-center-point-of-a-dom-rect.mdx",
    "content": "---\ncategory: DOM\ncreated: '2023-12-09'\nopenGraphCover: /og/1-loc/get-center-point-dom-rect.png\ntitle: Get the center point of a DOMRect\n---\n\n**JavaScript version**\n\n```js getCenter.js\nconst getCenter = rect => [rect.left + rect.width / 2, rect.top + rect.height / 2];\n```\n\n**TypeScript version**\n\n```ts getCenter.ts\nconst getCenter = (rect: DOMRect): [number, number] => [rect.left + rect.width / 2, rect.top + rect.height / 2];\n```\n\n**Examples**\n\n```js example.js\ngetCenter(new DOMRect(0, 0, 200, 400));     // [100, 200]\n```\n"
  },
  {
    "path": "contents/get-the-current-quarter-of-a-date.mdx",
    "content": "---\ncategory: Date Time\ncreated: '2021-02-25'\ntitle: Get the current quarter of a date\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js getQuarter.js\nconst getQuarter = (d = new Date()) => Math.ceil((d.getMonth() + 1) / 3);\n```\n\n**TypeScript version**\n\n```ts getQuarter.ts\nconst getQuarter = (d = new Date()): number => Math.ceil((d.getMonth() + 1) / 3);\n```\n"
  },
  {
    "path": "contents/get-the-current-timestamp-in-seconds.mdx",
    "content": "---\ncategory: Date Time\ncreated: '2020-04-19'\ntitle: Get the current timestamp in seconds\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js ts.js\nconst ts = () => Math.floor(new Date().getTime() / 1000);\n```\n\n**TypeScript version**\n\n```ts ts.ts\nconst ts = (): number => Math.floor(new Date().getTime() / 1000);\n```\n"
  },
  {
    "path": "contents/get-the-day-of-the-year-from-a-date.mdx",
    "content": "---\ncategory: Date Time\ncreated: '2020-05-16'\ntitle: Get the day of the year from a date\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js dayOfYear.js\n// `date` is a Date object\nconst dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24));\n```\n\n**TypeScript version**\n\n```ts dayOfYear.ts\nconst dayOfYear = (date: Date): number =>\n    Math.floor((date.valueOf() - new Date(date.getFullYear(), 0, 0).valueOf()) / (1000 * 60 * 60 * 24));\n```\n\n**Example**\n\n```js example.js\ndayOfYear(new Date(2020, 04, 16)); // 137\n```\n"
  },
  {
    "path": "contents/get-the-file-extension-from-a-file-name.mdx",
    "content": "---\ncategory: String\ncreated: '2020-04-19'\ntitle: Get the file extension from a file name\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js ext.js\nconst ext = (fileName) => fileName.split('.').pop();\n```\n\n**TypeScript version**\n\n```ts ext.ts\nconst ext = (fileName: string): string => fileName.split('.').pop();\n```\n"
  },
  {
    "path": "contents/get-the-file-name-from-a-url.mdx",
    "content": "---\ncategory: String\ncreated: '2020-04-19'\ntitle: Get the file name from a URL\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js fileName.js\nconst fileName = (url: string): string => url.substring(url.lastIndexOf('/') + 1);\n```\n\n**TypeScript version**\n\n```ts fileName.ts\nconst fileName = (url: string): string => url.substring(url.lastIndexOf('/') + 1);\n```\n\n**Examples**\n\n```js examples.js\nfileName('http://domain.com/path/to/document.pdf'); // 'document.pdf'\n```\n"
  },
  {
    "path": "contents/get-the-first-date-in-the-month-of-a-date.mdx",
    "content": "---\ncategory: Date Time\ncreated: '2021-02-25'\ntitle: Get the first date in the month of a date\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js getFirstDate.js\nconst getFirstDate = (d = new Date()) => new Date(d.getFullYear(), d.getMonth(), 1);\n```\n\n**TypeScript version**\n\n```ts getFirstDate.ts\nconst getFirstDate = (d = new Date()): Date => new Date(d.getFullYear(), d.getMonth(), 1);\n```\n"
  },
  {
    "path": "contents/get-the-first-defined-and-non-null-argument.mdx",
    "content": "---\ncategory: Misc\ncreated: '2020-06-12'\ntitle: Get the first defined and non null argument\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js coalesce.js\nconst coalesce = (...args) => args.find((item) => item !== undefined && item !== null);\n\n// Or\nconst coalesce = (...args) => args.find((item) => ![undefined, null].includes(item));\n```\n\n**TypeScript version**\n\n```ts coalesce.ts\nconst coalesce = (...args: any[]): any[] => args.find((item) => item !== undefined && item !== null);\n\n// Or\nconst coalesce = (...args: any[]): any[] => args.find((item) => ![undefined, null].includes(item));\n```\n\n**Examples**\n\n```js examples.js\ncoalesce(undefined, null, 'helloworld', NaN); // 'helloworld'\n```\n"
  },
  {
    "path": "contents/get-the-intersection-of-arrays.mdx",
    "content": "---\ncategory: Array\ncontributors:\n    - vreymond\n    - robinpokorny\ncreated: '2020-05-09'\ntitle: Get the intersection of arrays\nupdated: '2021-10-22'\n---\n\n**JavaScript version**\n\n```js getIntersection.js\nconst getIntersection = (a, ...arr) => [...new Set(a)].filter((v) => arr.every((b) => b.includes(v)));\n```\n\n**TypeScript version**\n\n```ts getIntersection.ts\nconst getIntersection = <T,_>(a: T[], ...arr: T[][]): T[] => [...new Set(a)].filter((v) => arr.every((b) => b.includes(v)));\n```\n\n**Examples**\n\n```js examples.js\ngetIntersection([1, 2, 3], [2, 3, 4, 5]); // [2, 3]\ngetIntersection([1, 2, 3], [2, 3, 4, 5], [1, 3, 5]); // [3]\n```\n"
  },
  {
    "path": "contents/get-the-intersection-range-between-two-ranges.mdx",
    "content": "---\ncategory: Number\ncreated: '2023-12-07'\nopenGraphCover: /og/1-loc/get-intersection-range-between-two-ranges.png\ntitle: Get the intersection range between two ranges\n---\n\n**JavaScript version**\n\n```js intersection.js\nconst intersection = (a, b) => (a[0] > b[1] || a[1] < b[0]) ? [] : [Math.max(a[0], b[0]), Math.min(a[1], b[1])];\n```\n\n**TypeScript version**\n\n```ts intersection.ts\nconst intersection = (a: [number, number], b: [number, number]): number[] => (a[0] > b[1] || a[1] < b[0]) ? [] : [Math.max(a[0], b[0]), Math.min(a[1], b[1])];\n```\n\n**Examples**\n\n```js examples.js\nintersection([0, 20], [15, 35]);    // [15, 20]\nintersection([0, 20], [40, 50]);    // []\n```\n"
  },
  {
    "path": "contents/get-the-last-date-in-the-month-of-a-date.mdx",
    "content": "---\ncategory: Date Time\ncreated: '2021-02-25'\ntitle: Get the last date in the month of a date\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js getLastDate.js\nconst getLastDate = (d = new Date()) => new Date(d.getFullYear(), d.getMonth() + 1, 0);\n```\n\n**TypeScript version**\n\n```ts getLastDate.ts\nconst getLastDate = (d = new Date()): Date => new Date(d.getFullYear(), d.getMonth() + 1, 0);\n```\n"
  },
  {
    "path": "contents/get-the-length-of-a-string-in-bytes.mdx",
    "content": "---\ncategory: String\ncreated: '2020-05-16'\ntitle: Get the length of a string in bytes\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js bytes.js\nconst bytes = (str) => new Blob([str]).size;\n```\n\n**TypeScript version**\n\n```ts bytes.ts\nconst bytes = (str: string): number => new Blob([str]).size;\n```\n\n**Examples**\n\n```js examples.js\nbytes('hello world'); // 11\nbytes('🎉'); // 4\n```\n"
  },
  {
    "path": "contents/get-the-month-name-of-a-date.mdx",
    "content": "---\ncategory: Date Time\ncreated: '2020-05-05'\ntitle: Get the month name of a date\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js getMonthName.js\n// `date` is a Date object\nconst getMonthName = (date) =>\n    [\n        'January',\n        'February',\n        'March',\n        'April',\n        'May',\n        'June',\n        'July',\n        'August',\n        'September',\n        'October',\n        ' November',\n        'December',\n    ][date.getMonth()];\n```\n\n**TypeScript version**\n\n```ts getMonthName.ts\nconst getMonthName = (date: Date): string =>\n    [\n        'January',\n        'February',\n        'March',\n        'April',\n        'May',\n        'June',\n        'July',\n        'August',\n        'September',\n        'October',\n        ' November',\n        'December',\n    ][date.getMonth()];\n```\n"
  },
  {
    "path": "contents/get-the-number-of-a-character-in-a-string.mdx",
    "content": "---\ncategory: String\ncreated: '2020-08-02'\ntitle: Get the number of a character in a string\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js characterCount.js\nconst characterCount = (str, char) => str.split(char).length - 1;\n\n// Or\nconst characterCount = (str, char) => str.replace(new RegExp(String.raw`[^${char}]`, 'g'), '').length;\n```\n\n**TypeScript version**\n\n```ts characterCount.ts\nconst characterCount = (str: string, char: string): number => str.split(char).length - 1;\n\n// Or\nconst characterCount = (str: string, char: string): number =>\n    str.replace(new RegExp(String.raw`[^${char}]`, 'g'), '').length;\n```\n\n**Examples**\n\n```js examples.js\ncharacterCount('192.168.1.1', '.'); // 3\ncharacterCount('star wars', 's'); // 2\n```\n"
  },
  {
    "path": "contents/get-the-number-of-days-in-given-month.mdx",
    "content": "---\ncategory: Date Time\ncreated: '2020-04-19'\ntitle: Get the number of days in given month\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js daysInMonth.js\n// `month` is zero-based index\nconst daysInMonth = (month, year) => new Date(year, month, 0).getDate();\n```\n\n**TypeScript version**\n\n```ts daysInMonth.ts\nconst daysInMonth = (month: number, year: number): number => new Date(year, month, 0).getDate();\n```\n"
  },
  {
    "path": "contents/get-the-position-of-an-element-relative-to-the-document.mdx",
    "content": "---\ncategory: DOM\ncreated: '2021-04-21'\ntitle: Get the position of an element relative to the document\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js getPosition.js\nconst getPosition = (ele) => (\n    (r = ele.getBoundingClientRect()), { left: r.left + window.scrollX, top: r.top + window.scrollY }\n);\n```\n\n**Example**\n\n```js example.js\ngetPosition(document.body); // { left: 0, top: 0 }\n```\n"
  },
  {
    "path": "contents/get-the-rank-of-an-array-of-numbers.mdx",
    "content": "---\ncategory: Array\ncreated: '2020-04-19'\ntitle: Get the rank of an array of numbers\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js ranking.js\nconst ranking = (arr) => arr.map((x, y, z) => z.filter((w) => w > x).length + 1);\n```\n\n**TypeScript version**\n\n```ts ranking.ts\nconst ranking = (arr: number[]): number[] => arr.map((x, y, z) => z.filter((w) => w > x).length + 1);\n```\n\n**Examples**\n\n```js examples.js\nranking([80, 65, 90, 50]); // [2, 3, 1, 4]\nranking([80, 80, 70, 50]); // [1, 1, 3, 4]\nranking([80, 80, 80, 50]); // [1, 1, 1, 4]\n```\n"
  },
  {
    "path": "contents/get-the-selected-text.mdx",
    "content": "---\ncategory: DOM\ncreated: '2020-04-19'\ntitle: Get the selected text\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js getSelectedText.js\nconst getSelectedText = () => window.getSelection().toString();\n```\n"
  },
  {
    "path": "contents/get-the-sum-of-an-array-of-numbers.mdx",
    "content": "---\ncategory: Array\ncreated: '2020-04-19'\ntitle: Get the sum of an array of numbers\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js sum.js\nconst sum = (arr) => arr.reduce((a, b) => a + b, 0);\n```\n\n**TypeScript version**\n\n```ts sum.ts\nconst sum = (arr: number[]): number => arr.reduce((a, b) => a + b, 0);\n```\n"
  },
  {
    "path": "contents/get-the-timezone-string.mdx",
    "content": "---\ncategory: Date Time\ncreated: '2021-02-25'\ntitle: Get the timezone string\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js getTimezone.js\nconst getTimezone = () => Intl.DateTimeFormat().resolvedOptions().timeZone;\n```\n\n**TypeScript version**\n\n```ts getTimezone.ts\nconst getTimezone = (): string => Intl.DateTimeFormat().resolvedOptions().timeZone;\n```\n\n**Example**\n\n```js example.js\ngetTimezone(); // 'Asia/Saigon'\n```\n"
  },
  {
    "path": "contents/get-the-tomorrow-date.mdx",
    "content": "---\ncategory: Date Time\ncreated: '2020-05-21'\ntitle: Get the tomorrow date\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js tomorrow.js\nconst tomorrow = ((d) => new Date(d.setDate(d.getDate() + 1)))(new Date());\n\n// Or\nconst tomorrow = new Date(new Date().valueOf() + 1000 * 60 * 60 * 24);\n```\n\n**TypeScript version**\n\n```ts tomorrow.ts\nconst tomorrow: Date = ((d) => new Date(d.setDate(d.getDate() + 1)))(new Date());\n\n// Or\nconst tomorrow: Date = new Date(new Date().valueOf() + 1000 * 60 * 60 * 24);\n```\n\n## See also\n\n-   [Determine one year from now](https://phuoc.ng/collection/1-loc/determine-one-year-from-now/)\n-   [Get the yesterday date](https://phuoc.ng/collection/1-loc/get-the-yesterday-date/)\n"
  },
  {
    "path": "contents/get-the-total-number-of-days-in-a-year.mdx",
    "content": "---\ncategory: Date Time\ncreated: '2021-04-10'\ntitle: Get the total number of days in a year\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js numberOfDays.js\nconst numberOfDays = (year) => ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 366 : 365);\n\n// Or\nconst numberOfDays = (year) => (new Date(year, 1, 29).getDate() === 29 ? 366 : 365);\n```\n\n**TypeScript version**\n\n```ts numberOfDays.ts\nconst numberOfDays = (year: number): number => ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 366 : 365);\n\n// Or\nconst numberOfDays = (year: number): number => (new Date(year, 1, 29).getDate() === 29 ? 366 : 365);\n```\n"
  },
  {
    "path": "contents/get-the-unique-values-of-an-array.mdx",
    "content": "---\ncategory: Array\ncontributors:\n    - vreymond\ncreated: '2020-04-19'\ntitle: Get the unique values of an array\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js unique.js\nconst unique = (arr) => [...new Set(arr)];\n\n// Or\nconst unique = (arr) => arr.filter((el, i, array) => array.indexOf(el) === i);\n\n// Or\nconst unique = (arr) => arr.reduce((acc, el) => (acc.includes(el) ? acc : [...acc, el]), []);\n```\n\n**TypeScript version**\n\n```ts unique.ts\nconst unique = <T,>(arr: T[]): T[] => [...new Set(arr)];\n\n// Or\nconst unique = <T,>(arr: T[]): T[] => arr.filter((el, i, array) => array.indexOf(el) === i);\n\n// Or\nconst unique = <T,>(arr: T[]): T[] => arr.reduce((acc, el) => (acc.includes(el) ? acc : [...acc, el]), [] as T[]);\n```\n"
  },
  {
    "path": "contents/get-the-value-at-given-path-of-an-object.mdx",
    "content": "---\ncategory: Object\ncreated: '2020-05-13'\ntitle: Get the value at given path of an object\n---\n\n**JavaScript version**\n\n```js getValue.js\nconst getValue = (path, obj) => path.split('.').reduce((acc, c) => acc && acc[c], obj);\n```\n\n**Examples**\n\n```js examples.js\ngetValue('a.b', { a: { b: 'Hello World' } }); // 'Hello World';\n```\n"
  },
  {
    "path": "contents/get-the-value-of-a-cookie.mdx",
    "content": "---\ncategory: Misc\ncreated: '2020-05-28'\ntitle: Get the value of a cookie\n---\n\n**JavaScript version**\n\n```js cookie.js\nconst cookie = (name) => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();\n```\n\n**Examples**\n\n```js examples.js\ncookie('_ga'); // GA1.2.825309271.1581874719\n```\n"
  },
  {
    "path": "contents/get-the-value-of-a-param-from-a-url.mdx",
    "content": "---\ncategory: Misc\ncreated: '2020-04-23'\ntitle: Get the value of a param from a URL\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js getParam.js\nconst getParam = (url, param) => new URLSearchParams(new URL(url).search).get(param);\n```\n\n**TypeScript version**\n\n```ts getParam.ts\nconst getParam = (url: string, param: string): string | null => new URLSearchParams(new URL(url).search).get(param);\n```\n\n**Examples**\n\n```js examples.js\ngetParam('http://domain.com?message=hello', 'message'); // 'hello'\n```\n"
  },
  {
    "path": "contents/get-the-weekday-of-a-date.mdx",
    "content": "---\ncategory: Date Time\ncreated: '2020-05-05'\ntitle: Get the weekday of a date\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js getWeekday.js\n// `date` is a Date object\nconst getWeekday = (date) =>\n    ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][date.getDay()];\n```\n\n**TypeScript version**\n\n```ts getWeekday.ts\nconst getWeekday = (date: Date): string =>\n    ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][date.getDay()];\n```\n"
  },
  {
    "path": "contents/get-the-yesterday-date.mdx",
    "content": "---\ncategory: Date Time\ncreated: '2020-05-21'\ntitle: Get the yesterday date\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js yesterday.js\nconst yesterday = ((d) => new Date(d.setDate(d.getDate() - 1)))(new Date());\n\n// Or\nconst yesterday = new Date(new Date().valueOf() - 1000 * 60 * 60 * 24);\n```\n\n**TypeScript version**\n\n```ts yesterday.ts\nconst yesterday: Date = ((d) => new Date(d.setDate(d.getDate() - 1)))(new Date());\n\n// Or\nconst yesterday: Date = new Date(new Date().valueOf() - 1000 * 60 * 60 * 24);\n```\n\n## See also\n\n-   [Determine one year from now](https://phuoc.ng/collection/1-loc/determine-one-year-from-now/)\n-   [Get the tomorrow date](https://phuoc.ng/collection/1-loc/get-the-tomorrow-date/)\n"
  },
  {
    "path": "contents/get-type-of-a-variable-in-string.mdx",
    "content": "---\ncategory: Misc\ncreated: '2021-01-12'\ntitle: Get type of a variable in string\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js getTypeOf.js\nconst getTypeOf = (obj) => Object.prototype.toString.call(obj).match(/\\[object (.*)\\]/)[1];\n```\n\n**TypeScript version**\n\n```ts getTypeOf.ts\nconst getTypeOf = (obj: any): string => (Object.prototype.toString.call(obj).match(/\\[object (.*)\\]/) as string[])[1];\n```\n\n**Examples**\n\n```js examples.js\ngetTypeOf('hello world'); // String\ngetTypeOf(1000); // Number\ngetTypeOf(Infinity); // Number\ngetTypeOf(true); // Boolean\ngetTypeOf(Symbol()); // Symbol\ngetTypeOf(null); // Null\ngetTypeOf(undefined); // Undefined\ngetTypeOf({}); // Object\ngetTypeOf([]); // Array\ngetTypeOf(/[a-z]/g); // RegExp\ngetTypeOf(new Date(2021)); // Date\ngetTypeOf(new Error()); // Error\ngetTypeOf(function () {}); // Function\ngetTypeOf((a, b) => a + b); // Function\ngetTypeOf(async () => {}); // AsyncFunction\ngetTypeOf(document); // HTMLDocument\n```\n"
  },
  {
    "path": "contents/get-union-of-arrays.mdx",
    "content": "---\ncategory: Array\ncreated: '2020-05-09'\ntitle: Get union of arrays\nupdated: '2021-10-22'\n---\n\n**JavaScript version**\n\n```js union.js\nconst union = (...arr) => [...new Set(arr.flat())];\n```\n\n**TypeScript version**\n\n```ts union.ts\nconst union = <T,_>(...arr: T[][]): T[] => [...new Set(arr.flat())];\n```\n\n**Example**\n\n```js example.js\nunion([1, 2], [2, 3], [3]); // [1, 2, 3]\n```\n"
  },
  {
    "path": "contents/get-unique-arr-obj.mdx",
    "content": "---\ncategory: Object\ncontributors:\n    - gpbuavv\ncreated: '2023-02-17'\ntitle: Returns an object with unique values by key\n---\n\n**JavaScript version**\n\n```js\nexport const getUniqueArrObj = (arrObj, keyUnique) => [...new Map(arrObj.map((item) => [item[keyUnique], item])).values()];\n```\n\n**Example**\n\n```js example.js\n// Example\ngetUniqueArrObj([{ k: 1, e: 1 }, { k: 1, e: 1 }, { k: 3, e: 1 }], 'k'); // [{ k: 1, e: 1 }, { k: 3, e: 1 }]\n```\n"
  },
  {
    "path": "contents/go-back-to-the-previous-page.mdx",
    "content": "---\ncategory: DOM\ncreated: '2020-04-19'\ntitle: Go back to the previous page\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js\nhistory.back();\n\n// Or\nhistory.go(-1);\n```\n"
  },
  {
    "path": "contents/group-an-array-of-objects-by-a-key.mdx",
    "content": "---\ncategory: Array\ncreated: '2020-06-03'\ntitle: Group an array of objects by a key\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js groupBy.js\nconst groupBy = (arr, key) =>\n    arr.reduce((acc, item) => ((acc[item[key]] = [...(acc[item[key]] || []), item]), acc), {});\n```\n\n**TypeScript version**\n\n```ts groupBy.ts\nconst groupBy = <T extends Record<string, any>, K extends keyof T>(arr: T[], key: K): Record<string, T[]> => (\n    arr.reduce((acc, item) => ((acc[item[key]] = [...(acc[item[key]] || []), item]), acc), {} as Record<string, T[]>)\n);\n```\n\n**Example**\n\n```js example.js\ngroupBy(\n    [\n        { branch: 'audi', model: 'q8', year: '2019' },\n        { branch: 'audi', model: 'rs7', year: '2020' },\n        { branch: 'ford', model: 'mustang', year: '2019' },\n        { branch: 'ford', model: 'explorer', year: '2020' },\n        { branch: 'bmw', model: 'x7', year: '2020' },\n    ],\n    'branch'\n);\n\n/*\n{\n    audi: [\n        { branch: 'audi', model: 'q8', year: '2019' },\n        { branch: 'audi', model: 'rs7', year: '2020' }\n    ],\n    bmw: [\n        { branch: 'bmw', model: 'x7', year: '2020' }\n    ],\n    ford: [\n        { branch: 'ford', model: 'mustang', year: '2019' },\n        { branch: 'ford', model: 'explorer', year: '2020' }\n    ],\n}\n*/\n```\n"
  },
  {
    "path": "contents/hide-an-element.mdx",
    "content": "---\ncategory: DOM\ncontributors:\n    - iamdileepkumar\n    - islamozbek\ncreated: '2020-04-19'\ntitle: Hide an element\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js hide.js\n// Pick the method that is suitable for your use case\nconst hide = (ele) => (ele.style.display = 'none');\n\n// Or\nconst hide = (ele) => (ele.style.visibility = 'hidden');\n\n// Or\nconst hide = (ele) => (ele.hidden = true);\n```\n\n**TypeScript version**\n\n```ts hide.ts\nconst hide = (ele: HTMLElement): string => (ele.style.display = 'none');\n\n// Or\nconst hide = (ele: HTMLElement): string => (ele.style.visibility = 'hidden');\n\n// Or\nconst hide = (ele: HTMLElement): boolean => (ele.hidden = true);\n```\n"
  },
  {
    "path": "contents/identity-function.mdx",
    "content": "---\ncategory: Function\ncreated: '2020-05-07'\ntitle: Identity function\n---\n\n**JavaScript version**\n\n```js identity.js\nconst identity = (x) => x;\n```\n"
  },
  {
    "path": "contents/immutably-rename-object-keys.mdx",
    "content": "---\ncategory: Object\ncontributors:\n    - imyangyong\ncreated: '2021-01-11'\ntitle: Immutably rename object keys\n---\n\n**JavaScript version**\n\n```js renameKeys.js\nconst renameKeys = (keysMap, obj) =>\n    Object.keys(obj).reduce((acc, key) => ({ ...acc, ...{ [keysMap[key] || key]: obj[key] } }), {});\n```\n\n**Examples**\n\n```js examples.js\nconst obj = { a: 1, b: 2, c: 3 };\nconst keysMap = { a: 'd', b: 'e', c: 'f' };\nrenameKeys(keysMap, obj); // { d: 1, e: 2, f: 3 }\n```\n"
  },
  {
    "path": "contents/initialize-the-current-date-but-set-time-to-midnight.mdx",
    "content": "---\ncategory: Date Time\ncreated: '2021-04-20'\ntitle: Initialize the current date but set time to midnight\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js midnightOfToday.js\nconst midnightOfToday = () => new Date(new Date().setHours(0, 0, 0, 0));\n```\n\n**TypeScript version**\n\n```ts midnightOfToday.ts\nconst midnightOfToday = (): Date => new Date(new Date().setHours(0, 0, 0, 0));\n```\n"
  },
  {
    "path": "contents/insert-an-element-after-other-one.mdx",
    "content": "---\ncategory: DOM\ncreated: '2020-04-19'\ntitle: Insert an element after other one\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js insertAfter.js\nconst insertAfter = (ele, anotherEle) => anotherEle.parentNode.insertBefore(ele, anotherEle.nextSibling);\n\n// Or\nconst insertAfter = (ele, anotherEle) => anotherEle.insertAdjacentElement('afterend', ele);\n```\n\n**TypeScript version**\n\n```ts insertAfter.ts\nconst insertAfter = (ele: Element, anotherEle: Element): Element | null =>\n    anotherEle.parentNode ? anotherEle.parentNode.insertBefore(ele, anotherEle.nextSibling) : null;\n\n// Or\nconst insertAfter = (ele: Element, anotherEle: Element): Element | null =>\n    anotherEle.insertAdjacentElement('afterend', ele);\n```\n"
  },
  {
    "path": "contents/insert-an-element-before-other-one.mdx",
    "content": "---\ncategory: DOM\ncreated: '2020-04-19'\ntitle: Insert an element before other one\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js insertBefore.js\nconst insertBefore = (ele, anotherEle) => anotherEle.parentNode.insertBefore(ele, anotherEle);\n\n// Or\nconst insertBefore = (ele, anotherEle) => anotherEle.insertAdjacentElement('beforebegin', ele);\n```\n\n**TypeScript version**\n\n```ts insertBefore.ts\nconst insertBefore = (ele: Element, anotherEle: Element): Element | null =>\n    anotherEle.parentNode ? anotherEle.parentNode.insertBefore(ele, anotherEle) : null;\n\n// Or\nconst insertBefore = (ele: Element, anotherEle: Element) => anotherEle.insertAdjacentElement('beforebegin', ele);\n```\n"
  },
  {
    "path": "contents/insert-given-html-after-an-element.mdx",
    "content": "---\ncategory: DOM\ncreated: '2020-04-19'\ntitle: Insert given HTML after an element\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js insertHtmlAfter.js\nconst insertHtmlAfter = (html, ele) => ele.insertAdjacentHTML('afterend', html);\n```\n\n**TypeScript version**\n\n```ts insertHtmlAfter.ts\nconst insertHtmlAfter = (html: string, ele: Element): void => ele.insertAdjacentHTML('afterend', html);\n```\n"
  },
  {
    "path": "contents/insert-given-html-before-an-element.mdx",
    "content": "---\ncategory: DOM\ncreated: '2020-04-19'\ntitle: Insert given HTML before an element\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js insertHtmlBefore.js\nconst insertHtmlBefore = (html, ele) => ele.insertAdjacentHTML('beforebegin', html);\n```\n\n**TypeScript version**\n\n```ts insertHtmlBefore.ts\nconst insertHtmlBefore = (html: string, ele: Element): void => ele.insertAdjacentHTML('beforebegin', html);\n```\n"
  },
  {
    "path": "contents/intersperse-element-between-elements.mdx",
    "content": "---\ncategory: Array\ncontributors:\n    - iamandrewluca\ncreated: '2021-12-24'\ntitle: Intersperse element between elements\n---\n\n**JavaScript version**\n\n```js intersperse.js\nconst intersperse = (a, s) => [...Array(2 * a.length - 1)].map((_, i) => (i % 2 ? s : a[i / 2]));\n```\n\n**TypeScript version**\n\n```ts\nconst intersperse = <T>(a: T[], s: T): T[] => [...Array(2 * a.length - 1)].map((_, i) => (i % 2 ? s : a[i / 2]));\n```\n\n**Examples**\n\n```tsx\nintersperse(['A', 'B', 'C'], '/'); // ['A', '/', 'B', '/', 'C']\nintersperse([<li>A</li>, <li>B</li>, <li>C</li>], <li>/</li>); // [<li>A</li>, <li>/</li>, <li>B</li>, <li>/</li>, <li>C</li>]\n```\n"
  },
  {
    "path": "contents/invert-keys-and-values-of-an-object.mdx",
    "content": "---\ncategory: Object\ncontributors:\n    - johandalabacka\ncreated: '2020-05-15'\ntitle: Invert keys and values of an object\nupdated: '2020-12-27'\n---\n\n**JavaScript version**\n\n```js invert.js\nconst invert = (obj) => Object.keys(obj).reduce((res, k) => Object.assign(res, { [obj[k]]: k }), {});\n\n// Or\nconst invert = (obj) => Object.fromEntries(Object.entries(obj).map(([k, v]) => [v, k]));\n```\n\n**Examples**\n\n```js examples.js\ninvert({ a: '1', b: '2', c: '3' }); // { 1: 'a', 2: 'b', 3: 'c' }\n```\n"
  },
  {
    "path": "contents/linear-scale-number-in-ranges.mdx",
    "content": "---\ncategory: Math\ncontributors:\n    - iamandrewluca\ncreated: '2023-09-28'\ntitle: Linear Scale of a Number between two ranges\n---\n\n**JavaScript version**\n\n```js linear-scale.js\nfunction linearScale(value, inMin, inMax, outMin, outMax) {\n    return ((value - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin;\n}\n```\n\n**TypeScript version**\n\n```ts linear-scale.ts\nfunction linearScale(value: number, inMin: number, inMax: number, outMin: number, outMax: number) {\n    return ((value - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin;\n}\n```\n\n**Examples**\n\n```js examples.js\nlinearScale(5, 0, 10, 0, 100); // 50\nlinearScale(10, 10, 20, 0, 100); // 0\nlinearScale(3, 0, 9, 0, 90); // 30\n```\n\n## See also\n\n-   [Normalize the ratio of a number in a range](https://phuoc.ng/collection/1-loc/normalize-the-ratio-of-a-number-in-a-range)\n-   [Calculate the linear interpolation between two numbers](https://phuoc.ng/collection/1-loc/calculate-the-linear-interpolation-between-two-numbers)\n"
  },
  {
    "path": "contents/linear-scale-of-a-number-between-two-ranges.mdx",
    "content": "---\nauthor: iamandrewluca\ncategory: Math\ncontributors:\n    - iamandrewluca\ncreated: '2023-09-28'\nopenGraphCover: /og/1-loc/linear-scale-number-between-two-ranges.png\ntitle: Linear scale of a number between two ranges\n---\n\n**JavaScript version**\n\n```js linear-scale.js\nconst linearScale = (value, inMin, inMax, outMin, outMax) =>\n    ((value - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin;\n```\n\n**TypeScript version**\n\n```ts linear-scale.ts\nconst linearScale = (value: number, inMin: number, inMax: number, outMin: number, outMax: number): number =>\n    ((value - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin;\n```\n\n**Examples**\n\n```js examples.js\nlinearScale(5, 0, 10, 0, 100);      // 50\nlinearScale(10, 10, 20, 0, 100);    // 0\nlinearScale(3, 0, 9, 0, 90);        // 30\n```\n\n## See also\n\n-   [Normalize the ratio of a number in a range](https://phuoc.ng/collection/1-loc/normalize-the-ratio-of-a-number-in-a-range/)\n-   [Calculate the linear interpolation between two numbers](https://phuoc.ng/collection/1-loc/calculate-the-linear-interpolation-between-two-numbers/)\n"
  },
  {
    "path": "contents/logical-xor-operator.mdx",
    "content": "---\ncategory: Function\ncreated: '2020-05-13'\ntitle: Logical xor operator\n---\n\n**JavaScript version**\n\n```js\n// returns `true` if one of the arguments is truthy and the other is falsy\n\nconst xor = (a, b) => (a && !b) || (!a && b);\n\n// Or\nconst xor = (a, b) => !(!a && !b) && !(a && b);\n\n// Or\nconst xor = (a, b) => Boolean(!a ^ !b);\n```\n\n**Examples**\n\n```js examples.js\nxor(true, true); // false\nxor(false, false); // false\nxor(true, false); // true\nxor(false, true); // true\n```\n"
  },
  {
    "path": "contents/make-the-first-character-of-a-string-lowercase.mdx",
    "content": "---\ncategory: String\ncreated: '2020-05-03'\ntitle: Make the first character of a string lowercase\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js lowercaseFirst.js\nconst lowercaseFirst = (str) => `${str.charAt(0).toLowerCase()}${str.slice(1)}`;\n```\n\n**TypeScript version**\n\n```ts lowercaseFirst.ts\nconst lowercaseFirst = (str: string): string => `${str.charAt(0).toLowerCase()}${str.slice(1)}`;\n```\n\n**Examples**\n\n```js examples.js\nlowercaseFirst('Hello World'); // 'hello World'\n```\n"
  },
  {
    "path": "contents/memoize-a-function.mdx",
    "content": "---\ncategory: Function\ncontributors:\n    - Kikobeats\ncreated: '2020-05-16'\ntitle: Memoize a function\nupdated: '2021-10-06'\n---\n\n**JavaScript version**\n\n```js memoize.js\nconst memoize = (fn) =>\n    (\n        (cache = Object.create(null)) =>\n        (arg) =>\n            cache[arg] || (cache[arg] = fn(arg))\n    )();\n```\n\n**Examples**\n\n```js examples.js\n// Calculate Fibonacci numbers\nconst fibo = memoize((n) => (n <= 2 ? 1 : fibo(n - 1) + fibo(n - 2)));\n\nfibo(1); // 1\nfibo(2); // 1\nfibo(3); // 2\nfibo(4); // 3\nfibo(5); // 5\nfibo(6); // 8\n```\n"
  },
  {
    "path": "contents/merge-two-arrays.mdx",
    "content": "---\ncategory: Array\ncreated: '2020-04-19'\ntitle: Merge two arrays\nupdated: '2021-10-22'\n---\n\n**JavaScript version**\n\n```js merge.js\n// Merge but don't remove the duplications\nconst merge = (a, b) => a.concat(b);\n// Or\nconst merge = (a, b) => [...a, ...b];\n\n// Merge and remove the duplications\nconst merge = (a, b) => [...new Set(a.concat(b))];\n// Or\nconst merge = (a, b) => [...new Set([...a, ...b])];\n```\n\n**TypeScript version**\n\n```ts merge.ts\n// Merge but don't remove the duplications\nconst merge = <T,_>(a: T[], b: T[]): T[] => a.concat(b);\n// Or\nconst merge = <T,_>(a: T[], b: T[]): T[] => [...a, ...b];\n\n// Merge and remove the duplications\nconst merge = <T,_>(a: T[], b: T[]): T[] => [...new Set(a.concat(b))];\n// Or\nconst merge = <T,_>(a: T[], b: T[]): T[] => [...new Set([...a, ...b])];\n```\n"
  },
  {
    "path": "contents/multiply-arguments.mdx",
    "content": "---\ncategory: Number\ncreated: '2020-05-05'\ntitle: Multiply arguments\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js mul.js\nconst mul = (...args) => args.reduce((a, b) => a * b);\n```\n\n**TypeScript version**\n\n```ts mul.ts\nconst mul = (...args: number[]): number => args.reduce((a, b) => a * b);\n```\n\n**Examples**\n\n```js examples.js\nmul(1, 2, 3, 4); // 24\n```\n"
  },
  {
    "path": "contents/normalize-file-path-slashes.mdx",
    "content": "---\ncategory: String\ncreated: '2020-05-15'\ntitle: Normalize file path slashes\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js normalizePath.js\nconst normalizePath = (path) => path.replace(/[\\\\/]+/g, '/');\n```\n\n**TypeScript version**\n\n```ts normalizePath.ts\nconst normalizePath = (path: string): string => path.replace(/[\\\\/]+/g, '/');\n```\n\n**Examples**\n\n```js examples.js\nnormalizePath('\\\\foo\\\\bar\\\\baz\\\\'); // /foo/bar/baz/\nnormalizePath('.//foo//bar///////baz/'); // ./foo/bar/baz/\n```\n"
  },
  {
    "path": "contents/normalize-the-ratio-of-a-number-in-a-range.mdx",
    "content": "---\ncategory: Math\ncreated: '2021-05-24'\ntitle: Normalize the ratio of a number in a range\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js normalizeRatio.js\nconst normalizeRatio = (value, min, max) => (value - min) / (max - min);\n```\n\n**TypeScript version**\n\n```ts normalizeRatio.ts\nconst normalizeRatio = (value: number, min: number, max: number): number => (value - min) / (max - min);\n```\n\n## See also\n\n-   [Calculate the linear interpolation between two numbers](https://phuoc.ng/collection/1-loc/calculate-the-linear-interpolation-between-two-numbers/)\n-   [Linear scale of a number between two ranges](https://phuoc.ng/collection/1-loc/linear-scale-of-a-number-between-two-ranges/)\n"
  },
  {
    "path": "contents/omit-a-subset-of-properties-from-an-object.mdx",
    "content": "---\ncategory: Object\ncreated: '2020-05-13'\ntitle: Omit a subset of properties from an object\n---\n\n**JavaScript version**\n\n```js omit.js\nconst omit = (obj, keys) =>\n    Object.keys(obj)\n        .filter((k) => !keys.includes(k))\n        .reduce((res, k) => Object.assign(res, { [k]: obj[k] }), {});\n```\n\n**Examples**\n\n```js examples.js\nomit({ a: '1', b: '2', c: '3' }, ['a', 'b']); // { c: '3' }\n```\n"
  },
  {
    "path": "contents/partially-apply-a-function.mdx",
    "content": "---\ncategory: Function\ncreated: '2020-05-13'\ntitle: Partially apply a function\n---\n\n**JavaScript version**\n\n```js partial.js\nconst partial =\n    (fn, ...a) =>\n    (...b) =>\n        fn(...a, ...b);\n```\n\n**Examples**\n\n```js examples.js\nconst sum = (x, y) => x + y;\nconst inc = partial(sum, 1);\ninc(9); // 10\n```\n"
  },
  {
    "path": "contents/partition-an-array-based-on-a-condition.mdx",
    "content": "---\ncategory: Array\ncontributors:\n    - TangSY\ncreated: '2020-05-13'\ntitle: Partition an array based on a condition\nupdated: '2021-10-22'\n---\n\n**JavaScript version**\n\n```js partition.js\nconst partition = (arr, criteria) => arr.reduce((acc, i) => (acc[criteria(i) ? 0 : 1].push(i), acc), [[], []]);\n```\n\n**TypeScript version**\n\n```ts partition.ts\nconst partition = <T,_>(arr: T[], criteria: (a: T) => boolean): T[][] => arr.reduce((acc, i) => (acc[criteria(i) ? 0 : 1].push(i), acc), [[], []]);\n```\n\n**Example**\n\n```js example.js\npartition([1, 2, 3, 4, 5], (n) => n % 2); // [[1, 3, 5], [2, 4]]\n```\n"
  },
  {
    "path": "contents/pick-a-random-property-of-an-object.mdx",
    "content": "---\ncategory: Random\ncreated: '2021-04-19'\ntitle: Pick a random property of an object\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js randomProp.js\nconst randomProp = (obj) => Object.keys(obj)[(Math.random() * Object.keys(obj).length) | 0];\n```\n\n**TypeScript version**\n\n```ts randomProp.ts\nconst randomProp = (obj: object): any => Object.keys(obj)[(Math.random() * Object.keys(obj).length) | 0];\n```\n\n**Examples**\n\n```js examples.js\nconst colors = {\n    aqua: '#00ffff',\n    azure: '#f0ffff',\n    beige: '#f5f5dc',\n    black: '#000000',\n    blue: '#0000ff',\n    brown: '#a52a2a',\n    cyan: '#00ffff',\n    darkblue: '#00008b',\n    darkcyan: '#008b8b',\n    darkgrey: '#a9a9a9',\n    darkgreen: '#006400',\n    darkkhaki: '#bdb76b',\n    darkmagenta: '#8b008b',\n    darkolivegreen: '#556b2f',\n    darkorange: '#ff8c00',\n    darkorchid: '#9932cc',\n    darkred: '#8b0000',\n    darksalmon: '#e9967a',\n    darkviolet: '#9400d3',\n    fuchsia: '#ff00ff',\n    gold: '#ffd700',\n    green: '#008000',\n    indigo: '#4b0082',\n    khaki: '#f0e68c',\n    lightblue: '#add8e6',\n    lightcyan: '#e0ffff',\n    lightgreen: '#90ee90',\n    lightgrey: '#d3d3d3',\n    lightpink: '#ffb6c1',\n    lightyellow: '#ffffe0',\n    lime: '#00ff00',\n    magenta: '#ff00ff',\n    maroon: '#800000',\n    navy: '#000080',\n    olive: '#808000',\n    orange: '#ffa500',\n    pink: '#ffc0cb',\n    purple: '#800080',\n    violet: '#800080',\n    red: '#ff0000',\n    silver: '#c0c0c0',\n    white: '#ffffff',\n    yellow: '#ffff00',\n};\nrandomProp(colors); // 'red'\n```\n"
  },
  {
    "path": "contents/pick-a-subset-of-properties-of-an-object.mdx",
    "content": "---\ncategory: Object\ncreated: '2020-05-13'\ntitle: Pick a subset of properties of an object\n---\n\n**JavaScript version**\n\n```js pick.js\nconst pick = (obj, keys) =>\n    Object.keys(obj)\n        .filter((k) => keys.includes(k))\n        .reduce((res, k) => Object.assign(res, { [k]: obj[k] }), {});\n```\n\n**Examples**\n\n```js examples.js\npick({ a: '1', b: '2', c: '3' }, ['a', 'b']); // { a: '1', b: '2' }\n```\n"
  },
  {
    "path": "contents/pick-random-lines-from-a-text-document.mdx",
    "content": "---\ncategory: Random\ncreated: '2021-06-01'\ntitle: Pick random lines from a text document\n---\n\n**JavaScript version**\n\n```js randomLines.js\nconst randomLines = (str, count) =>\n    str\n        .split(/\\r?\\n/)\n        .reduce(\n            (p, _, __, arr) =>\n                p[0] < count ? [p[0] + 1, p[1].concat(arr.splice((Math.random() * arr.length) | 0, 1))] : p,\n            [0, []]\n        )[1];\n```\n\n**Examples**\n\n```js examples.js\nrandomLines(\n    `one\ntwo\nthree\nfour\nfive`,\n    2\n);\n\n// ['one', 'four']\n```\n"
  },
  {
    "path": "contents/prefix-an-integer-with-zeros.mdx",
    "content": "---\ncategory: Number\ncontributors:\n    - VincentRoth\ncreated: '2020-04-23'\ntitle: Prefix an integer with zeros\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js prefixWithZeros.js\nconst prefixWithZeros = (n, length) => (n / Math.pow(10, length)).toFixed(length).substr(2);\n\n// Or\nconst prefixWithZeros = (n, length) => `${Array(length).join('0')}${n}`.slice(-length);\n\n// Or\nconst prefixWithZeros = (n, length) => String(n).padStart(length, '0');\n```\n\n**TypeScript version**\n\n```ts prefixWithZeros.ts\nconst prefixWithZeros = (n: number, length: number): string => (n / Math.pow(10, length)).toFixed(length).substr(2);\n\n// Or\nconst prefixWithZeros = (n: number, length: number): string => `${Array(length).join('0')}${n}`.slice(-length);\n\n// Or\nconst prefixWithZeros = (n: number, length: number): string => String(n).padStart(length, '0');\n```\n\n**Examples**\n\n```js examples.js\nprefixWithZeros(42, 5); // '00042'\n```\n"
  },
  {
    "path": "contents/prepend-a-line-number-to-each-line-of-a-text-document.mdx",
    "content": "---\ncategory: String\ncreated: '2021-06-07'\ntitle: Prepend a line number to each line of a text document\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js prependNumbers.js\nconst prependNumbers = (str) =>\n    str\n        .split(/\\r?\\n/)\n        .map((line, i) => `${(i + 1).toString().padStart(2, ' ')} ${line}`)\n        .join('\\n');\n```\n\n**TypeScript version**\n\n```ts prependNumbers.ts\nconst prependNumbers = (str: string): string =>\n    str\n        .split(/\\r?\\n/)\n        .map((line, i) => `${(i + 1).toString().padStart(2, ' ')} ${line}`)\n        .join('\\n');\n```\n\n**Examples**\n\n```js examples.js\nprependNumbers(`one\ntwo\nthree\nfour`);\n\n/* Output */\n/*\n1 one\n2 two\n3 three\n4 four\n*/\n```\n"
  },
  {
    "path": "contents/redirect-the-page-to-https-if-it-is-in-http.mdx",
    "content": "---\ncategory: Misc\ncreated: '2020-05-31'\ntitle: Redirect the page to HTTPS if it is in HTTP\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js redirectHttps.js\nconst redirectHttps = () =>\n    location.protocol === 'https:' ? {} : location.replace(`https://${location.href.split('//')[1]}`);\n\n// Or\nconst redirectHttps = () => (location.protocol === 'https:' ? {} : (location.protocol = 'https:'));\n```\n\n**TypeScript version**\n\n```ts redirectHttps.ts\nconst redirectHttps = (): void =>\n    location.protocol === 'https:' ? void 0 : location.replace(`https://${location.href.split('//')[1]}`);\n\n// Or\nconst redirectHttps = (): string => (location.protocol === 'https:' ? '' : (location.protocol = 'https:'));\n```\n"
  },
  {
    "path": "contents/redirect-to-another-page.mdx",
    "content": "---\ncategory: DOM\ncreated: '2020-04-19'\ntitle: Redirect to another page\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js goTo.js\nconst goTo = (url) => (location.href = url);\n```\n\n**TypeScript version**\n\n```ts goTo.ts\nconst goTo = (url: string): string => (location.href = url);\n```\n"
  },
  {
    "path": "contents/reload-the-current-page.mdx",
    "content": "---\ncategory: DOM\ncreated: '2020-04-19'\ntitle: Reload the current page\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js reload.js\nconst reload = () => location.reload();\n\n// Or\nconst reload = () => (location.href = location.href);\n```\n\n**TypeScript version**\n\n```ts reload.ts\nconst reload = (): void => location.reload();\n\n// Or\nconst reload = (): string => (location.href = location.href);\n```\n"
  },
  {
    "path": "contents/remove-all-null-and-undefined-properties-from-an-object.mdx",
    "content": "---\ncategory: Object\ncontributors:\n    - jjswifty\ncreated: '2021-04-20'\ntitle: Remove all null and undefined properties from an object\nupdated: '2023-05-15'\n---\n\n**JavaScript version**\n\n```js removeNullUndefined.js\nconst removeNullUndefined = (obj) => Object.entries(obj).reduce((a, [k, v]) => (v == null ? a : ((a[k] = v), a)), {});\n\n// Or\nconst removeNullUndefined = (obj) =>\n    Object.entries(obj)\n        .filter(([_, v]) => v != null)\n        .reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {});\n\n// Or\nconst removeNullUndefined = (obj) => Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));\n```\n\n**TypeScript version**\n\n```ts\nconst removeNullUndefined = <T extends Record<string, any>>(obj: T) =>\n\tObject.entries(obj).reduce((a: any, [k, v]) =>\n\t\t(v == null ? a : ((a[k] = v), a)), {}) as {\n\t\t[K in keyof T as T[K] extends null | undefined ? never : K]: T[K]\n\t};\n\n// Or\nconst removeNullUndefined = <T extends Record<string, any>>(obj: T) =>\n\tObject.entries(obj)\n\t\t.filter(([_, v]) => v != null)\n\t\t.reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {}) as {\n\t\t[K in keyof T as T[K] extends null | undefined ? never : K]: T[K]\n\t};\n\n// Or\nconst removeNullUndefined = <T extends Record<string, any>>(obj: T) =>\n\tObject.fromEntries(Object.entries(obj).filter(([_, v]) => v != null)) as {\n\t\t[K in keyof T as T[K] extends null | undefined ? never : K]: T[K]\n\t};\n```\n\n**Examples**\n\n```js examples.js\nremoveNullUndefined({\n    foo: null,\n    bar: undefined,\n    fuzz: 42,\n}); // { fuzz: 42 }\n```\n"
  },
  {
    "path": "contents/remove-duplicate-lines-of-a-text-document.mdx",
    "content": "---\ncategory: String\ncreated: '2021-05-31'\ntitle: Remove duplicate lines of a text document\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js removeDuplicateLines.js\nconst removeDuplicateLines = (str) => Array.from(new Set(str.split(/\\r?\\n/))).join('\\n');\n```\n\n**TypeScript version**\n\n```ts removeDuplicateLines.ts\nconst removeDuplicateLines = (str: string): string => Array.from(new Set(str.split(/\\r?\\n/))).join('\\n');\n```\n\n**Examples**\n\n```js examples.js\nremoveDuplicateLines(`one\nthree\ntwo\nthree\none\nfour`);\n\n/* Output */\n/*\none\nthree\ntwo\nfour\n*/\n```\n"
  },
  {
    "path": "contents/remove-duplicate-values-in-an-array.mdx",
    "content": "---\ncategory: Array\ncreated: '2021-03-07'\ntitle: Remove duplicate values in an array\nupdated: '2021-10-22'\n---\n\n**JavaScript version**\n\n```js removeDuplicate.js\nconst removeDuplicate = (arr) => arr.filter((i) => arr.indexOf(i) === arr.lastIndexOf(i));\n```\n\n**TypeScript version**\n\n```ts removeDuplicate.ts\nconst removeDuplicate = <T,_>(arr: T[]): T[] => arr.filter((i) => arr.indexOf(i) === arr.lastIndexOf(i));\n```\n\n**Example**\n\n```js example.js\nremoveDuplicate(['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']); //  ['h', 'e', 'w', 'r', 'd']\n```\n"
  },
  {
    "path": "contents/remove-empty-lines-of-a-text-document.mdx",
    "content": "---\ncategory: String\ncreated: '2021-05-28'\ntitle: Remove empty lines of a text document\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js removeEmptyLines.js\nconst removeEmptyLines = (str) =>\n    str\n        .split(/\\r?\\n/)\n        .filter((line) => line.trim() !== '')\n        .join('\\n');\n```\n\n**TypeScript version**\n\n```ts removeEmptyLines.ts\nconst removeEmptyLines = (str: string): string =>\n    str\n        .split(/\\r?\\n/)\n        .filter((line) => line.trim() !== '')\n        .join('\\n');\n```\n\n**Examples**\n\n```js examples.js\nremoveEmptyLines(`red\n\ngreen\nblue\n\nyellow`);\n\n/* Output */\n/*\nred\ngreen\nblue\nyellow\n*/\n```\n"
  },
  {
    "path": "contents/remove-falsy-values-from-array.mdx",
    "content": "---\ncategory: Array\ncontributors:\n    - vreymond\ncreated: '2020-05-09'\ntitle: Remove falsy values from array\nupdated: '2021-10-22'\n---\n\n**JavaScript version**\n\n```js removeFalsy.js\nconst removeFalsy = (arr) => arr.filter(Boolean);\n```\n\n**TypeScript version**\n\n```ts removeFalsy.ts\nconst removeFalsy = <T,_>(arr: T[]): T[] => arr.filter(Boolean);\n```\n\n**Example**\n\n```js example.js\nremoveFalsy([0, 'a string', '', NaN, true, 5, undefined, 'another string', false]);\n// ['a string', true, 5, 'another string']\n```\n"
  },
  {
    "path": "contents/remove-spaces-from-a-string.mdx",
    "content": "---\ncategory: String\ncreated: '2020-05-03'\ntitle: Remove spaces from a string\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js removeSpaces.js\nconst removeSpaces = (str) => str.replace(/\\s/g, '');\n```\n\n**TypeScript version**\n\n```ts removeSpaces.ts\nconst removeSpaces = (str: string): string => str.replace(/\\s/g, '');\n```\n\n**Examples**\n\n```js examples.js\nremoveSpaces('hel lo wor ld'); // 'helloworld'\n```\n"
  },
  {
    "path": "contents/repeat-a-string.mdx",
    "content": "---\ncategory: String\ncontributors:\n    - chety\ncreated: '2020-04-19'\ntitle: Repeat a string\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js repeat.js\nconst repeat = (str, numberOfTimes) => str.repeat(numberOfTimes);\n\n// Or\nconst repeat = (str, numberOfTimes) => Array(numberOfTimes + 1).join(str);\n```\n\n**TypeScript version**\n\n```ts repeat.ts\nconst repeat = (str: string, numberOfTimes: number): string => str.repeat(numberOfTimes);\n\n// Or\nconst repeat = (str: string, numberOfTimes: number): string => Array(numberOfTimes + 1).join(str);\n```\n"
  },
  {
    "path": "contents/repeat-an-array.mdx",
    "content": "---\ncategory: Array\ncreated: '2021-07-21'\ntitle: Repeat an array\nupdated: '2021-10-22'\n---\n\n**JavaScript version**\n\n```js repeat.js\n// `arr` is an array\nconst repeat = (arr, n) => [].concat(...Array(n).fill(arr));\n\n// Or\nconst repeat = (arr, n) => Array(n).fill(arr).flat();\n\n// Or\nconst repeat = (arr, n) =>\n    Array(arr.length * n)\n        .fill(0)\n        .map((_, i) => arr[i % arr.length]);\n\n// Or\nconst repeat = (arr, n) => Array.from({ length: arr.length * n }, (_, i) => arr[i % arr.length]);\n```\n\n**TypeScript version**\n\n```ts repeat.ts\nconst repeat = <T,_>(arr: T[], n: number): T[] => [].concat(...Array(n).fill(arr));\n\n// Or\nconst repeat = <T,_>(arr: T[], n: number): T[] => Array(n).fill(arr).flat();\n\n// Or\nconst repeat = <T,_>(arr: T[], n: number): T[] =>\n    Array(arr.length * n)\n        .fill(0)\n        .map((_, i) => arr[i % arr.length]);\n\n// Or\nconst repeat = <T,_>(arr: T[], n: number): T[] => Array.from({ length: arr.length * n }, (_, i) => arr[i % arr.length]);\n```\n\n**Example**\n\n```js example.js\nrepeat([1, 2, 3], 3); // [1, 2, 3, 1, 2, 3, 1, 2, 3]\n```\n"
  },
  {
    "path": "contents/replace-all-line-breaks-with-br-elements.mdx",
    "content": "---\ncategory: String\ncreated: '2020-04-19'\ntitle: Replace all line breaks with br elements\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js nl2br.js\nconst nl2br = (str) => str.replace(new RegExp('\\r?\\n', 'g'), '<br>');\n\n// In React\nstr.split('\\n').map((item, index) => (\n    <React.Fragment key={index}>\n        {item}\n        <br />\n    </React.Fragment>\n));\n```\n\n**TypeScript version**\n\n```ts nl2br.ts\nconst nl2br = (str: string): string => str.replace(new RegExp('\\r?\\n', 'g'), '<br>');\n```\n"
  },
  {
    "path": "contents/replace-all-tab-characters-with-spaces.mdx",
    "content": "---\ncategory: String\ncreated: '2021-05-27'\ntitle: Replace all tab characters with spaces\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js replace.js\nconst replace = (str, numSpaces = 4) => str.replaceAll('\\t', ' '.repeat(numSpaces));\n```\n\n**TypeScript version**\n\n```ts replace.ts\nconst replace = (str: string, numSpaces = 4): string => str.replaceAll('\\t', ' '.repeat(numSpaces));\n```\n"
  },
  {
    "path": "contents/replace-an-element.mdx",
    "content": "---\ncategory: DOM\ncreated: '2020-04-19'\ntitle: Replace an element\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js replace.js\nconst replace = (ele, newEle) => ele.parentNode.replaceChild(newEle, ele);\n```\n\n**TypeScript version**\n\n```ts replace.ts\nconst replace = (ele: Element, newEle: Element): Element | null =>\n    ele.parentNode ? ele.parentNode.replaceChild(newEle, ele) : null;\n```\n"
  },
  {
    "path": "contents/replace-multiple-spaces-with-a-single-space.mdx",
    "content": "---\ncategory: String\ncreated: '2020-05-09'\ntitle: Replace multiple spaces with a single space\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js replaceSpaces.js\n// Replace spaces, tabs and new line characters\nconst replaceSpaces = (str) => str.replace(/\\s\\s+/g, ' ');\n\n// Only replace spaces\nconst replaceOnlySpaces = (str) => str.replace(/  +/g, ' ');\n```\n\n**TypeScript version**\n\n```ts replaceSpaces.ts\nconst replaceSpaces = (str: string): string => str.replace(/\\s\\s+/g, ' ');\n\nconst replaceOnlySpaces = (str: string): string => str.replace(/  +/g, ' ');\n```\n\n**Examples**\n\n```js examples.js\nreplaceSpaces('this\\n   is     \\ta    \\rmessage'); // 'this is a message'\n```\n"
  },
  {
    "path": "contents/replace-the-first-given-number-of-characters-of-a-string-with-another-character.mdx",
    "content": "---\ncategory: String\ncreated: '2020-06-15'\ntitle: Replace the first given number of characters of a string with another character\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js mask.js\nconst mask = (str, num, mask) => `${str}`.slice(num).padStart(`${str}`.length, mask);\n```\n\n**TypeScript version**\n\n```ts mask.ts\nconst mask = (str: string, num: number, mask: string): string => `${str}`.slice(num).padStart(`${str}`.length, mask);\n```\n\n**Examples**\n\n```js examples.js\nmask(1234567890, 3, '*'); // ***4567890\n```\n"
  },
  {
    "path": "contents/reverse-a-string.mdx",
    "content": "---\ncategory: String\ncreated: '2020-04-19'\ntitle: Reverse a string\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js reverse.js\nconst reverse = (str) => str.split('').reverse().join('');\n\n// Or\nconst reverse = (str) => [...str].reverse().join('');\n\n// Or\nconst reverse = (str) => str.split('').reduce((rev, char) => `${char}${rev}`, '');\n\n// Or\nconst reverse = (str) => (str === '' ? '' : `${reverse(str.substr(1))}${str.charAt(0)}`);\n```\n\n**TypeScript version**\n\n```ts reverse.ts\nconst reverse = (str: string): string => str.split('').reverse().join('');\n\n// Or\nconst reverse = (str: string): string => [...str].reverse().join('');\n\n// Or\nconst reverse = (str: string): string => str.split('').reduce((rev, char) => `${char}${rev}`, '');\n\n// Or\nconst reverse = (str: string): string => (str === '' ? '' : `${reverse(str.substr(1))}${str.charAt(0)}`);\n```\n\n**Examples**\n\n```js examples.js\nreverse('hello world'); // 'dlrow olleh'\n```\n"
  },
  {
    "path": "contents/reverse-the-order-of-lines-of-a-text.mdx",
    "content": "---\ncategory: String\ncreated: '2021-05-30'\ntitle: Reverse the order of lines of a text\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js reverseLines.js\nconst reverseLines = (str) => str.split(/\\r?\\n/).reverse().join('\\n');\n```\n\n**TypeScript version**\n\n```ts reverseLines.ts\nconst reverseLines = (str: string): string => str.split(/\\r?\\n/).reverse().join('\\n');\n```\n\n**Examples**\n\n```js examples.js\nreverseLines(`one\ntwo\nthree`);\n\n/* Output */\n/*\nthree\ntwo\none\n*/\n```\n"
  },
  {
    "path": "contents/round-a-number-to-a-given-number-of-digits.mdx",
    "content": "---\ncategory: Number\ncreated: '2020-05-16'\ntitle: Round a number to a given number of digits\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js round.js\nconst round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);\n```\n\n**TypeScript version**\n\n```ts round.ts\nconst round = (n: number, decimals: number = 0): number => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);\n```\n\n**Examples**\n\n```js examples.js\nround(1.234567, 3); // 1.235\nround(1.234567, 4); // 1.2346\n```\n"
  },
  {
    "path": "contents/round-a-number-to-the-nearest-multiple-of-a-given-value.mdx",
    "content": "---\ncategory: Math\ncreated: '2021-05-11'\ntitle: Round a number to the nearest multiple of a given value\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js roundNearest.js\nconst roundNearest = (value, nearest) => Math.round(value / nearest) * nearest;\n```\n\n**TypeScript version**\n\n```ts roundNearest.ts\nconst roundNearest = (value: number, nearest: number): number => Math.round(value / nearest) * nearest;\n```\n\n**Examples**\n\n```js examples.js\nroundNearest(100, 30); // 90\nroundNearest(200, 30); // 210\nroundNearest(200, 40); // 200\n```\n"
  },
  {
    "path": "contents/run-promises-in-sequence.mdx",
    "content": "---\ncategory: Misc\ncreated: '2020-05-02'\ntitle: Run Promises in sequence\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js run.js\n// `promises` is an array of `Promise`\nconst run = (promises) => promises.reduce((p, c) => p.then((rp) => c.then((rc) => [...rp, rc])), Promise.resolve([]));\n```\n\n**TypeScript version**\n\n```ts run.ts\nconst run = (promises: Promise<any>[]): Promise<any> =>\n    promises.reduce((p, c) => p.then((rp) => c.then((rc) => [...rp, rc])), Promise.resolve([]));\n```\n\n**Examples**\n\n```js examples.js\nrun(promises).then((results) => {\n    // `results` is an array of promise results in the same order\n});\n```\n"
  },
  {
    "path": "contents/scroll-to-top-of-the-page.mdx",
    "content": "---\ncategory: DOM\ncreated: '2020-04-19'\ntitle: Scroll to top of the page\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js goToTop.js\nconst goToTop = () => window.scrollTo(0, 0);\n```\n\n**TypeScript version**\n\n```ts goToTop.ts\nconst goToTop = (): void => window.scrollTo(0, 0);\n```\n"
  },
  {
    "path": "contents/serialize-form-data.mdx",
    "content": "---\ncategory: DOM\ncreated: '2021-02-01'\ntitle: Serialize form data\n---\n\n**JavaScript version**\n\n```js serialize.js\nconst serialize = (formEle) =>\n    Array.from(new FormData(formEle)).reduce(\n        (p, [k, v]) => Object.assign({}, p, { [k]: p[k] ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v }),\n        {}\n    );\n```\n"
  },
  {
    "path": "contents/shallow-copy-an-object.mdx",
    "content": "---\ncategory: Object\ncontributors:\n    - Namysh\ncreated: '2020-05-13'\ntitle: Shallow copy an object\nupdated: '2020-07-16'\n---\n\n**JavaScript version**\n\n```js shallowCopy.js\nconst shallowCopy = obj => Object.assign({}, obj);\n\n// or\nconst shallowCopy = obj => {...obj};\n```\n"
  },
  {
    "path": "contents/show-an-element.mdx",
    "content": "---\ncategory: DOM\ncreated: '2020-04-19'\ntitle: Show an element\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js show.js\nconst show = (ele) => (ele.style.display = '');\n```\n\n**TypeScript version**\n\n```ts show.ts\nconst show = (ele: HTMLElement): string => (ele.style.display = '');\n```\n"
  },
  {
    "path": "contents/shuffle-an-array.mdx",
    "content": "---\ncategory: Array\ncontributors:\n    - elkarouani\ncreated: '2020-05-20'\ntitle: Shuffle an array\nupdated: '2021-12-22'\n---\n\n**JavaScript version**\n\n```js shuffle.js\nconst shuffle = (arr) =>\n    arr\n        .map((a) => ({ sort: Math.random(), value: a }))\n        .sort((a, b) => a.sort - b.sort)\n        .map((a) => a.value);\n```\n\n**TypeScript version**\n\n```ts shuffle.ts\nconst shuffle = <T,_>(arr: T[]): T[] =>\n    arr\n        .map((a) => ({ sort: Math.random(), value: a }))\n        .sort((a, b) => a.sort - b.sort)\n        .map((a) => a.value);\n```\n\n**Example**\n\n```js example.js\nshuffle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); // [9, 1, 10, 6, 8, 5, 2, 3, 7, 4]\n```\n"
  },
  {
    "path": "contents/sort-an-array-of-dates.mdx",
    "content": "---\ncategory: Date Time\ncreated: '2020-04-19'\ntitle: Sort an array of dates\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js sortDescending.js\n// `arr` is an array of `Date` items\nconst sortDescending = (arr) => arr.sort((a, b) => a.getTime() > b.getTime());\n\nconst sortAscending = (arr) => arr.sort((a, b) => a.getTime() < b.getTime());\n```\n\n**TypeScript version**\n\n```ts sortDescending.ts\nconst sortDescending = (arr: Date[]): Date[] => arr.sort((a, b) => a.getTime() - b.getTime());\n\nconst sortAscending = (arr: Date[]): Date[] => arr.sort((a, b) => b.getTime() - a.getTime());\n```\n"
  },
  {
    "path": "contents/sort-an-array-of-items-by-given-key.mdx",
    "content": "---\ncategory: Array\ncreated: '2021-01-13'\ntitle: Sort an array of items by given key\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js sortBy.js\nconst sortBy = (arr, k) => arr.concat().sort((a, b) => (a[k] > b[k] ? 1 : a[k] < b[k] ? -1 : 0));\n```\n\n**TypeScript version**\n\n```ts sortBy.ts\nconst sortBy = <T extends Record<string, any>, K extends keyof T>(arr: T[], k: K): T[] => (\n    arr.concat().sort((a, b) => (a[k] > b[k] ? 1 : a[k] < b[k] ? -1 : 0))\n);\n```\n\n**Example**\n\n```js example.js\nconst people = [\n    { name: 'Foo', age: 42 },\n    { name: 'Bar', age: 24 },\n    { name: 'Fuzz', age: 36 },\n    { name: 'Baz', age: 32 },\n];\nsortBy(people, 'age');\n\n//  [\n//      { name: 'Bar', age: 24 },\n//      { name: 'Baz', age: 32 },\n//      { name: 'Fuzz', age: 36 },\n//      { name: 'Foo', age: 42 },\n//  ]\n```\n"
  },
  {
    "path": "contents/sort-an-array-of-numbers.mdx",
    "content": "---\ncategory: Array\ncreated: '2020-05-20'\ntitle: Sort an array of numbers\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js sort.js\nconst sort = (arr) => arr.sort((a, b) => a - b);\n```\n\n**TypeScript version**\n\n```ts sort.ts\nconst sort = (arr: number[]): number[] => arr.sort((a, b) => a - b);\n```\n\n**Example**\n\n```js example.js\nsort([1, 5, 2, 4, 3]); // [1, 2, 3, 4, 5]\n```\n"
  },
  {
    "path": "contents/sort-an-object-by-its-properties.mdx",
    "content": "---\ncategory: Object\ncreated: '2021-04-20'\ntitle: Sort an object by its properties\n---\n\n**JavaScript version**\n\n```js sort.js\nconst sort = (obj) =>\n    Object.keys(obj)\n        .sort()\n        .reduce((p, c) => ((p[c] = obj[c]), p), {});\n```\n\n**Examples**\n\n```js examples.js\nconst colors = {\n    white: '#ffffff',\n    black: '#000000',\n    red: '#ff0000',\n    green: '#008000',\n    blue: '#0000ff',\n};\nsort(colors);\n/*\n{\n    black: '#000000',\n    blue: '#0000ff',\n    green: '#008000',\n    red: '#ff0000',\n    white: '#ffffff',\n}\n*/\n```\n"
  },
  {
    "path": "contents/sort-lines-of-a-text-document-in-the-alphabetical-order.mdx",
    "content": "---\ncategory: String\ncreated: '2021-05-26'\ntitle: Sort lines of a text document in the alphabetical order\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js sortLines.js\nconst sortLines = (str) => str.split(/\\r?\\n/).sort().join('\\n');\n\n// Reverse the order\nconst reverseSortedLines = (str) => str.split(/\\r?\\n/).sort().reverse().join('\\n');\n```\n\n**TypeScript version**\n\n```ts sortLines.ts\nconst sortLines = (str: string): string => str.split(/\\r?\\n/).sort().join('\\n');\n\n// Reverse the order\nconst reverseSortedLines = (str: string): string => str.split(/\\r?\\n/).sort().reverse().join('\\n');\n```\n\n**Examples**\n\n```js examples.js\nsortLines(`Thaddeus Mullen\nKareem Marshall\nFerdinand Valentine\nHasad Lindsay\nMufutau Berg\nKnox Tyson\nKasimir Fletcher\nColton Sharp\nAdrian Rosales\nTheodore Rogers`);\n\n/* Output */\n/*\nAdrian Rosales\nColton Sharp\nFerdinand Valentine\nHasad Lindsay\nKareem Marshall\nKasimir Fletcher\nKnox Tyson\nMufutau Berg\nThaddeus Mullen\nTheodore Rogers\n*/\n```\n"
  },
  {
    "path": "contents/sort-the-characters-of-a-string-in-the-alphabetical-order.mdx",
    "content": "---\ncategory: String\ncreated: '2020-05-16'\ntitle: Sort the characters of a string in the alphabetical order\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js sort.js\nconst sort = (str) =>\n    str\n        .split('')\n        .sort((a, b) => a.localeCompare(b))\n        .join('');\n```\n\n**TypeScript version**\n\n```ts sort.ts\nconst sort = (str: string): string =>\n    str\n        .split('')\n        .sort((a, b) => a.localeCompare(b))\n        .join('');\n```\n\n**Examples**\n\n```js examples.js\nsort('hello world'); // dehllloorw\n```\n"
  },
  {
    "path": "contents/split-an-array-into-chunks.mdx",
    "content": "---\ncategory: Array\ncreated: '2020-05-13'\ntitle: Split an array into chunks\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js chunk.js\nconst chunk = (arr, size) =>\n    arr.reduce((acc, e, i) => (i % size ? acc[acc.length - 1].push(e) : acc.push([e]), acc), []);\n```\n\n**TypeScript version**\n\n```ts chunk.ts\nconst chunk = <T,>(arr: T[], size: number): T[][] => (\n    arr.reduce((acc, e, i) => (i % size ? acc[acc.length - 1].push(e) : acc.push([e]), acc), [] as T[][])\n);\n```\n\n**Examples**\n\n```js examples.js\nchunk([1, 2, 3, 4, 5, 6, 7, 8], 3); // [[1, 2, 3], [4, 5, 6], [7, 8]]\nchunk([1, 2, 3, 4, 5, 6, 7, 8], 4); // [[1, 2, 3, 4], [5, 6, 7, 8]]\n```\n"
  },
  {
    "path": "contents/strip-ansi-codes-from-a-string.mdx",
    "content": "---\ncategory: String\ncreated: '2020-06-07'\ntitle: Strip ANSI codes from a string\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js stripAnsiCodes.js\nconst stripAnsiCodes = (str) =>\n    str.replace(/[\\u001b\\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, '');\n```\n\n**TypeScript version**\n\n```ts stripAnsiCodes.ts\nconst stripAnsiCodes = (str: string): string =>\n    str.replace(/[\\u001b\\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, '');\n```\n\n**Examples**\n\n```js examples.js\nstripAnsiCodes('\\u001B[4mcake\\u001B[0m'); // 'cake'\nstripAnsiCodes('\\u001B[0m\\u001B[4m\\u001B[42m\\u001B[31mfoo\\u001B[39m\\u001B[49m\\u001B[24mfoo\\u001B[0m'); // 'foofoo'\n```\n"
  },
  {
    "path": "contents/strip-html-from-a-given-text.mdx",
    "content": "---\ncategory: DOM\ncreated: '2020-04-19'\ntitle: Strip HTML from a given text\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js stripHtml.js\nconst stripHtml = (html) => new DOMParser().parseFromString(html, 'text/html').body.textContent || '';\n```\n\n**TypeScript version**\n\n```ts stripHtml.ts\nconst stripHtml = (html: string): string => new DOMParser().parseFromString(html, 'text/html').body.textContent || '';\n```\n"
  },
  {
    "path": "contents/subtract-arguments.mdx",
    "content": "---\ncategory: Number\ncreated: '2020-05-05'\ntitle: Subtract arguments\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js subtract.js\nconst subtract = (...args) => args.reduce((a, b) => a - b);\n```\n\n**TypeScript version**\n\n```ts subtract.ts\nconst subtract = (...args: number[]): number => args.reduce((a, b) => a - b);\n```\n\n**Examples**\n\n```js examples.js\nsubtract(1, 2, 3, 4); // -8\n```\n"
  },
  {
    "path": "contents/swap-case-of-characters-in-a-string.mdx",
    "content": "---\ncategory: String\ncreated: '2021-02-20'\ntitle: Swap case of characters in a string\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js swapCase.js\nconst swapCase = (str) =>\n    str\n        .split('')\n        .map((c) => (c === c.toLowerCase() ? c.toUpperCase() : c.toLowerCase()))\n        .join('');\n```\n\n**TypeScript version**\n\n```ts swapCase.ts\nconst swapCase = (str: string): string =>\n    str\n        .split('')\n        .map((c) => (c === c.toLowerCase() ? c.toUpperCase() : c.toLowerCase()))\n        .join('');\n```\n\n**Examples**\n\n```js examples.js\nswapCase('Hello World'); // 'hELLO wORLD'\n```\n"
  },
  {
    "path": "contents/swap-the-rows-and-columns-of-a-matrix.mdx",
    "content": "---\ncategory: Array\ncreated: '2020-05-24'\ntitle: Swap the rows and columns of a matrix\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js transpose.js\nconst transpose = (matrix) => matrix[0].map((col, i) => matrix.map((row) => row[i]));\n\n// Or\nconst transpose = (matrix) => matrix[0].map((col, c) => matrix.map((row, r) => matrix[r][c]));\n\n// Or\nconst transpose = (matrix) => matrix.reduce((prev, next) => next.map((item, i) => (prev[i] || []).concat(next[i])), []);\n```\n\n**TypeScript version**\n\n```ts transpose.ts\nconst transpose = <T,>(matrix: T[][]): T[][] => matrix[0].map((col, i) => matrix.map((row) => row[i]));\n\n// Or\nconst transpose = <T,>(matrix: T[][]): T[][] => matrix[0].map((col, c) => matrix.map((row, r) => matrix[r][c]));\n\n// Or\nconst transpose = <T,>(matrix: T[][]): T[][] => (\n    matrix.reduce((prev, next) => next.map((item, i) => (prev[i] || []).concat(next[i])), [] as T[][])\n);\n```\n\n**Examples**\n\n```js examples.js\ntranspose([\n    // [\n    [1, 2, 3], //      [1, 4, 7],\n    [4, 5, 6], //      [2, 5, 8],\n    [7, 8, 9], //      [3, 6, 9],\n]); //  ]\n```\n"
  },
  {
    "path": "contents/swap-two-array-items.mdx",
    "content": "---\ncategory: Array\ncreated: '2021-03-13'\ntitle: Swap two array items\nupdated: '2021-10-22'\n---\n\n**JavaScript version**\n\n```js swapItems.js\n// `i` must be less than `j`\nconst swapItems = (a, i, j) =>\n    (a[i] && a[j] && [...a.slice(0, i), a[j], ...a.slice(i + 1, j), a[i], ...a.slice(j + 1)]) || a;\n```\n\n**TypeScript version**\n\n```ts swapItems.ts\nconst swapItems = <T,_>(a: T[], i: number, j: number): T[] => (a[i] && a[j] && [...a.slice(0, i), a[j], ...a.slice(i + 1, j), a[i], ...a.slice(j + 1)]) || a;\n```\n\n**Example**\n\n```js example.js\nswapItems([1, 2, 3, 4, 5], 1, 4); // [1, 5, 3, 4, 2]\n```\n"
  },
  {
    "path": "contents/swap-two-variables.mdx",
    "content": "---\ncategory: Misc\ncreated: '2020-04-19'\ntitle: Swap two variables\nupdated: '2020-09-05'\n---\n\n**JavaScript version**\n\n```js\n[a, b] = [b, a];\n\n// Or\na = [b, (b = a)][0];\n\n// Or\na = ((x) => x)(b, (b = a));\n\n// Or\n// (only works with numbers)\na = b + ((b = a), 0);\n\na = b * ((b = a), 1);\n```\n"
  },
  {
    "path": "contents/toggle-an-element.mdx",
    "content": "---\ncategory: DOM\ncontributors:\n    - islamozbek\ncreated: '2020-04-19'\ntitle: Toggle an element\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js toggle.js\nconst toggle = (ele) => (ele.style.display = ele.style.display === 'none' ? 'block' : 'none');\n\n// Or\nconst toggle = (ele) => (ele.hidden = !ele.hidden);\n```\n\n**TypeScript version**\n\n```ts toggle.ts\nconst toggle = (ele: HTMLElement): string => (ele.style.display = ele.style.display === 'none' ? 'block' : 'none');\n\n// Or\nconst toggle = (ele: HTMLElement): boolean => (ele.hidden = !ele.hidden);\n```\n"
  },
  {
    "path": "contents/trim-slashes-at-the-beginning-and-the-end-of-a-string.mdx",
    "content": "---\ncategory: String\ncreated: '2020-06-01'\ntitle: Trim slashes at the beginning and the end of a string\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js trimSlashes.js\nconst trimSlashes = (str) => str.replace(/^\\/+|\\/+$/g, '');\n\n// Or\nconst trimSlashes = (str) => str.split('/').filter(Boolean).join('/');\n```\n\n**TypeScript version**\n\n```ts trimSlashes.ts\nconst trimSlashes = (str: string): string => str.replace(/^\\/+|\\/+$/g, '');\n\n// Or\nconst trimSlashes = (str: string): string => str.split('/').filter(Boolean).join('/');\n```\n\n**Examples**\n\n```js examples.js\ntrimSlashes('//hello/world///'); // hello/world\n```\n"
  },
  {
    "path": "contents/trim-some-character.mdx",
    "content": "---\ncategory: String\ncontributors:\n    - mahdiyar\ncreated: '2020-06-04'\ntitle: Trim some character\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js trim.js\nconst trim = (str, char) => str.split(char).filter(Boolean).join();\n```\n\n**TypeScript version**\n\n```ts trim.ts\nconst trim = (str: string, char: string): string => str.split(char).filter(Boolean).join();\n```\n\n**Examples**\n\n```js examples.js\ntrim('/hello world//', '/'); // hello world\ntrim('\"hello world\"', '\"'); // hello world\ntrim('   hello world ', ' '); // hello world\n```\n"
  },
  {
    "path": "contents/trim-the-file-extension-from-a-file-name.mdx",
    "content": "---\ncategory: String\ncreated: '2020-05-30'\ntitle: Trim the file extension from a file name\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js trimExt.js\nconst trimExt = (fileName) => (fileName.indexOf('.') === -1 ? fileName : fileName.split('.').slice(0, -1).join('.'));\n```\n\n**TypeScript version**\n\n```ts trimExt.ts\nconst trimExt = (fileName: string): string =>\n    fileName.indexOf('.') === -1 ? fileName : fileName.split('.').slice(0, -1).join('.');\n```\n\n**Examples**\n\n```js examples.js\ntrimExt('document'); // document\ntrimExt('document.pdf'); // document\ntrimExt('document.2020.pdf'); // document.2020\n```\n"
  },
  {
    "path": "contents/truncate-a-number-at-decimal.mdx",
    "content": "---\ncategory: Number\ncontributors:\n    - onelifemedia\ncreated: '2020-08-05'\ntitle: Truncate a number at decimal\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js truncate.js\nconst truncate = (n) => ~~n;\n```\n\n**TypeScript version**\n\n```ts truncate.ts\nconst truncate = (n: number): number => ~~n;\n```\n\n**Examples**\n\n```js examples.js\ntruncate(25.198726354); // 25\ntruncate(-25.198726354); // -25\n```\n"
  },
  {
    "path": "contents/truncate-a-number-to-a-given-number-of-decimal-places-without-rounding.mdx",
    "content": "---\ncategory: Number\ncontributors:\n    - onelifemedia\ncreated: '2020-05-28'\ntitle: Truncate a number to a given number of decimal places without rounding\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js toFixed.js\nconst toFixed = (n, fixed) => `${n}`.match(new RegExp(`^-?\\\\d+(?:\\.\\\\d{0,${fixed}})?`))[0];\n\n// Or\nconst toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);\n```\n\n**TypeScript version**\n\n```ts toFixed.ts\nconst toFixed = (n: number, fixed: number): number => +(`${n}`.match(new RegExp(`^-?\\\\d+(?:\\.\\\\d{0,${fixed}})?`)) as string[])[0];\n\n// Or\nconst toFixed = (n: number, fixed: number): number => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);\n```\n\n**Examples**\n\n```js examples.js\ntoFixed(25.198726354, 1); // 25.1\ntoFixed(25.198726354, 2); // 25.19\ntoFixed(25.198726354, 3); // 25.198\ntoFixed(25.198726354, 4); // 25.1987\ntoFixed(25.198726354, 5); // 25.19872\ntoFixed(25.198726354, 6); // 25.198726\n```\n"
  },
  {
    "path": "contents/truncate-a-string-at-full-words.mdx",
    "content": "---\ncategory: String\ncreated: '2020-05-29'\ntitle: Truncate a string at full words\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js truncate.js\nconst truncate = (str, max, suffix) =>\n    str.length < max ? str : `${str.substr(0, str.substr(0, max - suffix.length).lastIndexOf(' '))}${suffix}`;\n```\n\n**TypeScript version**\n\n```ts truncate.ts\nconst truncate = (str: string, max: number, suffix: string = '...'): string =>\n    str.length < max ? str : `${str.substr(0, str.substr(0, max - suffix.length).lastIndexOf(' '))}${suffix}`;\n```\n\n**Examples**\n\n```js examples.js\ntruncate('This is a long message', 20, '...'); // 'This is a long...'\n```\n"
  },
  {
    "path": "contents/uncurry-a-function.mdx",
    "content": "---\ncategory: Function\ncreated: '2020-05-15'\ntitle: Uncurry a function\n---\n\n**JavaScript version**\n\n```js\n// `fn` is a curried function\n// `n` is the depth of parameters\nconst uncurry =\n    (fn, n = 1) =>\n    (...args) =>\n        (\n            (acc) => (args) =>\n                args.reduce((x, y) => x(y), acc)\n        )(fn)(args.slice(0, n));\n```\n\n**Examples**\n\n```js examples.js\nconst sum = (a) => (b) => (c) => a + b + c;\nuncurry(sum, 1)(1)(2)(3); // 6\nuncurry(sum, 2)(1, 2)(3); // 6\nuncurry(sum, 3)(1, 2, 3); // 6\n```\n"
  },
  {
    "path": "contents/unescape-html-special-characters.mdx",
    "content": "---\ncategory: String\ncreated: '2020-05-29'\ntitle: Unescape HTML special characters\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js unescape.js\nconst unescape = (str) =>\n    str\n        .replace(/&amp;/g, '&')\n        .replace(/&lt;/g, '<')\n        .replace(/&gt;/g, '>')\n        .replace(/&#0*39;/g, \"'\")\n        .replace(/&quot;/g, '\"');\n```\n\n**TypeScript version**\n\n```ts unescape.ts\nconst unescape = (str: string): string =>\n    str\n        .replace(/&amp;/g, '&')\n        .replace(/&lt;/g, '<')\n        .replace(/&gt;/g, '>')\n        .replace(/&#0*39;/g, \"'\")\n        .replace(/&quot;/g, '\"');\n```\n"
  },
  {
    "path": "contents/unzip-an-array-of-arrays.mdx",
    "content": "---\ncategory: Array\ncreated: '2020-05-15'\ntitle: Unzip an array of arrays\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js unzip.js\nconst unzip = (arr) =>\n    arr.reduce(\n        (acc, c) => (c.forEach((v, i) => acc[i].push(v)), acc),\n        Array.from({ length: Math.max(...arr.map((a) => a.length)) }, (_) => [])\n    );\n```\n\n**Example**\n\n```js example.js\nunzip([\n    ['a', 1],\n    ['b', 2],\n    ['c', 3],\n    ['d', 4],\n    ['e', 5],\n]); // [['a', 'b', 'c', 'd', 'e'], [1, 2, 3, 4, 5]]\n\n/*\n    a     1\n     b   2\n      c 3\n      d 4\n      e 5\n*/\n```\n"
  },
  {
    "path": "contents/uppercase-the-first-character-of-each-word-in-a-string.mdx",
    "content": "---\ncategory: String\ncreated: '2020-05-03'\ntitle: Uppercase the first character of each word in a string\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js uppercaseWords.js\nconst uppercaseWords = (str) =>\n    str\n        .split(' ')\n        .map((w) => `${w.charAt(0).toUpperCase()}${w.slice(1)}`)\n        .join(' ');\n\n// Or\nconst uppercaseWords = (str) => str.replace(/^(.)|\\s+(.)/g, (c) => c.toUpperCase());\n```\n\n**TypeScript version**\n\n```ts uppercaseWords.ts\nconst uppercaseWords = (str: string): string =>\n    str\n        .split(' ')\n        .map((w) => `${w.charAt(0).toUpperCase()}${w.slice(1)}`)\n        .join(' ');\n\n// Or\nconst uppercaseWords = (str: string): string => str.replace(/^(.)|\\s+(.)/g, (c) => c.toUpperCase());\n```\n\n**Examples**\n\n```js examples.js\nuppercaseWords('hello world'); // 'Hello World'\n```\n"
  },
  {
    "path": "contents/validate-a-gregorian-date.mdx",
    "content": "---\ncategory: Validator\ncreated: '2020-05-03'\ntitle: Validate a Gregorian date\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js\n// `m`: the month (zero-based index)\n// `d`: the day\n// `y`: the year\nconst isValidDate = (m, d, y) => 0 <= m && m <= 11 && 0 < y && y < 32768 && 0 < d && d <= new Date(y, m, 0).getDate();\n```\n\n**TypeScript version**\n\n```ts isValidDate.ts\nconst isValidDate = (m: number, d: number, y: number): boolean =>\n    0 <= m && m <= 11 && 0 < y && y < 32768 && 0 < d && d <= new Date(y, m, 0).getDate();\n```\n"
  },
  {
    "path": "contents/wait-for-an-amount-of-time.mdx",
    "content": "---\ncategory: Misc\ncontributors:\n    - furkankose\ncreated: '2020-05-06'\nopenGraphCover: /og/1-loc/wait-amount-time.png\ntitle: Wait for an amount of time\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js wait.js\nconst wait = async (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));\n```\n\n**TypeScript version**\n\n```ts wait.ts\nconst wait = async (milliseconds: number) => new Promise((resolve) => setTimeout(resolve, milliseconds));\n```\n\n## See also\n\n-   [Wait for the next event loop](https://phuoc.ng/collection/1-loc/wait-for-the-next-event-loop/)\n"
  },
  {
    "path": "contents/wait-for-the-next-event-loop.mdx",
    "content": "---\ncategory: Misc\ncreated: '2023-12-14'\nopenGraphCover: /og/1-loc/wait-next-event-loop.png\ntags: event loop, next tick, requestAnimationFrame, setTimeout(0)\ntitle: Wait for the next event loop\n---\n\nIn JavaScript, there may be times when you need to wait for the next event loop before executing a block of code. For example, you might want to ensure that certain updates to the DOM have been completed before running a function.\n\nTo do this, you can create a `Promise` that resolves after the next event loop. The following `waitForNextLoop()` function uses `setTimeout` with a delay of `0` to queue a function call on the event loop. When this function is called, it resolves the `Promise`. This `Promise` can be used in other parts of your code to ensure that the next event loop has completed before proceeding.\n\n```js waitForNextLoop.js\nconst waitForNextLoop = async () => new Promise((resolve) => {\n    setTimeout(() => {\n        resolve();\n    }, 0);\n});\n```\n\nHere's an example of how you can use the `waitForNextLoop()` function:\n\n```js\nwaitForNextLoop().then(() => {\n    console.log('This code runs after the next event loop!');\n});\n```\n\nBy using `requestAnimationFrame` instead of `setTimeout`, we can provide some performance benefits. This is because `requestAnimationFrame` allows the browser to optimize when to run your code. It also ensures that your code runs at a consistent frame rate, which can help prevent jank and stuttering in animations.\n\nHere's the modified version:\n\n```ts nextTick.ts\nconst nextTick = (): Promise<void> => new Promise((resolve) => requestAnimationFrame(() => resolve()));\n```\n\nWhen you call `nextTick()`, it returns a new `Promise` that resolves when the next animation frame is ready to be rendered. This ensures that any updates to the UI or animations will be finished before the `Promise` resolves.\n\nHere's an example of how to use the `nextTick()` function:\n\n```js\nasync function doSomethingAsync() {\n    await nextTick();\n    // Code here will run after the next animation frame\n}\n\ndoSomethingAsync();\n```\n\n## See also\n\n-   [setTimeout(0) vs requestAnimationFrame](https://phuoc.ng/collection/this-vs-that/set-timeout-zero-vs-request-animation-frame/)\n-   [Wait for an amount of time](https://phuoc.ng/collection/1-loc/wait-for-an-amount-of-time/)\n"
  },
  {
    "path": "contents/wrap-a-number-between-two-values.mdx",
    "content": "---\ncategory: Number\ncontributors:\n    - iamandrewluca\ncreated: '2021-12-13'\ntitle: Wrap a number between two values\n---\n\n**JavaScript version**\n\n```js wrap.js\nconst wrap = (num, min, max) => ((((num - min) % (max - min)) + (max - min)) % (max - min)) + min;\n```\n\n**TypeScript version**\n\n```ts\nconst wrap = (num: number, min: number, max: number): number =>\n    ((((num - min) % (max - min)) + (max - min)) % (max - min)) + min;\n```\n\n**Examples**\n\n```js examples.js\nwrap(11, 10, 25); // 11\nwrap(10, 10, 25); // 10\nwrap(9, 10, 25); // 25\nwrap(24, 10, 25); // 24\nwrap(25, 10, 25); // 25\nwrap(26, 10, 25); // 10\n```\n\n## See also\n\n-   [Clamp a number between two values](https://phuoc.ng/collection/1-loc/clamp-a-number-between-two-values/)\n"
  },
  {
    "path": "contents/zip-multiple-arrays.mdx",
    "content": "---\ncategory: Array\ncreated: '2020-05-13'\ntitle: Zip multiple arrays\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js zip.js\nconst zip = (...arr) => Array.from({ length: Math.max(...arr.map((a) => a.length)) }, (_, i) => arr.map((a) => a[i]));\n```\n\n**Example**\n\n```js example.js\nzip(['a', 'b', 'c', 'd', 'e'], [1, 2, 3, 4, 5]); // [['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5]]\n\n/*\nDoes it look like a zipper?\n        a 1\n        b 2\n       c   3\n      d     4\n     e       5\n*/\n```\n"
  }
]