Showing preview only (252K chars total). Download the full file or copy to clipboard to get everything.
Repository: phuocng/1loc
Branch: master
Commit: 14b481cf60df
Files: 316
Total size: 184.1 KB
Directory structure:
gitextract_mcm7t2nt/
├── .gitignore
├── LICENSE
├── README.md
└── contents/
├── add-am-pm-suffix-to-an-hour.mdx
├── add-an-ordinal-suffix-to-a-number.mdx
├── box-handler.mdx
├── calculate-fibonacci-numbers.mdx
├── calculate-the-angle-of-a-line-defined-by-two-points.mdx
├── calculate-the-average-of-arguments.mdx
├── calculate-the-distance-between-two-points.mdx
├── calculate-the-distance-to-the-bottom-of-a-page.mdx
├── calculate-the-division-of-arguments.mdx
├── calculate-the-factorial-of-a-number.mdx
├── calculate-the-linear-interpolation-between-two-numbers.mdx
├── calculate-the-midpoint-between-two-points.mdx
├── calculate-the-midpoint-of-a-given-range.mdx
├── calculate-the-mod-of-collection-index.mdx
├── calculate-the-number-of-difference-days-between-two-dates.mdx
├── calculate-the-number-of-months-between-two-dates.mdx
├── calculate-the-remainder-of-division-of-arguments.mdx
├── calculate-the-sum-of-arguments.mdx
├── capitalize-a-string.mdx
├── cast-a-value-as-an-array.mdx
├── check-if-a-character-is-a-digit.mdx
├── check-if-a-date-is-a-weekday.mdx
├── check-if-a-date-is-a-weekend.mdx
├── check-if-a-date-is-between-two-dates.mdx
├── check-if-a-date-is-today.mdx
├── check-if-a-date-occurs-in-the-current-year.mdx
├── check-if-a-flat-array-has-duplicate-values.mdx
├── check-if-a-given-dom-rect-is-contained-within-another-dom-rect.mdx
├── check-if-a-given-integer-is-a-prime-number.mdx
├── check-if-a-number-is-a-power-of-2.mdx
├── check-if-a-number-is-even.mdx
├── check-if-a-number-is-in-a-given-range.mdx
├── check-if-a-number-is-negative.mdx
├── check-if-a-number-is-odd.mdx
├── check-if-a-number-is-positive.mdx
├── check-if-a-path-is-relative.mdx
├── check-if-a-point-is-inside-a-rectangle.mdx
├── check-if-a-rectangle-contains-other-one.mdx
├── check-if-a-rectangle-overlaps-other-one.mdx
├── check-if-a-string-consists-of-a-repeated-character-sequence.mdx
├── check-if-a-string-contains-lower-case-characters.mdx
├── check-if-a-string-contains-only-ascii-characters.mdx
├── check-if-a-string-contains-only-digits.mdx
├── check-if-a-string-contains-only-letters-and-numbers.mdx
├── check-if-a-string-contains-only-letters.mdx
├── check-if-a-string-contains-upper-case-characters.mdx
├── check-if-a-string-contains-whitespace.mdx
├── check-if-a-string-is-a-hexadecimal-color.mdx
├── check-if-a-string-is-a-hexadecimal-number.mdx
├── check-if-a-string-is-a-mongo-db-object-id.mdx
├── check-if-a-string-is-a-palindrome.mdx
├── check-if-a-string-is-an-octal-number.mdx
├── check-if-a-string-is-lower-case.mdx
├── check-if-a-string-is-upper-case.mdx
├── check-if-a-url-is-absolute.mdx
├── check-if-a-value-is-a-business-identifier-code.mdx
├── check-if-a-value-is-a-function.mdx
├── check-if-a-value-is-a-generator-function.mdx
├── check-if-a-value-is-a-number.mdx
├── check-if-a-value-is-a-plain-object.mdx
├── check-if-a-value-is-a-regular-expression.mdx
├── check-if-a-value-is-a-string.mdx
├── check-if-a-value-is-an-async-function.mdx
├── check-if-a-value-is-an-object.mdx
├── check-if-a-value-is-base32-encoded.mdx
├── check-if-a-value-is-base58-encoded.mdx
├── check-if-a-value-is-base64-encoded.mdx
├── check-if-a-value-is-nil.mdx
├── check-if-a-year-is-leap-year.mdx
├── check-if-all-array-elements-are-equal-to-a-given-value.mdx
├── check-if-all-items-in-an-array-are-equal.mdx
├── check-if-an-array-contains-a-value-matching-some-criterias.mdx
├── check-if-an-array-is-empty.mdx
├── check-if-an-array-is-not-empty.mdx
├── check-if-an-array-is-subset-of-other-array.mdx
├── check-if-an-element-has-css-overflow.mdx
├── check-if-an-element-has-overflow.mdx
├── check-if-an-element-is-a-descendant-of-another.mdx
├── check-if-an-element-is-focused.mdx
├── check-if-an-object-is-a-promise.mdx
├── check-if-an-object-is-an-array.mdx
├── check-if-an-object-is-empty.mdx
├── check-if-multiple-objects-are-equal.mdx
├── check-if-the-code-is-running-in-jest.mdx
├── check-if-the-code-is-running-in-node-js.mdx
├── check-if-the-code-is-running-in-the-browser.mdx
├── check-if-the-touch-events-are-supported.mdx
├── check-if-two-dom-rects-intersect.mdx
├── check-if-two-strings-are-anagram.mdx
├── check-if-user-scrolls-to-the-bottom-of-the-page.mdx
├── clamp-a-number-between-two-values.mdx
├── clear-all-cookies.mdx
├── clone-an-array.mdx
├── compare-two-arrays-regardless-of-order.mdx
├── compare-two-arrays.mdx
├── compare-two-dates.mdx
├── compare-two-dom-rects-for-size-and-position-match.mdx
├── compose-functions-from-left-to-right.mdx
├── compose-functions.mdx
├── compute-the-greatest-common-divisor-between-two-numbers.mdx
├── convert-3-digits-color-to-6-digits-color.mdx
├── convert-a-base64-encoded-string-to-an-uint8-array.mdx
├── convert-a-date-to-yyyy-mm-dd-format.mdx
├── convert-a-lab-color-to-an-lch-color.mdx
├── convert-a-letter-to-associate-emoji.mdx
├── convert-a-number-to-equivalent-characters.mdx
├── convert-a-string-to-camel-case.mdx
├── convert-a-string-to-number.mdx
├── convert-a-string-to-pascal-case.mdx
├── convert-a-string-to-url-slug.mdx
├── convert-a-windows-file-path-to-unix-path.mdx
├── convert-an-array-of-objects-to-a-single-object.mdx
├── convert-an-array-of-strings-to-numbers.mdx
├── convert-an-lch-color-to-a-lab-color.mdx
├── convert-an-uint8-array-to-a-base64-encoded-string.mdx
├── convert-camel-case-to-kebab-case-and-vice-versa.mdx
├── convert-celsius-to-fahrenheit.mdx
├── convert-cookie-to-object.mdx
├── convert-decimal-to-binary-recursively.mdx
├── convert-degrees-to-radians.mdx
├── convert-fahrenheit-to-celsius.mdx
├── convert-hex-to-rgb.mdx
├── convert-radians-to-degrees.mdx
├── convert-rgb-color-to-hex.mdx
├── convert-seconds-to-hh-mm-ss-format.mdx
├── convert-snake-case-to-camel-case.mdx
├── convert-the-name-of-an-excel-column-to-number.mdx
├── convert-url-parameters-to-object.mdx
├── count-by-the-properties-of-an-array-of-objects.mdx
├── count-the-number-of-words-in-a-string.mdx
├── count-the-occurrences-of-a-character-in-a-string.mdx
├── count-the-occurrences-of-a-value-in-an-array.mdx
├── count-the-occurrences-of-array-elements.mdx
├── create-a-function-that-accepts-a-single-argument.mdx
├── create-an-array-of-cumulative-sum.mdx
├── create-an-array-of-numbers-in-the-given-range.mdx
├── create-an-empty-function.mdx
├── create-an-empty-map-that-does-not-have-properties.mdx
├── create-an-object-from-the-pairs-of-key-and-value.mdx
├── create-cartesian-product.mdx
├── curry-a-function.mdx
├── decapitalize-a-string.mdx
├── decode-a-jwt-token.mdx
├── decode-html-entities.mdx
├── delay-the-evaluation-of-a-function.mdx
├── detect-dark-mode.mdx
├── detect-internet-explorer-browser.mdx
├── detect-macos-browser.mdx
├── determine-one-year-from-now.mdx
├── easing-functions.mdx
├── empty-an-array.mdx
├── emulate-a-dice-throw.mdx
├── encode-a-url.mdx
├── escape-html-special-characters.mdx
├── execute-a-function-once.mdx
├── extract-values-of-a-property-from-an-array-of-objects.mdx
├── extract-year-month-day-hour-minute-second-and-millisecond-from-a-date.mdx
├── find-the-closest-number-from-an-array.mdx
├── find-the-index-of-the-last-matching-item-of-an-array.mdx
├── find-the-index-of-the-maximum-item-of-an-array.mdx
├── find-the-index-of-the-minimum-item-of-an-array.mdx
├── find-the-length-of-the-longest-string-in-an-array.mdx
├── find-the-maximum-item-of-an-array-by-given-key.mdx
├── find-the-maximum-item-of-an-array.mdx
├── find-the-minimum-item-of-an-array-by-given-key.mdx
├── find-the-minimum-item-of-an-array.mdx
├── flatten-an-array.mdx
├── flip-the-arguments-of-a-function.mdx
├── format-a-date-for-the-given-locale.mdx
├── format-a-string.mdx
├── generate-a-hash-of-a-string.mdx
├── generate-a-random-boolean.mdx
├── generate-a-random-floating-point-number-in-given-range.mdx
├── generate-a-random-hex-color.mdx
├── generate-a-random-integer-in-given-range.mdx
├── generate-a-random-ip-address.mdx
├── generate-a-random-sign.mdx
├── generate-a-random-string-from-given-characters.mdx
├── generate-a-random-string-using-node-crypto-module.mdx
├── generate-a-random-string-with-given-length.mdx
├── generate-a-random-uuid.mdx
├── generate-a-weighted-random-number-in-given-range.mdx
├── generate-an-array-of-alphabet-characters.mdx
├── generate-an-array-of-random-integers-in-a-given-range.mdx
├── generate-an-unique-and-increment-id.mdx
├── get-a-random-item-and-remove-it-from-an-array.mdx
├── get-a-random-item-from-an-array.mdx
├── get-all-arrays-of-consecutive-elements.mdx
├── get-all-nth-items-of-an-array.mdx
├── get-all-siblings-of-an-element.mdx
├── get-all-subsets-of-an-array.mdx
├── get-hours-and-minutes-from-decimal-time.mdx
├── get-indices-of-a-value-in-an-array.mdx
├── get-random-items-of-an-array.mdx
├── get-the-arrays-of-digits-from-a-number.mdx
├── get-the-average-of-an-array.mdx
├── get-the-base-url-without-any-parameters.mdx
├── get-the-center-point-of-a-dom-rect.mdx
├── get-the-current-quarter-of-a-date.mdx
├── get-the-current-timestamp-in-seconds.mdx
├── get-the-day-of-the-year-from-a-date.mdx
├── get-the-file-extension-from-a-file-name.mdx
├── get-the-file-name-from-a-url.mdx
├── get-the-first-date-in-the-month-of-a-date.mdx
├── get-the-first-defined-and-non-null-argument.mdx
├── get-the-intersection-of-arrays.mdx
├── get-the-intersection-range-between-two-ranges.mdx
├── get-the-last-date-in-the-month-of-a-date.mdx
├── get-the-length-of-a-string-in-bytes.mdx
├── get-the-month-name-of-a-date.mdx
├── get-the-number-of-a-character-in-a-string.mdx
├── get-the-number-of-days-in-given-month.mdx
├── get-the-position-of-an-element-relative-to-the-document.mdx
├── get-the-rank-of-an-array-of-numbers.mdx
├── get-the-selected-text.mdx
├── get-the-sum-of-an-array-of-numbers.mdx
├── get-the-timezone-string.mdx
├── get-the-tomorrow-date.mdx
├── get-the-total-number-of-days-in-a-year.mdx
├── get-the-unique-values-of-an-array.mdx
├── get-the-value-at-given-path-of-an-object.mdx
├── get-the-value-of-a-cookie.mdx
├── get-the-value-of-a-param-from-a-url.mdx
├── get-the-weekday-of-a-date.mdx
├── get-the-yesterday-date.mdx
├── get-type-of-a-variable-in-string.mdx
├── get-union-of-arrays.mdx
├── get-unique-arr-obj.mdx
├── go-back-to-the-previous-page.mdx
├── group-an-array-of-objects-by-a-key.mdx
├── hide-an-element.mdx
├── identity-function.mdx
├── immutably-rename-object-keys.mdx
├── initialize-the-current-date-but-set-time-to-midnight.mdx
├── insert-an-element-after-other-one.mdx
├── insert-an-element-before-other-one.mdx
├── insert-given-html-after-an-element.mdx
├── insert-given-html-before-an-element.mdx
├── intersperse-element-between-elements.mdx
├── invert-keys-and-values-of-an-object.mdx
├── linear-scale-number-in-ranges.mdx
├── linear-scale-of-a-number-between-two-ranges.mdx
├── logical-xor-operator.mdx
├── make-the-first-character-of-a-string-lowercase.mdx
├── memoize-a-function.mdx
├── merge-two-arrays.mdx
├── multiply-arguments.mdx
├── normalize-file-path-slashes.mdx
├── normalize-the-ratio-of-a-number-in-a-range.mdx
├── omit-a-subset-of-properties-from-an-object.mdx
├── partially-apply-a-function.mdx
├── partition-an-array-based-on-a-condition.mdx
├── pick-a-random-property-of-an-object.mdx
├── pick-a-subset-of-properties-of-an-object.mdx
├── pick-random-lines-from-a-text-document.mdx
├── prefix-an-integer-with-zeros.mdx
├── prepend-a-line-number-to-each-line-of-a-text-document.mdx
├── redirect-the-page-to-https-if-it-is-in-http.mdx
├── redirect-to-another-page.mdx
├── reload-the-current-page.mdx
├── remove-all-null-and-undefined-properties-from-an-object.mdx
├── remove-duplicate-lines-of-a-text-document.mdx
├── remove-duplicate-values-in-an-array.mdx
├── remove-empty-lines-of-a-text-document.mdx
├── remove-falsy-values-from-array.mdx
├── remove-spaces-from-a-string.mdx
├── repeat-a-string.mdx
├── repeat-an-array.mdx
├── replace-all-line-breaks-with-br-elements.mdx
├── replace-all-tab-characters-with-spaces.mdx
├── replace-an-element.mdx
├── replace-multiple-spaces-with-a-single-space.mdx
├── replace-the-first-given-number-of-characters-of-a-string-with-another-character.mdx
├── reverse-a-string.mdx
├── reverse-the-order-of-lines-of-a-text.mdx
├── round-a-number-to-a-given-number-of-digits.mdx
├── round-a-number-to-the-nearest-multiple-of-a-given-value.mdx
├── run-promises-in-sequence.mdx
├── scroll-to-top-of-the-page.mdx
├── serialize-form-data.mdx
├── shallow-copy-an-object.mdx
├── show-an-element.mdx
├── shuffle-an-array.mdx
├── sort-an-array-of-dates.mdx
├── sort-an-array-of-items-by-given-key.mdx
├── sort-an-array-of-numbers.mdx
├── sort-an-object-by-its-properties.mdx
├── sort-lines-of-a-text-document-in-the-alphabetical-order.mdx
├── sort-the-characters-of-a-string-in-the-alphabetical-order.mdx
├── split-an-array-into-chunks.mdx
├── strip-ansi-codes-from-a-string.mdx
├── strip-html-from-a-given-text.mdx
├── subtract-arguments.mdx
├── swap-case-of-characters-in-a-string.mdx
├── swap-the-rows-and-columns-of-a-matrix.mdx
├── swap-two-array-items.mdx
├── swap-two-variables.mdx
├── toggle-an-element.mdx
├── trim-slashes-at-the-beginning-and-the-end-of-a-string.mdx
├── trim-some-character.mdx
├── trim-the-file-extension-from-a-file-name.mdx
├── truncate-a-number-at-decimal.mdx
├── truncate-a-number-to-a-given-number-of-decimal-places-without-rounding.mdx
├── truncate-a-string-at-full-words.mdx
├── uncurry-a-function.mdx
├── unescape-html-special-characters.mdx
├── unzip-an-array-of-arrays.mdx
├── uppercase-the-first-character-of-each-word-in-a-string.mdx
├── validate-a-gregorian-date.mdx
├── wait-for-an-amount-of-time.mdx
├── wait-for-the-next-event-loop.mdx
├── wrap-a-number-between-two-values.mdx
└── zip-multiple-arrays.mdx
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
.DS_Store
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2020 phuoc-ng
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
# Favorite single line of code
What's your favorite JavaScript single LOC (line of code)? Let me know!
## Contributing
Pull 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.
## About
This project is developed by _Nguyen Huu Phuoc_. I love building products and sharing knowledge.
Be my friend on
- [Twitter](https://twitter.com/_phuocng)
- [Github](https://github.com/phuocng)
================================================
FILE: contents/add-am-pm-suffix-to-an-hour.mdx
================================================
---
category: Date Time
created: '2021-02-20'
title: Add AM PM suffix to an hour
updated: '2021-10-13'
---
**JavaScript version**
```js suffixAmPm.js
// `h` is an hour number between 0 and 23
const suffixAmPm = (h) => `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? 'am' : 'pm'}`;
```
**TypeScript version**
```ts suffixAmPm.ts
const suffixAmPm = (h: number): string => `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? 'am' : 'pm'}`;
```
**Examples**
```js examples.js
suffixAmPm(0); // '12am'
suffixAmPm(5); // '5am'
suffixAmPm(12); // '12pm'
suffixAmPm(15); // '3pm'
suffixAmPm(23); // '11pm'
```
================================================
FILE: contents/add-an-ordinal-suffix-to-a-number.mdx
================================================
---
category: Number
created: '2020-05-16'
title: Add an ordinal suffix to a number
updated: '2021-10-13'
---
**JavaScript version**
```js addOrdinal.js
// `n` is a position number
const addOrdinal = (n) => `${n}${['st', 'nd', 'rd'][((((n + 90) % 100) - 10) % 10) - 1] || 'th'}`;
```
**TypeScript version**
```ts addOrdinal.ts
const addOrdinal = (n: number): string => `${n}${['st', 'nd', 'rd'][((((n + 90) % 100) - 10) % 10) - 1] || 'th'}`;
```
**Examples**
```js examples.js
addOrdinal(1); // '1st'
addOrdinal(2); // '2nd'
addOrdinal(3); // '3rd'
addOrdinal(11); // '11th'
addOrdinal(12); // '13th'
addOrdinal(13); // '13th'
```
================================================
FILE: contents/box-handler.mdx
================================================
---
category: Function
contributors:
- Valeriy Arbachakov
created: '2020-07-15'
title: Box handler
updated: '2020-08-18'
---
**JavaScript version**
```js boxHandler.js
const boxHandler = (x) => ({ next: (f) => boxHandler(f(x)), done: (f) => f(x) });
```
**Examples**
```js examples.js
// First example
const getPercentNumber = (str) =>
boxHandler(str)
.next((str) => str.replace(/\%/, ''))
.next((str) => parseFloat(str))
.done((res) => res * 0.01);
getPercentNumber('50%'); // 0.5
// Second example
const getMoney = (price) => Number.parseFloat(price.replace(/\$/, ''));
const getPercent = (percent) => Number.parseFloat(percent.replace(/\%/)) * 0.01;
const getDiscountPrice = (price, discount) =>
boxHandler(getMoney(price))
.done((cents) => boxHandler(getPercent(discount)).next((save) => cents - cents * save))
.done((res) => res);
getDiscountPrice('$6.00', '20%'); // 4.8
```
================================================
FILE: contents/calculate-fibonacci-numbers.mdx
================================================
---
category: Number
created: '2020-05-16'
title: Calculate Fibonacci numbers
updated: '2021-10-13'
---
**JavaScript version**
```js fibo.js
const fibo = (n, memo = {}) => memo[n] || (n <= 2 ? 1 : (memo[n] = fibo(n - 1, memo) + fibo(n - 2, memo)));
```
**TypeScript version**
```ts fibo.ts
const fibo = (n: number, memo: Record<string, number> = {}): number =>
memo[n] || (n <= 2 ? 1 : (memo[n] = fibo(n - 1, memo) + fibo(n - 2, memo)));
```
**Examples**
```js examples.js
fibo(1); // 1
fibo(2); // 1
fibo(3); // 2
fibo(4); // 3
fibo(5); // 5
fibo(6); // 8
```
================================================
FILE: contents/calculate-the-angle-of-a-line-defined-by-two-points.mdx
================================================
---
category: Math
created: '2021-04-08'
title: Calculate the angle of a line defined by two points
updated: '2021-10-13'
---
**JavaScript version**
```js radiansAngle.js
// In radians
const radiansAngle = (p1, p2) => Math.atan2(p2.y - p1.y, p2.x - p1.x);
// In degrees
const degreesAngle = (p1, p2) => (Math.atan2(p2.y - p1.y, p2.x - p1.x) * 180) / Math.PI;
```
**TypeScript version**
```ts radiansAngle.ts
interface Point {
x: number;
y: number;
}
const radiansAngle = (p1: Point, p2: Point): number => Math.atan2(p2.y - p1.y, p2.x - p1.x);
const degreesAngle = (p1: Point, p2: Point): number => (Math.atan2(p2.y - p1.y, p2.x - p1.x) * 180) / Math.PI;
```
================================================
FILE: contents/calculate-the-average-of-arguments.mdx
================================================
---
category: Number
created: '2020-05-05'
title: Calculate the average of arguments
updated: '2021-10-13'
---
**JavaScript version**
```js average.js
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
```
**TypeScript version**
```ts average.ts
const average = (...args: number[]): number => args.reduce((a, b) => a + b) / args.length;
```
**Examples**
```js examples.js
average(1, 2, 3, 4); // 2.5
```
================================================
FILE: contents/calculate-the-distance-between-two-points.mdx
================================================
---
category: Math
created: '2021-04-05'
title: Calculate the distance between two points
updated: '2021-10-13'
---
**JavaScript version**
```js distance.js
const distance = (p1, p2) => Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
```
**TypeScript version**
```js distance.ts
interface Point {
x: number;
y: number;
}
const distance = (p1: Point, p2: Point): number => Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
```
================================================
FILE: contents/calculate-the-distance-to-the-bottom-of-a-page.mdx
================================================
---
category: DOM
created: '2023-08-23'
description: one-liner function to calculate how far you are from the bottom of the page
openGraphCover: /og/1-loc/distance-to-bottom.png
title: Calculate the distance to the bottom of a page
---
The following snippet calculates how far you are from the bottom of the page.
Here'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`).
The result is the distance from your current position to the bottom of the page.
**JavaScript version**
```js distanceToBottom.js
const distanceToBottom = document.body.scrollHeight - window.innerHeight - window.scrollY;
```
**TypeScript version**
```js distanceToBottom.ts
const distanceToBottom: number = document.body.scrollHeight - window.innerHeight - window.scrollY;
```
================================================
FILE: contents/calculate-the-division-of-arguments.mdx
================================================
---
category: Number
created: '2020-05-05'
title: Calculate the division of arguments
updated: '2021-10-13'
---
**JavaScript version**
```js division.js
const division = (...args) => args.reduce((a, b) => a / b);
```
**TypeScript version**
```ts division.ts
const division = (...args: number): number => args.reduce((a, b) => a / b);
```
**Examples**
```js examples.js
division(1, 2, 3, 4); // 0.04166666666666666
```
================================================
FILE: contents/calculate-the-factorial-of-a-number.mdx
================================================
---
category: Number
created: '2020-05-19'
title: Calculate the factorial of a number
updated: '2021-10-13'
---
**JavaScript version**
```js factorial.js
const factorial = (n) => (n <= 1 ? 1 : n * factorial(n - 1));
```
**TypeScript version**
```ts factorial.ts
const factorial = (n: number): number => (n <= 1 ? 1 : n * factorial(n - 1));
```
**Examples**
```js examples.js
factorial(2); // 2
factorial(3); // 6
factorial(4); // 24
factorial(5); // 120
factorial(6); // 720
```
================================================
FILE: contents/calculate-the-linear-interpolation-between-two-numbers.mdx
================================================
---
category: Math
created: '2021-05-24'
title: Calculate the linear interpolation between two numbers
updated: '2021-10-13'
---
**JavaScript version**
```js lerp.js
const lerp = (a, b, amount) => (1 - amount) * a + amount * b;
```
**TypeScript version**
```ts lerp.ts
const lerp = (a: number, b: number, amount: number): number => (1 - amount) * a + amount * b;
```
## See also
- [Linear scale of a number between two ranges](https://phuoc.ng/collection/1-loc/linear-scale-of-a-number-between-two-ranges/)
- [Normalize the ratio of a number in a range](https://phuoc.ng/collection/1-loc/normalize-the-ratio-of-a-number-in-a-range/)
================================================
FILE: contents/calculate-the-midpoint-between-two-points.mdx
================================================
---
category: Math
created: '2021-04-10'
openGraphCover: /og/1-loc/calculate-midpoint-two-points.png
title: Calculate the midpoint between two points
updated: '2021-10-13'
---
**JavaScript version**
```js midpoint.js
const midpoint = (p1, p2) => [(p1.x + p2.x) / 2, (p1.y + p2.y) / 2];
```
**TypeScript version**
```ts midpoint.ts
interface Point {
x: number;
y: number;
}
const midpoint = (p1: Point, p2: Point): number[] => [(p1.x + p2.x) / 2, (p1.y + p2.y) / 2];
```
## See also
- [Calculate the midpoint of a given range](https://phuoc.ng/collection/1-loc/calculate-the-midpoint-of-a-given-range/)
================================================
FILE: contents/calculate-the-midpoint-of-a-given-range.mdx
================================================
---
category: Math
created: '2023-12-08'
openGraphCover: /og/1-loc/calculate-midpoint-given-range.png
title: Calculate the midpoint of a given range
---
**JavaScript version**
```js midpoint.js
const midpoint = ([from, to]) => (from + to) / 2;
```
**TypeScript version**
```ts midpoint.ts
const midpoint = ([from, to]: [number, number]): number => (from + to) / 2;
```
## See also
- [Calculate the midpoint between two points](https://phuoc.ng/collection/1-loc/calculate-the-midpoint-between-two-points/)
================================================
FILE: contents/calculate-the-mod-of-collection-index.mdx
================================================
---
category: Number
contributors:
- marcobiedermann
created: '2020-05-08'
title: Calculate the mod of collection index
updated: '2021-10-13'
---
**JavaScript version**
```js mod.js
const mod = (a, b) => ((a % b) + b) % b;
```
**TypeScript version**
```ts mod.ts
const mod = (a: number, b: number): number => ((a % b) + b) % b;
```
**Examples**
```js examples.js
mod(-1, 5); // 4
mod(3, 5); // 3
mod(6, 5); // 1
```
================================================
FILE: contents/calculate-the-number-of-difference-days-between-two-dates.mdx
================================================
---
category: Date Time
created: '2020-04-19'
title: Calculate the number of difference days between two dates
updated: '2021-10-13'
---
**JavaScript version**
```js diffDays.js
const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));
```
**TypeScript version**
```ts diffDays.ts
const diffDays = (date: Date, otherDate: Date): number =>
Math.ceil(Math.abs(date.valueOf() - otherDate.valueOf()) / (1000 * 60 * 60 * 24));
```
**Examples**
```js examples.js
diffDays(new Date('2014-12-19'), new Date('2020-01-01')); // 1839
```
================================================
FILE: contents/calculate-the-number-of-months-between-two-dates.mdx
================================================
---
category: Date Time
contributors:
- kwaimind
created: '2020-07-27'
title: Calculate the number of months between two dates
updated: '2021-10-13'
---
**JavaScript version**
```js monthDiff.js
const monthDiff = (startDate, endDate) =>
Math.max(0, (endDate.getFullYear() - startDate.getFullYear()) * 12 - startDate.getMonth() + endDate.getMonth());
```
**TypeScript version**
```ts monthDiff.ts
const monthDiff = (startDate: Date, endDate: Date): number =>
Math.max(0, (endDate.getFullYear() - startDate.getFullYear()) * 12 - startDate.getMonth() + endDate.getMonth());
```
**Example**
```js example.js
monthDiff(new Date('2020-01-01'), new Date('2021-01-01')); // 12
```
================================================
FILE: contents/calculate-the-remainder-of-division-of-arguments.mdx
================================================
---
category: Number
created: '2020-05-05'
title: Calculate the remainder of division of arguments
updated: '2021-10-13'
---
**JavaScript version**
```js remainder.js
const remainder = (...args) => args.reduce((a, b) => a % b);
```
**TypeScript version**
```ts remainder.ts
const remainder = (...args: number[]): number => args.reduce((a, b) => a % b);
```
**Examples**
```js examples.js
remainder(1, 2, 3, 4); // 1
```
================================================
FILE: contents/calculate-the-sum-of-arguments.mdx
================================================
---
category: Number
created: '2020-05-05'
title: Calculate the sum of arguments
updated: '2021-10-13'
---
**JavaScript version**
```js sum.js
const sum = (...args) => args.reduce((a, b) => a + b);
```
**TypeScript version**
```ts sum.ts
const sum = (...args: number[]): number => args.reduce((a, b) => a + b);
```
**Examples**
```js examples.js
sum(1, 2, 3, 4); // 10
```
================================================
FILE: contents/capitalize-a-string.mdx
================================================
---
category: String
contributors:
- Edmon Narmetov
- fahimfaisaal
created: '2023-04-11'
title: Capitalize a string
updated: '2020-04-19'
---
**JavaScript version**
```js capitalize.js
const capitalize = (str) => `${str.charAt(0).toUpperCase()}${str.slice(1)}`;
// Or
const capitalize = ([first, ...rest]) => `${first.toUpperCase()}${rest.join('')}`;
// Or
const capitalize = (str) => str.replace(/^([a-z])/, (first) => first.toUpperCase());
```
**TypeScript version**
```ts capitalize.ts
const capitalize = (str: string): string => `${str.charAt(0).toUpperCase()}${str.slice(1)}`;
// Or
const capitalize = ([first, ...rest]: string): string => `${first.toUpperCase()}${rest.join('')}`;
// Or
const capitalize = (str: string): string => str.replace(/^([a-z])/, (first) => first.toUpperCase());
```
**Examples**
```js examples.js
capitalize('hello world'); // 'Hello world'
```
================================================
FILE: contents/cast-a-value-as-an-array.mdx
================================================
---
category: Array
title: Cast a value as an array
created: '2021-04-04'
updated: '2021-10-22'
---
**JavaScript version**
```js castArray.js
const castArray = (value) => (Array.isArray(value) ? value : [value]);
```
**TypeScript version**
```ts castArray.ts
const castArray = <T,_>(value: T | T[]): T[] => (Array.isArray(value) ? value : [value]);
```
**Examples**
```js examples.js
castArray(1); // [1]
castArray([1, 2, 3]); // [1, 2, 3]
```
================================================
FILE: contents/check-if-a-character-is-a-digit.mdx
================================================
---
category: Validator
created: '2021-10-22'
title: Check if a character is a digit
---
**JavaScript version**
```js isDigit.js
const isDigit = (char) => char < 10;
// Or
const isDigit = (char) => char.length === 1 && c >= '0' && c <= '9';
// Or
const isDigit = (char) => Boolean([true, true, true, true, true, true, true, true, true, true][char]);
```
**TypeScript version**
```ts isDigit.ts
const isDigit = (char: string): boolean => char < 10;
// Or
const isDigit = (char: string): boolean => char.length === 1 && c >= '0' && c <= '9';
// Or
const isDigit = (char: string): boolean => Boolean([true, true, true, true, true, true, true, true, true, true][char]);
```
**Examples**
```js examples.js
isDigit('a'); // false
isDigit('abc'); // false
isDigit(10); // false
isDigit('10'); // false
isDigit('2'); // true
isDigit(2); // true
```
================================================
FILE: contents/check-if-a-date-is-a-weekday.mdx
================================================
---
category: Validator
created: '2021-02-25'
title: Check if a date is a weekday
updated: '2021-10-13'
---
**JavaScript version**
```js isWeekday.js
// `date` is a Date object
const isWeekday = (date = new Date()) => date.getDay() % 6 !== 0;
```
**TypeScript version**
```ts isWeekday.ts
const isWeekday = (date = new Date()): boolean => date.getDay() % 6 !== 0;
```
================================================
FILE: contents/check-if-a-date-is-a-weekend.mdx
================================================
---
category: Validator
created: '2021-02-25'
title: Check if a date is a weekend
updated: '2021-10-13'
---
**JavaScript version**
```js isWeekend.js
// `date` is a Date object
const isWeekend = (date = new Date()) => date.getDay() % 6 === 0;
```
**TypeScript version**
```ts isWeekend.ts
const isWeekend = (date = new Date()): boolean => date.getDay() % 6 === 0;
```
================================================
FILE: contents/check-if-a-date-is-between-two-dates.mdx
================================================
---
category: Validator
created: '2020-04-19'
title: Check if a date is between two dates
updated: '2021-10-13'
---
**JavaScript version**
```js isBetween.js
// `min`, `max` and `date` are `Date` instances
const isBetween = (date, min, max) => date.getTime() >= min.getTime() && date.getTime() <= max.getTime();
```
**TypeScript version**
```ts isBetween.ts
const isBetween = (date: Date, min: Date, max: Date): boolean =>
date.getTime() >= min.getTime() && date.getTime() <= max.getTime();
```
================================================
FILE: contents/check-if-a-date-is-today.mdx
================================================
---
category: Validator
created: '2020-05-05'
title: Check if a date is today
updated: '2021-10-13'
---
**JavaScript version**
```js isToday.js
// `date` is a Date object
const isToday = (date) => date.toISOString().slice(0, 10) === new Date().toISOString().slice(0, 10);
```
**TypeScript version**
```ts isToday.ts
const isToday = (date: Date): boolean => date.toISOString().slice(0, 10) === new Date().toISOString().slice(0, 10);
```
================================================
FILE: contents/check-if-a-date-occurs-in-the-current-year.mdx
================================================
---
category: Validator
created: '2021-04-13'
title: Check if a date occurs in the current year
updated: '2021-10-13'
---
**JavaScript version**
```js isCurrentYear.js
// `date` is a Date object
const isCurrentYear = (date) => date.getUTCFullYear() === new Date().getUTCFullYear();
```
**TypeScript version**
```ts isCurrentYear.ts
const isCurrentYear = (date: Date): boolean => date.getUTCFullYear() === new Date().getUTCFullYear();
```
================================================
FILE: contents/check-if-a-flat-array-has-duplicate-values.mdx
================================================
---
category: Validator
created: '2021-02-25'
title: Check if a flat array has duplicate values
updated: '2022-01-26'
---
**JavaScript version**
```js hasDuplicateValues.js
const hasDuplicateValues = (arr) => new Set(arr).size !== arr.length;
// Or
const hasDuplicateValues = (arr) => arr.some((item, index, arr) => arr.indexOf(item) !== index);
```
**TypeScript version**
```ts hasDuplicateValues.ts
const hasDuplicateValues = <T,_>(arr: T[]): boolean => new Set(arr).size !== arr.length;
// Or
const hasDuplicateValues = <T,_>(arr: T[]): boolean => arr.some((item, index, arr) => arr.indexOf(item) !== index);
```
**Examples**
```js examples.js
hasDuplicateValues(['h', 'e', 'l', 'l', 'o']); // true
hasDuplicateValues(['w', 'o', 'r', 'd']); // false
```
================================================
FILE: contents/check-if-a-given-dom-rect-is-contained-within-another-dom-rect.mdx
================================================
---
category: DOM
created: '2023-12-11'
openGraphCover: /og/1-loc/check-given-dom-rect-contained-within-another-dom-rect.png
title: Check if a given DOMRect is contained within another DOMRect
---
**JavaScript version**
```js isContained.js
const isContained = (target, container) => (
target.left >= container.left &&
target.left + target.width <= container.left + container.width &&
target.top >= container.top &&
target.top + target.height <= container.top + container.height
);
```
**TypeScript version**
```ts isContained.ts
const isContained = (target: DOMRect, container: DOMRect): boolean => (
target.left >= container.left &&
target.left + target.width <= container.left + container.width &&
target.top >= container.top &&
target.top + target.height <= container.top + container.height
);
```
**Example**
```js example.js
const target = new DOMRect(10, 10, 20, 20);
const container = new DOMRect(0, 0, 40, 40);
isContained(target, container); // true
```
## See also
- [Check if two DOMRects intersect](https://phuoc.ng/collection/1-loc/check-if-two-dom-rects-intersect/)
================================================
FILE: contents/check-if-a-given-integer-is-a-prime-number.mdx
================================================
---
category: Validator
created: '2020-04-19'
title: Check if a given integer is a prime number
updated: '2021-10-13'
---
**JavaScript version**
```js isPrime.js
const isPrime = (n) =>
n > 1 &&
Array(Math.floor(Math.sqrt(n)) - 1)
.fill(0)
.map((_, i) => i + 2)
.every((i) => n % i !== 0);
```
**TypeScript version**
```ts isPrime.ts
const isPrime = (n: number): boolean =>
n > 1 &&
Array(Math.floor(Math.sqrt(n)) - 1)
.fill(0)
.map((_, i) => i + 2)
.every((i) => n % i !== 0);
```
================================================
FILE: contents/check-if-a-number-is-a-power-of-2.mdx
================================================
---
category: Validator
created: '2020-04-19'
title: Check if a number is a power of 2
updated: '2021-10-13'
---
**JavaScript version**
```js isPowerOfTwo.js
const isPowerOfTwo = (n) => (n & (n - 1)) === 0;
```
**TypeScript version**
```ts isPowerOfTwo.ts
const isPowerOfTwo = (n: number): boolean => (n & (n - 1)) === 0;
```
**Examples**
```js examples.js
isPowerOfTwo(256); // true
isPowerOfTwo(129); // false
```
================================================
FILE: contents/check-if-a-number-is-even.mdx
================================================
---
category: Validator
contributors:
- chety
- ietienam
- Vadim-Moshev
- marcobiedermann
created: '2020-05-06'
title: Check if a number is even
updated: '2021-10-13'
---
**JavaScript version**
```js isEven.js
const isEven = (n) => n % 2 === 0;
// Or
const isEven = (n) => (n & 1) === 0;
// Or
const isEven = (n) => !(n & 1);
// Or
const isEven = (n) => Number.isInteger(n / 2);
```
**TypeScript version**
```ts isEven.ts
const isEven = (n: number): boolean => n % 2 === 0;
// Or
const isEven = (n: number): boolean => (n & 1) === 0;
// Or
const isEven = (n: number): boolean => !(n & 1);
// Or
const isEven = (n: number): boolean => Number.isInteger(n / 2);
```
**Examples**
```js examples.js
isEven(1); // false
isEven(2); // true
```
================================================
FILE: contents/check-if-a-number-is-in-a-given-range.mdx
================================================
---
category: Validator
created: '2020-06-04'
title: Check if a number is in a given range
updated: '2021-10-13'
---
**JavaScript version**
```js inRange.js
const inRange = (num, a, b, threshold = 0) => Math.min(a, b) - threshold <= num && num <= Math.max(a, b) + threshold;
```
**TypeScript version**
```ts inRange.ts
const inRange = (num: number, a: number, b: number, threshold: number = 0): boolean =>
Math.min(a, b) - threshold <= num && num <= Math.max(a, b) + threshold;
```
**Examples**
```js examples.js
inRange(10, 5, 15); // true
inRange(10, 5, 6); // false
inRange(10, 15, 5); // true
inRange(-10, -5, -15); // true
```
================================================
FILE: contents/check-if-a-number-is-negative.mdx
================================================
---
category: Validator
contributors:
- sadirde
- tugsanunlu
created: '2020-05-07'
title: Check if a number is negative
updated: '2021-10-13'
---
**JavaScript version**
```js isNegative.js
const isNegative = (n) => Math.sign(n) === -1;
// Or
const isNegative = (n) => n < 0;
```
**TypeScript version**
```ts isNegative.ts
const isNegative = (n: number): boolean => Math.sign(n) === -1;
// Or
const isNegative = (n: number): boolean => n < 0;
```
**Examples**
```js examples.js
isNegative(-3); // true
isNegative(8); // false
```
================================================
FILE: contents/check-if-a-number-is-odd.mdx
================================================
---
category: Validator
contributors:
- ietienam
- Namysh
- marcobiedermann
created: '2020-05-06'
title: Check if a number is odd
updated: '2021-10-13'
---
**JavaScript version**
```js isOdd.js
const isOdd = (n) => n % 2 !== 0;
// Or
const isOdd = (n) => !!(n & 1);
// Or
const isOdd = (n) => !Number.isInteger(n / 2);
```
**TypeScript version**
```ts isOdd.ts
const isOdd = (n: number): boolean => n % 2 !== 0;
// Or
const isOdd = (n: number): boolean => !!(n & 1);
// Or
const isOdd = (n: number): boolean => !Number.isInteger(n / 2);
```
**Examples**
```js examples.js
isOdd(1); // true
isOdd(2); // false
```
================================================
FILE: contents/check-if-a-number-is-positive.mdx
================================================
---
category: Validator
contributors:
- tugsanunlu
created: '2020-05-07'
title: Check if a number is positive
updated: '2021-10-13'
---
**JavaScript version**
```js isPositive.js
const isPositive = (n) => Math.sign(n) === 1;
```
**TypeScript version**
```ts isPositive.ts
const isPositive = (n: number): boolean => Math.sign(n) === 1;
```
**Examples**
```js examples.js
isPositive(3); // true
isPositive(-8); // false
```
================================================
FILE: contents/check-if-a-path-is-relative.mdx
================================================
---
category: String
created: '2020-05-15'
title: Check if a path is relative
updated: '2021-10-13'
---
**JavaScript version**
```js isRelative.js
const isRelative = (path) => !/^([a-z]+:)?[\\/]/i.test(path);
```
**TypeScript version**
```ts isRelative.ts
const isRelative = (path: string): boolean => !/^([a-z]+:)?[\\/]/i.test(path);
```
**Examples**
```js examples.js
isRelative('/foo/bar/baz'); // false
isRelative('C:\\foo\\bar\\baz'); // false
isRelative('foo/bar/baz.txt'); // true
isRelative('foo.md'); // true
```
================================================
FILE: contents/check-if-a-point-is-inside-a-rectangle.mdx
================================================
---
category: Math
created: '2021-04-05'
title: Check if a point is inside a rectangle
updated: '2021-10-13'
---
**JavaScript version**
```js isInside.js
const isInside = (point, rect) =>
point.x > rect.left && point.x < rect.right && point.y > rect.top && point.y < rect.bottom;
```
**TypeScript version**
```ts isInside.ts
interface Point {
x: number;
y: number;
}
interface Rect {
bottom: number;
left: number;
top: number;
right: number;
}
const isInside = (point: Point, rect: Rect): boolean =>
point.x > rect.left && point.x < rect.right && point.y > rect.top && point.y < rect.bottom;
```
================================================
FILE: contents/check-if-a-rectangle-contains-other-one.mdx
================================================
---
category: Math
created: '2021-04-08'
title: Check if a rectangle contains other one
updated: '2021-10-13'
---
**JavaScript version**
```js contains.js
// Returns true if `a` contains `b`
// (x1, y1) and (x2, y2) are top-left and bottom-right corners
const contains = (a, b) => a.x1 <= b.x1 && a.y1 <= b.y1 && a.x2 >= b.x2 && a.y2 >= b.y2;
```
**TypeScript version**
```ts contains.ts
interface Rect {
x1: number;
x2: number;
y1: number;
y2: number;
}
const contains = (a: Rect, b: Rect): boolean => a.x1 <= b.x1 && a.y1 <= b.y1 && a.x2 >= b.x2 && a.y2 >= b.y2;
```
================================================
FILE: contents/check-if-a-rectangle-overlaps-other-one.mdx
================================================
---
category: Math
created: '2021-04-08'
title: Check if a rectangle overlaps other one
updated: '2021-10-13'
---
**JavaScript version**
```js overlaps.js
// Returns true if `a` overlaps `b`
// (x1, y1) and (x2, y2) are top-left and bottom-right corners
const overlaps = (a, b) => (a.x1 < b.x2 && b.x1 < a.x2) || (a.y1 < b.y2 && b.y1 < a.y2);
```
**TypeScript version**
```ts overlaps.ts
interface Rect {
x1: number;
x2: number;
y1: number;
y2: number;
}
const overlaps = (a: Rect, b: Rect): boolean => (a.x1 < b.x2 && b.x1 < a.x2) || (a.y1 < b.y2 && b.y1 < a.y2);
```
================================================
FILE: contents/check-if-a-string-consists-of-a-repeated-character-sequence.mdx
================================================
---
category: String
created: '2021-04-21'
title: Check if a string consists of a repeated character sequence
updated: '2021-10-13'
---
**JavaScript version**
```js consistsRepeatedSubstring.js
const consistsRepeatedSubstring = (str) => `${str}${str}`.indexOf(str, 1) !== str.length;
```
**TypeScript version**
```ts consistsRepeatedSubstring.ts
const consistsRepeatedSubstring = (str: string): boolean => `${str}${str}`.indexOf(str, 1) !== str.length;
```
**Examples**
```js examples.js
consistsRepeatedSubstring('aa'); // true
consistsRepeatedSubstring('aaa'); // true
consistsRepeatedSubstring('ababab'); // true
consistsRepeatedSubstring('abc'); // false
```
================================================
FILE: contents/check-if-a-string-contains-lower-case-characters.mdx
================================================
---
category: Validator
created: '2020-05-16'
title: Check if a string contains lower case characters
updated: '2021-10-13'
---
**JavaScript version**
```js containsLowerCase.js
const containsLowerCase = (str) => str !== str.toUpperCase();
```
**TypeScript version**
```ts containsLowerCase.ts
const containsLowerCase = (str: string): boolean => str !== str.toUpperCase();
```
**Examples**
```js examples.js
containsLowerCase('Hello World'); // true
containsLowerCase('HELLO WORLD'); // false
```
================================================
FILE: contents/check-if-a-string-contains-only-ascii-characters.mdx
================================================
---
category: Validator
created: '2020-06-09'
title: Check if a string contains only ASCII characters
updated: '2021-10-13'
---
**JavaScript version**
```js isAscii.js
const isAscii = (str) => /^[\x00-\x7F]+$/.test(str);
```
**TypeScript version**
```ts isAscii.ts
const isAscii = (str: string): boolean => /^[\x00-\x7F]+$/.test(str);
```
================================================
FILE: contents/check-if-a-string-contains-only-digits.mdx
================================================
---
category: Validator
created: '2020-05-09'
title: Check if a string contains only digits
updated: '2021-10-13'
---
**JavaScript version**
```js isNumeric.js
const isNumeric = (str) => !/[^0-9]/.test(str);
```
**TypeScript version**
```ts isNumeric.ts
const isNumeric = (str: string): boolean => !/[^0-9]/.test(str);
```
**Examples**
```js examples.js
isNumeric(2); // true
isNumeric('23'); // true
isNumeric('00123'); // true
isNumeric('1.23'); // false
isNumeric('-Infinity'); // false
isNumeric('Infinity'); // false
isNumeric('NaN'); // false
```
================================================
FILE: contents/check-if-a-string-contains-only-letters-and-numbers.mdx
================================================
---
category: Validator
created: '2020-06-08'
title: Check if a string contains only letters and numbers
updated: '2021-10-13'
---
**JavaScript version**
```js isAlphanumeric.js
const isAlphanumeric = (str) => /^[0-9A-Z]+$/i.test(str);
```
**TypeScript version**
```ts isAlphanumeric.ts
const isAlphanumeric = (str: string): boolean => /^[0-9A-Z]+$/i.test(str);
```
**Examples**
```js examples.js
isAlphanumeric('helloworld'); // true
isAlphanumeric('HelloWorld'); // true
isAlphanumeric('hello world'); // false
isAlphanumeric('hello123'); // true
isAlphanumeric('hello 123'); // false
```
================================================
FILE: contents/check-if-a-string-contains-only-letters.mdx
================================================
---
category: Validator
created: '2020-06-07'
title: Check if a string contains only letters
updated: '2021-10-13'
---
**JavaScript version**
```js isAlpha.js
const isAlpha = (str) => /^[A-Z]+$/i.test(str);
```
**TypeScript version**
```ts isAlpha.ts
const isAlpha = (str: string): boolean => /^[A-Z]+$/i.test(str);
```
**Examples**
```js examples.js
isAlpha('helloworld'); // true
isAlpha('HelloWorld'); // true
isAlpha('hello world'); // false
isAlpha('0123456789'); // false
```
================================================
FILE: contents/check-if-a-string-contains-upper-case-characters.mdx
================================================
---
category: Validator
created: '2020-05-16'
title: Check if a string contains upper case characters
updated: '2021-10-13'
---
**JavaScript version**
```js containsUpperCase.js
const containsUpperCase = (str) => str !== str.toLowerCase();
```
**TypeScript version**
```ts containsUpperCase.ts
const containsUpperCase = (str: string): boolean => str !== str.toLowerCase();
```
**Examples**
```js examples.js
containsUpperCase('Hello World'); // true
containsUpperCase('hello world'); // false
```
================================================
FILE: contents/check-if-a-string-contains-whitespace.mdx
================================================
---
category: Validator
created: '2020-04-19'
title: Check if a string contains whitespace
updated: '2021-10-13'
---
**JavaScript version**
```js containsWhitespace.js
const containsWhitespace = (str) => (str) => /\s/.test(str);
```
**TypeScript version**
```ts containsWhitespace.ts
const containsWhitespace =
(str: string): boolean =>
(str) =>
/\s/.test(str);
```
**Examples**
```js examples.js
containsWhitespace('hello world'); // true
```
================================================
FILE: contents/check-if-a-string-is-a-hexadecimal-color.mdx
================================================
---
category: Validator
created: '2020-06-09'
title: Check if a string is a hexadecimal color
updated: '2021-10-13'
---
**JavaScript version**
```js isHexColor.js
const isHexColor = (color) => /^#([0-9A-F]{3}|[0-9A-F]{4}|[0-9A-F]{6}|[0-9A-F]{8})$/i.test(color);
```
**TypeScript version**
```ts isHexColor.ts
const isHexColor = (color: string): boolean => /^#([0-9A-F]{3}|[0-9A-F]{4}|[0-9A-F]{6}|[0-9A-F]{8})$/i.test(color);
```
**Examples**
```js examples.js
isHexColor('#012'); // true
isHexColor('#A1B2C3'); // true
isHexColor('012'); // false
isHexColor('#GHIJKL'); // false
```
================================================
FILE: contents/check-if-a-string-is-a-hexadecimal-number.mdx
================================================
---
category: Validator
created: '2020-06-10'
title: Check if a string is a hexadecimal number
updated: '2021-10-13'
---
**JavaScript version**
```js isHexadecimal.js
const isHexadecimal = (str) => /^[A-F0-9]+$/i.test(str);
// Or
const isHexadecimal = (str) => str.split('').every((c) => '0123456789ABCDEFabcdef'.indexOf(c) !== -1);
```
**TypeScript version**
```ts isHexadecimal.ts
const isHexadecimal = (str: string): boolean => /^[A-F0-9]+$/i.test(str);
// Or
const isHexadecimal = (str: string): boolean => str.split('').every((c) => '0123456789ABCDEFabcdef'.indexOf(c) !== -1);
```
**Examples**
```js examples.js
isHexadecimal('123'); // true
isHexadecimal('A1B2C3'); // true
isHexadecimal('#123'); // false
```
================================================
FILE: contents/check-if-a-string-is-a-mongo-db-object-id.mdx
================================================
---
category: Validator
created: '2021-04-10'
title: Check if a string is a MongoDB ObjectId
updated: '2021-10-13'
---
**JavaScript version**
```js isMongoId.js
const isMongoId = (str) => str.length === 24 && /^[A-F0-9]+$/i.test(str);
// Or
const isMongoId = (str) => str.length === 24 && str.split('').every((c) => '0123456789ABCDEFabcdef'.indexOf(c) !== -1);
```
**TypeScript version**
```ts isMongoId.ts
const isMongoId = (str: string): boolean => str.length === 24 && /^[A-F0-9]+$/i.test(str);
// Or
const isMongoId = (str: string): boolean =>
str.length === 24 && str.split('').every((c) => '0123456789ABCDEFabcdef'.indexOf(c) !== -1);
```
================================================
FILE: contents/check-if-a-string-is-a-palindrome.mdx
================================================
---
category: String
contributors:
- marcobiedermann
created: '2020-05-18'
title: Check if a string is a palindrome
updated: '2021-10-13'
---
**JavaScript version**
```js isPalindrome.js
const isPalindrome = (str) => str === str.split('').reverse().join('');
```
**TypeScript version**
```ts isPalindrome.ts
const isPalindrome = (str: string): boolean => str === str.split('').reverse().join('');
```
**Examples**
```js examples.js
isPalindrome('abc'); // false
isPalindrom('abcba'); // true
```
================================================
FILE: contents/check-if-a-string-is-an-octal-number.mdx
================================================
---
category: Validator
created: '2021-04-10'
title: Check if a string is an octal number
updated: '2021-10-13'
---
**JavaScript version**
```js isOctal.js
const isOctal = (str) => /^(0o)?[0-7]+$/i.test(str);
```
**TypeScript version**
```ts isOctal.ts
const isOctal = (str: string): boolean => /^(0o)?[0-7]+$/i.test(str);
```
================================================
FILE: contents/check-if-a-string-is-lower-case.mdx
================================================
---
category: Validator
created: '2020-04-19'
title: Check if a string is lower case
updated: '2021-10-13'
---
**JavaScript version**
```js isLowerCase.js
const isLowerCase = (str) => str === str.toLowerCase();
```
**TypeScript version**
```ts isLowerCase.ts
const isLowerCase = (str: string): boolean => str === str.toLowerCase();
```
================================================
FILE: contents/check-if-a-string-is-upper-case.mdx
================================================
---
category: Validator
created: '2020-04-19'
title: Check if a string is upper case
updated: '2021-10-13'
---
**JavaScript version**
```js isUpperCase.js
const isUpperCase = (str) => str === str.toUpperCase();
```
**TypeScript version**
```ts isUpperCase.ts
const isUpperCase = (str: string): boolean => str === str.toUpperCase();
```
================================================
FILE: contents/check-if-a-url-is-absolute.mdx
================================================
---
category: String
created: '2020-05-15'
title: Check if a URL is absolute
updated: '2021-10-13'
---
**JavaScript version**
```js isAbsoluteUrl.js
const isAbsoluteUrl = (url) => /^[a-z][a-z0-9+.-]*:/.test(url);
```
**TypeScript version**
```ts isAbsoluteUrl.ts
const isAbsoluteUrl = (url: string): boolean => /^[a-z][a-z0-9+.-]*:/.test(url);
```
**Examples**
```js examples.js
isAbsoluteUrl('https://phuoc.ng'); // true
isAbsoluteUrl('https://phuoc.ng/collection/1-loc'); // true
isAbsoluteUrl('phuoc.ng'); // false
isAbsoluteUrl('//phuoc.ng'); // false
```
================================================
FILE: contents/check-if-a-value-is-a-business-identifier-code.mdx
================================================
---
category: Validator
created: '2021-04-10'
title: Check if a value is a business identifier code
updated: '2021-10-13'
---
**JavaScript version**
```js isBIC.js
const isBIC = (value) => /^[a-zA-Z]{6}[a-zA-Z0-9]{2}([a-zA-Z0-9]{3})?$/.test(value);
```
**TypeScript version**
```ts isBIC.ts
const isBIC = (value: string): boolean => /^[a-zA-Z]{6}[a-zA-Z0-9]{2}([a-zA-Z0-9]{3})?$/.test(value);
```
================================================
FILE: contents/check-if-a-value-is-a-function.mdx
================================================
---
category: Function
created: '2020-05-15'
title: Check if a value is a function
---
**JavaScript version**
```js isFunction.js
const isFunction = (v) =>
['[object Function]', '[object GeneratorFunction]', '[object AsyncFunction]', '[object Promise]'].includes(
Object.prototype.toString.call(v)
);
```
**Examples**
```js examples.js
isFunction(function () {}); // true
isFunction(function* () {}); // true
isFunction(async function () {}); // true
```
================================================
FILE: contents/check-if-a-value-is-a-generator-function.mdx
================================================
---
category: Function
created: '2020-05-15'
title: Check if a value is a generator function
---
**JavaScript version**
```js isGeneratorFunction.js
const isGeneratorFunction = (v) => Object.prototype.toString.call(v) === '[object GeneratorFunction]';
```
**Examples**
```js examples.js
isGeneratorFunction(function () {}); // false
isGeneratorFunction(function* () {}); // true
```
================================================
FILE: contents/check-if-a-value-is-a-number.mdx
================================================
---
category: Validator
contributors:
- nbayramberdiyev
created: '2020-04-23'
title: Check if a value is a number
updated: '2021-11-03'
---
**JavaScript version**
```js isNumber.js
const isNumber = (value) => !isNaN(parseFloat(value)) && isFinite(value);
```
**TypeScript version**
```ts isNumber.ts
const isNumber = (value: any): number => !isNaN(parseFloat(value)) && isFinite(value);
```
================================================
FILE: contents/check-if-a-value-is-a-plain-object.mdx
================================================
---
category: Validator
created: '2020-05-13'
title: Check if a value is a plain object
updated: '2021-10-13'
---
**JavaScript version**
```js isPlainObject.js
const isPlainObject = (v) => !!v && typeof v === 'object' && (v.__proto__ === null || v.__proto__ === Object.prototype);
```
**TypeScript version**
```ts isPlainObject.ts
const isPlainObject = (v: any): boolean =>
!!v && typeof v === 'object' && (v.__proto__ === null || v.__proto__ === Object.prototype);
```
**Examples**
```js examples.js
isPlainObject(null); // false
isPlainObject('hello world'); // false
isPlainObject([]); // false
isPlainObject(Object.create(null)); // false
isPlainObject(function () {}); // false
isPlainObject({}); // true
isPlainObject({ a: '1', b: '2' }); // true
```
================================================
FILE: contents/check-if-a-value-is-a-regular-expression.mdx
================================================
---
category: Validator
created: '2020-05-14'
title: Check if a value is a regular expression
updated: '2021-10-13'
---
**JavaScript version**
```js isRegExp.js
const isRegExp = (value) => Object.prototype.toString.call(value) === '[object RegExp]';
```
**TypeScript version**
```ts isRegExp.ts
const isRegExp = (value: any): boolean => Object.prototype.toString.call(value) === '[object RegExp]';
```
================================================
FILE: contents/check-if-a-value-is-a-string.mdx
================================================
---
category: Validator
created: '2020-06-05'
title: Check if a value is a string
updated: '2021-10-13'
---
**JavaScript version**
```js isString.js
const isString = (value) => Object.prototype.toString.call(value) === '[object String]';
```
**TypeScript version**
```ts isString.ts
const isString = (value: any): boolean => Object.prototype.toString.call(value) === '[object String]';
```
**Examples**
```js examples.js
isString('hello world'); // true
isString(new String('hello world')); // true
isString(10); // false
```
================================================
FILE: contents/check-if-a-value-is-an-async-function.mdx
================================================
---
category: Function
created: '2020-05-15'
title: Check if a value is an async function
---
**JavaScript version**
```js isAsyncFunction.js
const isAsyncFunction = (v) => Object.prototype.toString.call(v) === '[object AsyncFunction]';
```
**Examples**
```js examples.js
isAsyncFunction(function () {}); // false
isAsyncFunction(function* () {}); // false
isAsyncFunction(async function () {}); // true
```
================================================
FILE: contents/check-if-a-value-is-an-object.mdx
================================================
---
category: Validator
created: '2020-05-13'
title: Check if a value is an object
updated: '2021-10-13'
---
**JavaScript version**
```js isObject.js
const isObject = (v) => v !== null && typeof v === 'object';
```
**TypeScript version**
```ts isObject.ts
const isObject = (v: any): boolean => v !== null && typeof v === 'object';
```
**Examples**
```js examples.js
isObject(null); // false
isObject('hello world'); // false
isObject({}); // true
isObject([]); // true
```
================================================
FILE: contents/check-if-a-value-is-base32-encoded.mdx
================================================
---
category: Validator
created: '2021-04-10'
title: Check if a value is base32 encoded
updated: '2021-10-13'
---
**JavaScript version**
```js isBase32.js
const isBase32 = (value) => value.length % 8 === 0 && /^[A-Z2-7]+=*$/.test(value);
```
**TypeScript version**
```ts isBase32.ts
const isBase32 = (value: string): boolean => value.length % 8 === 0 && /^[A-Z2-7]+=*$/.test(value);
```
================================================
FILE: contents/check-if-a-value-is-base58-encoded.mdx
================================================
---
category: Validator
created: '2021-04-10'
title: Check if a value is base58 encoded
updated: '2021-10-13'
---
**JavaScript version**
```js isBase58.js
// It doesn't accept the I, O, l characters
const isBase58 = (value) => /^[A-HJ-NP-Za-km-z1-9]*$/.test(value);
```
**TypeScript version**
```ts isBase58.ts
const isBase58 = (value: string): boolean => /^[A-HJ-NP-Za-km-z1-9]*$/.test(value);
```
================================================
FILE: contents/check-if-a-value-is-base64-encoded.mdx
================================================
---
category: Validator
created: '2021-04-10'
title: Check if a value is base64 encoded
updated: '2021-10-13'
---
**JavaScript version**
```js isBase64.js
const isBase64 = (value) =>
/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/.test(value);
```
**TypeScript version**
```ts isBase64.ts
const isBase64 = (value: string): boolean =>
/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/.test(value);
```
================================================
FILE: contents/check-if-a-value-is-nil.mdx
================================================
---
category: Validator
contributors:
- JeromeDeLeon
created: '2020-05-06'
title: Check if a value is nil
updated: '2021-10-13'
---
**JavaScript version**
```js isNil.js
const isNil = (value) => value == null;
```
**TypeScript version**
```ts isNil.ts
const isNil = (value: any): boolean => value == null;
```
================================================
FILE: contents/check-if-a-year-is-leap-year.mdx
================================================
---
category: Validator
created: '2020-04-19'
title: Check if a year is leap year
updated: '2021-10-13'
---
**JavaScript version**
```js isLeapYear.js
const isLeapYear = (year) => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
// Or
// Get the number of days in February
const isLeapYear = (year) => new Date(year, 1, 29).getDate() === 29;
```
**TypeScript version**
```ts isLeapYear.ts
const isLeapYear = (year: number): boolean => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
// Or
const isLeapYear = (year: number): boolean => new Date(year, 1, 29).getDate() === 29;
```
================================================
FILE: contents/check-if-all-array-elements-are-equal-to-a-given-value.mdx
================================================
---
category: Validator
contributors:
- contributorpw
- tugsanunlu
created: '2020-05-08'
title: Check if all array elements are equal to a given value
updated: '2021-10-22'
---
**JavaScript version**
```js isEqual.js
const isEqual = (arr, value) => arr.every((item) => item === value);
// Or
// Ends earlier for false arrays
const isEqual = (arr, value) => !arr.some((item) => item !== value);
```
**TypeScript version**
```ts isEqual.ts
const isEqual = <T,_>(arr: T[], value: T): boolean => arr.every((item) => item === value);
// Or
const isEqual = <T,_>(arr: T[], value: T): boolean => !arr.some((item) => item !== value);
```
**Examples**
```js examples.js
isEqual(['foo', 'foo'], 'foo'); // true
isEqual(['foo', 'bar'], 'foo'); // false
isEqual(['bar', 'bar'], 'foo'); // false
```
================================================
FILE: contents/check-if-all-items-in-an-array-are-equal.mdx
================================================
---
category: Validator
contributors:
- manu2504
- glennfaison
created: '2020-04-19'
title: Check if all items in an array are equal
updated: '2021-10-22'
---
**JavaScript version**
```js areEqual.js
const areEqual = (arr) => arr.length > 0 && arr.every((item) => item === arr[0]);
// Or
const areEqual = (arr) => new Set(arr).size === 1;
```
**TypeScript version**
```ts areEqual.ts
const areEqual = <T,_>(arr: T[]): boolean => arr.length > 0 && arr.every((item) => item === arr[0]);
// Or
const areEqual = <T,_>(arr: T[]): boolean => new Set(arr).size === 1;
```
**Examples**
```js examples.js
areEqual([1, 2, 3, 4]); // false
areEqual(['hello', 'hello', 'hello']); // true
```
================================================
FILE: contents/check-if-an-array-contains-a-value-matching-some-criterias.mdx
================================================
---
category: Validator
contributors:
- chety
- nemanjapesic
- 31piy
- aethernet
created: '2020-05-10'
title: Check if an array contains a value matching some criterias
updated: '2021-10-22'
---
**JavaScript version**
```js contains.js
const contains = (arr, criteria) => arr.some((v) => criteria(v));
// Or
const contains = (arr, criteria) => arr.some(criteria);
// Or
const contains = (arr, criteria) => arr.filter(criteria).length > 0;
```
**TypeScript version**
```ts contains.ts
const contains = <T,_>(arr: T[], criteria: (a: T) => boolean): boolean => arr.some((v) => criteria(v));
// Or
const contains = <T,_>(arr: T[], criteria: (a: T) => boolean): boolean => arr.some(criteria);
// Or
const contains = <T,_>(arr: T[], criteria: (a: T) => boolean): boolean => arr.filter(criteria).length > 0;
```
**Examples**
```js examples.js
contains([10, 20, 30], (v) => v > 25); // true
contains([10, 20, 30], (v) => v > 100 || v < 15); // true
contains([10, 20, 30], (v) => v > 100); // false
```
================================================
FILE: contents/check-if-an-array-is-empty.mdx
================================================
---
category: Array
contributors:
- inoyakaigor
- elkarouani
created: '2020-06-23'
title: Check if an array is empty
updated: '2021-12-21'
---
**JavaScript version**
```js isEmpty.js
// `arr` is an array
const isEmpty = (arr) => Array.isArray(arr) && !arr.length;
```
**TypeScript version**
```ts isEmpty.ts
const isEmpty = <T,_>(arr: T[]): boolean => Array.isArray(arr) && !arr.length;
```
**Examples**
```js examples.js
isEmpty([]); // true
isEmpty([1, 2, 3]); // false
```
================================================
FILE: contents/check-if-an-array-is-not-empty.mdx
================================================
---
category: Validator
contributors:
- fenilgandhi
- marcobiedermann
created: '2020-05-06'
title: Check if an array is not empty
updated: '2021-10-13'
---
**JavaScript version**
```js isNotEmpty.js
const isNotEmpty = (arr) => Array.isArray(arr) && Object.keys(arr).length > 0;
```
**TypeScript version**
```ts isNotEmpty.ts
const isNotEmpty = (arr: any): boolean => Array.isArray(arr) && Object.keys(arr).length > 0;
```
**Examples**
```js examples.js
isNotEmpty([]); // false
isNotEmpty([1, 2, 3]); // true
```
================================================
FILE: contents/check-if-an-array-is-subset-of-other-array.mdx
================================================
---
category: Validator
contributors:
- lupu60
- Rupesh Jaiswal
created: '2020-05-10'
title: Check if an array is subset of other array
updated: '2021-10-22'
---
**JavaScript version**
```js isSubset.js
// Check if `b` is subset of `a`
const isSubset = (a, b) => new Set(b).size === new Set(b.concat(a)).size;
// Or
const isSubset = (a, b) => b.join('|').includes(a.join('|'));
```
**TypeScript version**
```ts isSubset.ts
const isSubset = <T,_>(a: T[], b: T[]): boolean => new Set(b).size === new Set(b.concat(a)).size;
// Or
const isSubset = <T,_>(a: T[], b: T[]): boolean => b.join('|').includes(a.join('|'));
```
**Examples**
```js examples.js
isSubset([1, 2], [1, 2, 3, 4]); // true
isSubset([1, 2, 5], [1, 2, 3, 4]); // false
isSubset([6], [1, 2, 3, 4]); // false
```
================================================
FILE: contents/check-if-an-element-has-css-overflow.mdx
================================================
---
category: DOM
created: '2023-12-15'
openGraphCover: /og/1-loc/check-element-has-css-overflow.png
tags: CSS overflow, getComputedStyle
title: Check if an element has CSS overflow
---
**JavaScript version**
```js hasCssOverflow.js
const hasCssOverflow = (ele) => ["auto", "scroll"].includes(window.getComputedStyle(ele)["overflow"]);
```
**TypeScript version**
```ts hasCssOverflow.ts
const hasCssOverflow = (ele: HTMLElement) => ["auto", "scroll"].includes(window.getComputedStyle(ele)["overflow"]);
```
The `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.
Next, 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`.
If neither of these values is present in the `overflow` property, we know there's no CSS overflow on the element and return `false`.
## See also
- [Check if an element has overflow](https://phuoc.ng/collection/1-loc/check-if-an-element-has-overflow/)
================================================
FILE: contents/check-if-an-element-has-overflow.mdx
================================================
---
category: DOM
created: '2023-12-16'
openGraphCover: /og/1-loc/check-element-has-overflow.png
title: Check if an element has overflow
---
**JavaScript version**
```js hasOverflow.js
const hasOverflow = (ele) => ele.scrollHeight > ele.clientHeight || ele.scrollWidth > ele.clientWidth;
```
**TypeScript version**
```ts hasOverflow.ts
const hasOverflow = (ele: HTMLElement) => ele.scrollHeight > ele.clientHeight || ele.scrollWidth > ele.clientWidth;
```
The `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.
If 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`.
This 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.
## See also
- [Check if an element has CSS overflow](https://phuoc.ng/collection/1-loc/check-if-an-element-has-css-overflow/)
================================================
FILE: contents/check-if-an-element-is-a-descendant-of-another.mdx
================================================
---
category: DOM
created: '2020-04-19'
title: Check if an element is a descendant of another
updated: '2021-10-13'
---
**JavaScript version**
```js isDescendant.js
const isDescendant = (child, parent) => parent.contains(child);
```
**TypeScript version**
```ts isDescendant.ts
const isDescendant = (child: Node, parent: Node): boolean => parent.contains(child);
```
================================================
FILE: contents/check-if-an-element-is-focused.mdx
================================================
---
category: DOM
created: '2020-04-19'
title: Check if an element is focused
updated: '2021-10-13'
---
**JavaScript version**
```js hasFocus.js
const hasFocus = (ele) => ele === document.activeElement;
```
**TypeScript version**
```ts hasFocus.ts
const hasFocus = (ele: Node): boolean => ele === document.activeElement;
```
================================================
FILE: contents/check-if-an-object-is-a-promise.mdx
================================================
---
category: Validator
contributors:
- quantumsheep
created: '2020-05-06'
title: Check if an object is a Promise
updated: '2021-10-13'
---
**JavaScript version**
```js isPromise.js
const isPromise = (obj) =>
!!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
```
**TypeScript version**
```ts isPromise.ts
const isPromise = (obj: any): boolean =>
!!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
```
================================================
FILE: contents/check-if-an-object-is-an-array.mdx
================================================
---
category: Validator
created: '2020-04-19'
title: Check if an object is an array
updated: '2021-10-13'
---
**JavaScript version**
```js isArray.js
const isArray = (obj) => Array.isArray(obj);
```
**TypeScript version**
```ts isArray.ts
const isArray = (obj: any): boolean => Array.isArray(obj);
```
================================================
FILE: contents/check-if-an-object-is-empty.mdx
================================================
---
category: Validator
contributors:
- robinpokorny
created: '2020-04-19'
title: Check if an object is empty
updated: '2021-10-13'
---
**JavaScript version**
```js isEmpty.js
const isEmpty = (obj) => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
// Or for enumerable property names only
const isEmpty = (obj) => JSON.stringify(obj) === '{}';
```
**TypeScript version**
```ts isEmpty.ts
const isEmpty = (obj: object): boolean => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
const isEmpty = (obj: object): boolean => JSON.stringify(obj) === '{}';
```
================================================
FILE: contents/check-if-multiple-objects-are-equal.mdx
================================================
---
category: Object
contributors:
- tugsanunlu
created: '2020-05-20'
title: Check if multiple objects are equal
updated: '2021-10-13'
---
**JavaScript version**
```js isEqual.js
const isEqual = (...objects) => objects.every((obj) => JSON.stringify(obj) === JSON.stringify(objects[0]));
```
**TypeScript version**
```ts isEqual.ts
const isEqual = (...objects: object[]): boolean =>
objects.every((obj) => JSON.stringify(obj) === JSON.stringify(objects[0]));
```
**Examples**
```js examples.js
isEqual({ foo: 'bar' }, { foo: 'bar' }); // true
isEqual({ foo: 'bar' }, { bar: 'foo' }); // false
```
================================================
FILE: contents/check-if-the-code-is-running-in-jest.mdx
================================================
---
category: Misc
created: '2022-06-18'
title: Check if the code is running in Jest
---
**JavaScript version**
```js isRunningInJest.js
const isRunningInJest = typeof process !== 'undefined' && process.env.JEST_WORKER_ID !== undefined;
```
**TypeScript version**
```ts isRunningInJest.ts
const isRunningInJest: boolean = typeof process !== 'undefined' && process.env.JEST_WORKER_ID !== undefined;
```
================================================
FILE: contents/check-if-the-code-is-running-in-node-js.mdx
================================================
---
category: Misc
created: '2020-05-02'
title: Check if the code is running in NodeJS
updated: '2021-10-13'
---
**JavaScript version**
```js isNode.js
const isNode = typeof process !== 'undefined' && process.versions != null && process.versions.node != null;
```
**TypeScript version**
```ts isNode.ts
const isNode: boolean = typeof process !== 'undefined' && process.versions != null && process.versions.node != null;
```
================================================
FILE: contents/check-if-the-code-is-running-in-the-browser.mdx
================================================
---
category: Misc
created: '2020-05-02'
title: Check if the code is running in the browser
updated: '2021-10-13'
---
**JavaScript version**
```js isBrowser.js
const isBrowser = typeof window === 'object' && typeof document === 'object';
```
**TypeScript version**
```ts isBrowser.ts
const isBrowser: boolean = typeof window === 'object' && typeof document === 'object';
```
================================================
FILE: contents/check-if-the-touch-events-are-supported.mdx
================================================
---
category: DOM
created: '2020-04-25'
title: Check if the touch events are supported
updated: '2021-10-13'
---
**JavaScript version**
```js touchSupported.js
const touchSupported = () =>
'ontouchstart' in window || (window.DocumentTouch && document instanceof window.DocumentTouch);
```
**TypeScript version**
```ts touchSupported.ts
const touchSupported = (): boolean => (
'ontouchstart' in window || (window as any)['DocumentTouch'] && document instanceof (window as any)['DocumentTouch']
);
```
================================================
FILE: contents/check-if-two-dom-rects-intersect.mdx
================================================
---
category: DOM
created: '2023-12-12'
openGraphCover: /og/1-loc/check-two-dom-rects-intersect.png
title: Check if two DOMRects intersect
---
**JavaScript version**
```js intersect.js
const intersect = (a, b) => (b.right >= a.left && b.left <= a.right && b.top <= a.bottom && b.bottom >= a.top);
```
**TypeScript version**
```ts intersect.ts
const intersect = (a: DOMRect, b: DOMRect): boolean => (b.right >= a.left && b.left <= a.right && b.top <= a.bottom && b.bottom >= a.top);
```
**Example**
```js example.js
const a = new DOMRect(0, 0, 40, 40);
const b = new DOMRect(10, 10, 20, 20);
intersect(a, b); // true
```
## See also
- [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/)
================================================
FILE: contents/check-if-two-strings-are-anagram.mdx
================================================
---
category: String
contributors:
- mahdiyar
created: '2020-05-07'
title: Check if two strings are anagram
updated: '2021-10-13'
---
**JavaScript version**
```js areAnagram.js
const areAnagram = (str1, str2) =>
str1.toLowerCase().split('').sort().join('') === str2.toLowerCase().split('').sort().join('');
```
**TypeScript version**
```ts areAnagram.ts
const areAnagram = (str1: string, str2: string): boolean =>
str1.toLowerCase().split('').sort().join('') === str2.toLowerCase().split('').sort().join('');
```
**Examples**
```js examples.js
areAnagram('listen', 'silent'); // true
areAnagram('they see', 'the eyes'); // true
areAnagram('node', 'deno'); // true
```
================================================
FILE: contents/check-if-user-scrolls-to-the-bottom-of-the-page.mdx
================================================
---
category: DOM
created: '2021-04-10'
title: Check if user scrolls to the bottom of the page
updated: '2021-10-13'
---
**JavaScript version**
```js isAtBottom.js
const isAtBottom = () =>
document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;
```
**TypeScript version**
```ts isAtBottom.ts
const isAtBottom = (): boolean =>
document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;
```
================================================
FILE: contents/clamp-a-number-between-two-values.mdx
================================================
---
category: Number
contributors:
- r-i-c-h
created: '2020-05-05'
title: Clamp a number between two values
updated: '2021-10-13'
---
**JavaScript version**
```js clamp.js
const clamp = (val, min = 0, max = 1) => Math.max(min, Math.min(max, val));
```
**TypeScript version**
```ts clamp.ts
const clamp = (val: number, min: number = 0, max: number = 1): number => Math.max(min, Math.min(max, val));
```
**Examples**
```js examples.js
clamp(199, 10, 25); // 25
```
## See also
- [Build a spin input](https://phuoc.ng/collection/html-dom/build-a-spin-input/)
- [Wrap a number between two values](https://phuoc.ng/collection/1-loc/wrap-a-number-between-two-values/)
================================================
FILE: contents/clear-all-cookies.mdx
================================================
---
category: Misc
contributors:
- iamandrewluca
created: '2021-04-20'
title: Clear all cookies
updated: '2021-10-13'
---
**JavaScript version**
```js clearCookies.js
const clearCookies = () =>
document.cookie
.split(';')
.forEach(
(c) =>
(document.cookie = c.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`))
);
```
**TypeScript version**
```ts clearCookies.ts
const clearCookies = (): void =>
document.cookie
.split(';')
.forEach(
(c) =>
(document.cookie = c.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`))
);
```
**Examples**
```js examples.js
clearCookies();
```
================================================
FILE: contents/clone-an-array.mdx
================================================
---
category: Array
contributors:
- tahseenio
created: '2020-05-07'
title: Clone an array
updated: '2022-06-27'
---
**JavaScript version**
```js clone.js
// `arr` is an array
const clone = (arr) => arr.slice(0);
// Or
const clone = (arr) => [...arr];
// Or
const clone = (arr) => Array.from(arr);
// Or
const clone = (arr) => arr.map((x) => x);
// Or
const clone = (arr) => JSON.parse(JSON.stringify(arr));
// Or
const clone = (arr) => arr.concat([]);
// Or
const clone = (arr) => structuredClone(arr);
```
**TypeScript version**
```ts clone.ts
// `arr` is an array
const clone = <T,_>(arr: T[]): T[] => arr.slice(0);
// Or
const clone = <T,_>(arr: T[]): T[] => [...arr];
// Or
const clone = <T,_>(arr: T[]): T[] => Array.from(arr);
// Or
const clone = <T,_>(arr: T[]): T[] => arr.map((x) => x);
// Or
const clone = <T,_>(arr: T[]): T[] => JSON.parse(JSON.stringify(arr));
// Or
const clone = <T,_>(arr: T[]): T[] => arr.concat([]);
// Or
const clone = <T,_>(arr: T[]): T[] => structuredClone(arr);
```
================================================
FILE: contents/compare-two-arrays-regardless-of-order.mdx
================================================
---
category: Array
contributors:
- Rupesh Jaiswal
- robinpokorny
- dauom
- elkarouani
created: '2020-05-11'
title: Compare two arrays regardless of order
updated: '2021-12-23'
---
**JavaScript version**
```js isEqual.js
// `a` and `b` are arrays
const isEqual = (a, b) => JSON.stringify([...new Set(a)].sort()) === JSON.stringify([...new Set(b)].sort());
```
**TypeScript version**
```ts isEqual.ts
const isEqual = <T,_>(a: T[], b: T[]): boolean => JSON.stringify([...(new Set(a))].sort()) === JSON.stringify([...(new Set(b))].sort());
```
**Examples**
```js examples.js
isEqual([1, 2, 3], [1, 2, 3]); // true
isEqual([1, 2, 3], [1, 3, 2]); // true
isEqual([1, 2, 3], [1, '2', 3]); // false
```
================================================
FILE: contents/compare-two-arrays.mdx
================================================
---
category: Array
created: '2020-05-05'
title: Compare two arrays
updated: '2021-10-22'
---
**JavaScript version**
```js isEqual.js
// `a` and `b` are arrays
const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
// Or
const isEqual = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
```
**TypeScript version**
```ts isEqual.ts
const isEqual = <T,_>(a: T[], b: T[]): boolean => JSON.stringify(a) === JSON.stringify(b);
// Or
const isEqual = <T,_>(a: T[], b: T[]): boolean => a.length === b.length && a.every((v, i) => v === b[i]);
```
**Examples**
```js examples.js
isEqual([1, 2, 3], [1, 2, 3]); // true
isEqual([1, 2, 3], [1, '2', 3]); // false
```
================================================
FILE: contents/compare-two-dates.mdx
================================================
---
category: Date Time
created: '2020-04-19'
title: Compare two dates
updated: '2021-10-13'
---
**JavaScript version**
```js compare.js
// `a` and `b` are `Date` instances
const compare = (a, b) => a.getTime() > b.getTime();
```
**TypeScript version**
```ts compare.ts
const compare = (a: Date, b: Date): boolean => a.getTime() > b.getTime();
```
**Example**
```js example.js
compare(new Date('2020-03-30'), new Date('2020-01-01')); // true
```
================================================
FILE: contents/compare-two-dom-rects-for-size-and-position-match.mdx
================================================
---
category: DOM
created: '2023-12-10'
openGraphCover: /og/1-loc/compare-two-dom-rects-size-position-match.png
title: Compare two DOMRects for size and position match
---
**JavaScript version**
```js compare.js
const compare = (a, b) => ['top', 'left', 'width', 'height'].every(key => a[key] === b[key]);
```
**Example**
```js example.js
const a = new DOMRect(0, 0, 100, 200);
const b = new DOMRect(0, 0, 100, 200);
compare(a, b); // true
```
================================================
FILE: contents/compose-functions-from-left-to-right.mdx
================================================
---
category: Function
created: '2020-05-12'
title: Compose functions from left to right
---
**JavaScript version**
```js pipe.js
// Compose functions from left to right
const pipe =
(...fns) =>
(x) =>
fns.reduce((y, f) => f(y), x);
```
**Examples**
```js examples.js
const lowercase = (str) => str.toLowerCase();
const capitalize = (str) => `${str.charAt(0).toUpperCase()}${str.slice(1)}`;
const reverse = (str) => str.split('').reverse().join('');
const fn = pipe(lowercase, capitalize, reverse);
// We will execute `lowercase`, `capitalize` and `reverse` in order
fn('Hello World') === 'dlrow olleH';
```
================================================
FILE: contents/compose-functions.mdx
================================================
---
category: Function
created: '2020-05-07'
title: Compose functions
---
**JavaScript version**
```js compose.js
// Compose functions from right to left
const compose =
(...fns) =>
(x) =>
fns.reduceRight((y, f) => f(y), x);
```
**Examples**
```js examples.js
const lowercase = (str) => str.toLowerCase();
const capitalize = (str) => `${str.charAt(0).toUpperCase()}${str.slice(1)}`;
const reverse = (str) => str.split('').reverse().join('');
const fn = compose(reverse, capitalize, lowercase);
// We will execute `lowercase`, `capitalize` and `reverse` in order
fn('Hello World') === 'dlrow olleH';
```
================================================
FILE: contents/compute-the-greatest-common-divisor-between-two-numbers.mdx
================================================
---
category: Number
created: '2020-04-23'
title: Compute the greatest common divisor between two numbers
updated: '2021-10-13'
---
**JavaScript version**
```js gcd.js
const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));
```
**TypeScript version**
```ts gcd.ts
const gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));
```
**Examples**
```js examples.js
gcd(10, 15); // 5
```
================================================
FILE: contents/convert-3-digits-color-to-6-digits-color.mdx
================================================
---
category: Misc
created: '2021-02-20'
title: Convert 3 digits color to 6 digits color
updated: '2021-10-13'
---
**JavaScript version**
```js toFullHexColor.js
const toFullHexColor = (color) =>
`#${(color.startsWith('#') ? color.slice(1) : color)
.split('')
.map((c) => `${c}${c}`)
.join('')}`;
```
**TypeScript version**
```ts toFullHexColor.ts
const toFullHexColor = (color: string): string =>
`#${(color.startsWith('#') ? color.slice(1) : color)
.split('')
.map((c) => `${c}${c}`)
.join('')}`;
```
**Examples**
```js examples.js
toFullHexColor('123'); // '#112233'
toFullHexColor('#123'); // '#112233'
toFullHexColor('#abc'); // '#aabbcc'
```
================================================
FILE: contents/convert-a-base64-encoded-string-to-an-uint8-array.mdx
================================================
---
category: String
created: '2021-11-11'
title: Convert a base64 encoded string to an uint8 array
---
**JavaScript version**
```js base64ToUint8.js
const base64ToUint8 = (str) => Uint8Array.from(atob(str), (c) => c.charCodeAt(0));
```
**TypeScript version**
```ts base64ToUint8.ts
const base64ToUint8 = (str: string): Uint8Array => Uint8Array.from(atob(str), (c) => c.charCodeAt(0));
```
## See also
- [Convert an uint8 array to a base64 encoded string](https://phuoc.ng/collection/1-loc/convert-an-uint8-array-to-a-base64-encoded-string/)
================================================
FILE: contents/convert-a-date-to-yyyy-mm-dd-format.mdx
================================================
---
category: Date Time
contributors:
- ValchanOficial
created: '2020-04-19'
title: 'Convert a date to YYYY-MM-DD format'
updated: '2021-10-13'
---
**JavaScript version**
```js formatYmd.js
// `date` is a `Date` object
const formatYmd = (date) => date.toISOString().slice(0, 10);
```
**TypeScript version**
```ts formatYmd.ts
const formatYmd = (date: Date): string => date.toISOString().slice(0, 10);
```
**Example**
```js example.js
formatYmd(new Date()); // 2020-05-06
```
================================================
FILE: contents/convert-a-lab-color-to-an-lch-color.mdx
================================================
---
category: Misc
created: '2023-11-10'
openGraphCover: /og/1-loc/convert-lab-color-lch-color.png
title: Convert a LAB color to an LCH color
---
**JavaScript version**
```js labToLch.js
const labToLch = (l, a, b) => [
l,
Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2)),
Math.atan2(b, a) * 180 / Math.PI,
];
```
**TypeScript version**
```ts labToLch.ts
const labToLch = (l: number, a: number, b: number): number[] => [
l,
Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2)),
Math.atan2(b, a) * 180 / Math.PI,
];
```
## See also
- [Convert an LCH color to a LAB color](https://phuoc.ng/collection/1-loc/convert-an-lch-color-to-a-lab-color/)
================================================
FILE: contents/convert-a-letter-to-associate-emoji.mdx
================================================
---
category: String
created: '2020-08-02'
title: Convert a letter to associate emoji
updated: '2021-10-13'
---
**JavaScript version**
```js letterToEmoji.js
const letterToEmoji = (c) => String.fromCodePoint(c.toLowerCase().charCodeAt(0) + 127365);
```
**TypeScript version**
```ts letterToEmoji.ts
const letterToEmoji = (c: string): string => String.fromCodePoint(c.toLowerCase().charCodeAt(0) + 127365);
```
**Examples**
```js examples.js
letterToEmoji('a'); // 🇦
letterToEmoji('b'); // 🇧
```
================================================
FILE: contents/convert-a-number-to-equivalent-characters.mdx
================================================
---
category: Number
created: '2020-05-27'
title: Convert a number to equivalent characters
updated: '2021-10-13'
---
**JavaScript version**
```js toChars.js
const toChars = (n) => `${n >= 26 ? toChars(Math.floor(n / 26) - 1) : ''}${'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[n % 26]}`;
```
**TypeScript version**
```ts toChars.ts
const toChars = (n: number): string =>
`${n >= 26 ? toChars(Math.floor(n / 26) - 1) : ''}${'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[n % 26]}`;
```
**Examples**
```js examples.js
toChars(0); // A
toChars(1); // B
toChars(25); // Z
toChars(26); // AA
toChars(27); // AB
toChars(51); // AZ
toChars(701); // ZZ
toChars(702); // AAA
toChars(703); // AAB
```
================================================
FILE: contents/convert-a-string-to-camel-case.mdx
================================================
---
category: String
created: '2020-05-16'
title: Convert a string to camelCase
updated: '2021-10-13'
---
**JavaScript version**
```js toCamelCase.js
const toCamelCase = (str) => str.trim().replace(/[-_\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''));
```
**TypeScript version**
```ts toCamelCase.ts
const toCamelCase = (str: string): string => str.trim().replace(/[-_\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''));
```
**Examples**
```js examples.js
toCamelCase('background-color'); // backgroundColor
toCamelCase('-webkit-scrollbar-thumb'); // WebkitScrollbarThumb
toCamelCase('_hello_world'); // HelloWorld
toCamelCase('hello_world'); // helloWorld
```
================================================
FILE: contents/convert-a-string-to-number.mdx
================================================
---
category: Number
created: '2020-04-19'
title: Convert a string to number
updated: '2021-10-13'
---
**JavaScript version**
```js toNumber.js
const toNumber = (str) => +str;
```
**TypeScript version**
```ts toNumber.ts
const toNumber = (str: string): number => +str;
```
**Examples**
```js examples.js
toNumber('42'); // 42
```
================================================
FILE: contents/convert-a-string-to-pascal-case.mdx
================================================
---
category: String
created: '2020-05-15'
title: Convert a string to PascalCase
updated: '2021-10-13'
---
**JavaScript version**
```js toPascalCase.js
const toPascalCase = (str) =>
(str.match(/[a-zA-Z0-9]+/g) || []).map((w) => `${w.charAt(0).toUpperCase()}${w.slice(1)}`).join('');
```
**TypeScript version**
```ts toPascalCase.ts
const toPascalCase = (str: string): string =>
(str.match(/[a-zA-Z0-9]+/g) || []).map((w) => `${w.charAt(0).toUpperCase()}${w.slice(1)}`).join('');
```
**Examples**
```js examples.js
toPascalCase('hello world'); // 'HelloWorld'
toPascalCase('hello.world'); // 'HelloWorld'
toPascalCase('foo_bar-baz'); // FooBarBaz
```
================================================
FILE: contents/convert-a-string-to-url-slug.mdx
================================================
---
category: String
created: '2020-05-04'
title: Convert a string to URL slug
updated: '2021-10-13'
---
**JavaScript version**
```js slugify.js
const slugify = (str) =>
str
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/[^\w-]+/g, '');
```
**TypeScript version**
```ts slugify.ts
const slugify = (str: string): string =>
str
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/[^\w-]+/g, '');
```
**Examples**
```js examples.js
slugify('Chapter One: Once upon a time...'); // 'chapter-one-once-upon-a-time'
```
================================================
FILE: contents/convert-a-windows-file-path-to-unix-path.mdx
================================================
---
category: String
created: '2020-05-15'
title: Convert a Windows file path to Unix path
updated: '2021-10-13'
---
**JavaScript version**
```js toUnixPath.js
const toUnixPath = (path) => path.replace(/[\\/]+/g, '/').replace(/^([a-zA-Z]+:|\.\/)/, '');
```
**TypeScript version**
```ts toUnixPath.ts
const toUnixPath = (path: string): string => path.replace(/[\\/]+/g, '/').replace(/^([a-zA-Z]+:|\.\/)/, '');
```
**Examples**
```js examples.js
toUnixPath('./foo/bar/baz'); // foo/bar/baz
toUnixPath('C:\\foo\\bar\\baz'); // /foo/bar/baz
```
================================================
FILE: contents/convert-an-array-of-objects-to-a-single-object.mdx
================================================
---
category: Array
contributors:
- ChoukseyKhushbu
- wenyangliu
created: '2020-05-04'
title: Convert an array of objects to a single object
updated: '2021-10-13'
---
**JavaScript version**
```js toObject.js
const toObject = (arr, key) => arr.reduce((a, b) => ({ ...a, [b[key]]: b }), {});
// Or
const toObject = (arr, key) => Object.fromEntries(arr.map((it) => [it[key], it]));
```
**TypeScript version**
```ts toObject.ts
const toObject = <T extends Record<string, any>, K extends keyof T>(arr: T[], key: K): Record<string, T> => (
arr.reduce((a, b) => ({ ...a, [b[key]]: b }), {})
);
const toObject = <T extends Record<string, any>, K extends keyof T>(arr: T[], key: K): Record<string, T> => (
Object.fromEntries(arr.map((it) => [it[key], it]))
);
```
**Example**
```js example.js
toObject(
[
{ id: '1', name: 'Alpha', gender: 'Male' },
{ id: '2', name: 'Bravo', gender: 'Male' },
{ id: '3', name: 'Charlie', gender: 'Female' },
],
'id'
);
/*
{
'1': { id: '1', name: 'Alpha', gender: 'Male' },
'2': { id: '2', name: 'Bravo', gender: 'Male' },
'3': { id: '3', name: 'Charlie', gender: 'Female' },
}
*/
```
================================================
FILE: contents/convert-an-array-of-strings-to-numbers.mdx
================================================
---
category: Array
contributors:
- jonrandy
created: '2020-04-23'
title: Convert an array of strings to numbers
updated: '2021-10-13'
---
**JavaScript version**
```js toNumbers.js
const toNumbers = (arr) => arr.map(Number);
// Or
const toNumbers = (arr) => arr.map((x) => +x);
```
**TypeScript version**
```ts toNumbers.ts
const toNumbers = (arr: string[]): number[] => arr.map(Number);
// Or
const toNumbers = (arr: string[]): number[] => arr.map((x) => +x);
```
**Example**
```js example.js
toNumbers(['2', '3', '4']); // [2, 3, 4]
```
================================================
FILE: contents/convert-an-lch-color-to-a-lab-color.mdx
================================================
---
category: Misc
created: '2023-11-10'
openGraphCover: /og/1-loc/convert-lch-color-lab-color.png
title: Convert an LCH color to a LAB color
---
**JavaScript version**
```js lchToLab.js
const lchToLab = (l, c, h) => [
l,
Math.cos(h * Math.PI / 180) * c,
Math.sin(h * Math.PI / 180) * c,
];
```
**TypeScript version**
```ts lchToLab.ts
const lchToLab = (l: number, c: number, h: number): number[] => [
l,
Math.cos(h * Math.PI / 180) * c,
Math.sin(h * Math.PI / 180) * c,
];
```
## See also
- [Convert a LAB color to an LCH color](https://phuoc.ng/collection/1-loc/convert-a-lab-color-to-an-lch-color/)
================================================
FILE: contents/convert-an-uint8-array-to-a-base64-encoded-string.mdx
================================================
---
category: String
created: '2021-11-11'
title: Convert an uint8 array to a base64 encoded string
---
**JavaScript version**
```js uint8ToBase64.js
const uint8ToBase64 = (arr) =>
btoa(
Array(arr.length)
.fill('')
.map((_, i) => String.fromCharCode(arr[i]))
.join('')
);
// For Node.js
const uint8ToBase64 = (arr) => Buffer.from(arr).toString('base64');
```
**TypeScript version**
```ts uint8ToBase64.ts
const uint8ToBase64 = (arr: Uint8Array): string =>
btoa(
Array(arr.length)
.fill('')
.map((_, i) => String.fromCharCode(arr[i]))
.join('')
);
// For Node.js
const uint8ToBase64 = (arr: Uint8Array): string => Buffer.from(arr).toString('base64');
```
## See also
- [Convert a base64 encoded string to an uint8 array](https://phuoc.ng/collection/1-loc/convert-a-base64-encoded-string-to-an-uint8-array/)
================================================
FILE: contents/convert-camel-case-to-kebab-case-and-vice-versa.mdx
================================================
---
category: String
created: '2020-05-12'
title: 'Convert camelCase to kebab-case and vice versa'
updated: '2021-10-13'
---
**JavaScript version**
```js kebabToCamel.js
const kebabToCamel = (str) => str.replace(/-./g, (m) => m.toUpperCase()[1]);
const camelToKebab = (str) => str.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
```
**TypeScript version**
```ts kebabToCamel.ts
const kebabToCamel = (str: string): string => str.replace(/-./g, (m) => m.toUpperCase()[1]);
const camelToKebab = (str: string): string => str.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
```
**Examples**
```js examples.js
kebabToCamel('background-color'); // 'backgroundColor'
camelToKebab('backgroundColor'); // 'background-color'
```
================================================
FILE: contents/convert-celsius-to-fahrenheit.mdx
================================================
---
category: Misc
contributors:
- mizanmahi
created: '2020-05-09'
title: Convert Celsius to Fahrenheit
updated: '2021-10-13'
---
**JavaScript version**
```js celsiusToFahrenheit.js
const celsiusToFahrenheit = (celsius) => (celsius * 9) / 5 + 32;
```
**TypeScript version**
```ts celsiusToFahrenheit.ts
const celsiusToFahrenheit = (celsius: number): number => (celsius * 9) / 5 + 32;
```
**Examples**
```js examples.js
celsiusToFahrenheit(15); // 59
celsiusToFahrenheit(0); // 32
celsiusToFahrenheit(-20); // -4
```
================================================
FILE: contents/convert-cookie-to-object.mdx
================================================
---
category: Misc
contributors:
- João Luís Ribeiro Augusto
created: '2020-06-27'
title: Convert cookie to object
---
**JavaScript version**
```js cookies.js
const cookies = document.cookie
.split(';')
.map((item) => item.split('='))
.reduce((acc, [k, v]) => (acc[k.trim().replace('"', '')] = v) && acc, {});
```
================================================
FILE: contents/convert-decimal-to-binary-recursively.mdx
================================================
---
category: Number
contributors:
- philosophercode
created: '2020-12-11'
title: Convert decimal to binary recursively
updated: '2021-10-13'
---
**JavaScript version**
```js decToBi.js
const decToBi = (num) => (num === 0 ? 0 : (num % 2) + 10 * decToBi(~~(num / 2)));
```
**TypeScript version**
```ts decToBi.ts
const decToBi = (num: number): number => (num === 0 ? 0 : (num % 2) + 10 * decToBi(~~(num / 2)));
```
**Examples**
```js examples.js
decToBi(10); //1010
```
================================================
FILE: contents/convert-degrees-to-radians.mdx
================================================
---
category: Math
created: '2020-05-16'
title: Convert degrees to radians
updated: '2021-10-13'
---
**JavaScript version**
```js degsToRads.js
const degsToRads = (deg) => (deg * Math.PI) / 180.0;
```
**TypeScript version**
```ts degsToRads.ts
const degsToRads = (deg: number): number => (deg * Math.PI) / 180.0;
```
================================================
FILE: contents/convert-fahrenheit-to-celsius.mdx
================================================
---
category: Misc
created: '2021-04-08'
title: Convert Fahrenheit to Celsius
updated: '2021-10-13'
---
**JavaScript version**
```js fahrenheitToCelsius.js
const fahrenheitToCelsius = (fahrenheit) => ((fahrenheit - 32) * 5) / 9;
```
**TypeScript version**
```ts fahrenheitToCelsius.ts
const fahrenheitToCelsius = (fahrenheit: number): number => ((fahrenheit - 32) * 5) / 9;
```
**Examples**
```js examples.js
fahrenheitToCelsius(59); // 15
fahrenheitToCelsius(32); // 0
```
================================================
FILE: contents/convert-hex-to-rgb.mdx
================================================
---
category: Misc
created: '2020-04-19'
title: Convert hex to rgb
updated: '2021-10-13'
---
**JavaScript version**
```js hexToRgb.js
const hexToRgb = (hex) =>
hex
.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i, (_, r, g, b) => `#${r}${r}${g}${g}${b}${b}`)
.substring(1)
.match(/.{2}/g)
.map((x) => parseInt(x, 16));
```
**TypeScript version**
```ts hexToRgb.ts
const hexToRgb = (hex: string): string =>
hex
.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i, (_, r, g, b) => `#${r}${r}${g}${g}${b}${b}`)
.substring(1)
.match(/.{2}/g)
.map((x) => parseInt(x, 16));
```
**Examples**
```js examples.js
hexToRgb('#00ffff'); // [0, 255, 255]
hexToRgb('#0ff'); // [0, 255, 255]
```
## See also
- [Convert rgb color to hex](https://phuoc.ng/collection/1-loc/convert-rgb-color-to-hex/)
- [Create an RGB to HEX color converter](https://phuoc.ng/collection/react-drag-drop/create-an-rgb-to-hex-color-converter/)
================================================
FILE: contents/convert-radians-to-degrees.mdx
================================================
---
category: Math
created: '2021-04-05'
title: Convert radians to degrees
updated: '2021-10-13'
---
**JavaScript version**
```js radsToDegs.js
const radsToDegs = (rad) => (rad * 180) / Math.PI;
```
**TypeScript version**
```ts radsToDegs.ts
const radsToDegs = (rad: number): number => (rad * 180) / Math.PI;
```
================================================
FILE: contents/convert-rgb-color-to-hex.mdx
================================================
---
category: Misc
created: '2020-04-19'
title: Convert rgb color to hex
updated: '2021-10-13'
---
**JavaScript version**
```js rgbToHex.js
const rgbToHex = (red, green, blue) => `#${((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1)}`;
// Or
const rgbToHex = (red, green, blue) => `#${[red, green, blue].map((v) => v.toString(16).padStart(2, '0')).join('')}`;
```
**TypeScript version**
```ts rgbToHex.ts
const rgbToHex = (red: number, green: number, blue: number): string =>
`#${((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1)}`;
// Or
const rgbToHex = (red: number, green: number, blue: number): string =>
`#${[red, green, blue].map((v) => v.toString(16).padStart(2, '0')).join('')}`;
```
**Examples**
```js examples.js
rgbToHex(0, 255, 255); // '#00ffff'
```
## See also
- [Convert hex to rgb](https://phuoc.ng/collection/1-loc/convert-hex-to-rgb/)
- [Create an RGB to HEX color converter](https://phuoc.ng/collection/react-drag-drop/create-an-rgb-to-hex-color-converter/)
================================================
FILE: contents/convert-seconds-to-hh-mm-ss-format.mdx
================================================
---
category: Date Time
created: '2020-05-15'
title: 'Convert seconds to hh:mm:ss format'
updated: '2021-10-13'
---
**JavaScript version**
```js formatSeconds.js
// `s` is number of seconds
const formatSeconds = (s) => new Date(s * 1000).toISOString().substr(11, 8);
// Or
const formatSeconds = (s) => new Date(s * 1000).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
// Or
const formatSeconds = (s) =>
[parseInt(s / 60 / 60), parseInt((s / 60) % 60), parseInt(s % 60)].join(':').replace(/\b(\d)\b/g, '0$1');
```
**TypeScript version**
```ts formatSeconds.ts
const formatSeconds = (s: number): string => new Date(s * 1000).toISOString().substr(11, 8);
// Or
const formatSeconds = (s: number): string => (new Date(s * 1000).toUTCString().match(/(\d\d:\d\d:\d\d)/) as string[])[0];
// Or
const formatSeconds = (s: number): string => (
[parseInt(`${s / 3600}`), parseInt(`${(s / 60) % 60}`), parseInt(`${s % 60}`)].join(':').replace(/\b(\d)\b/g, '0$1')
);
```
**Examples**
```js examples.js
formatSeconds(200); // 00:03:20
formatSeconds(500); // 00:08:20
```
================================================
FILE: contents/convert-snake-case-to-camel-case.mdx
================================================
---
category: String
created: '2020-05-12'
title: 'Convert snake_case to camelCase'
updated: '2021-10-13'
---
**JavaScript version**
```js snakeToCamel.js
const snakeToCamel = (str) => str.toLowerCase().replace(/(_\w)/g, (m) => m.toUpperCase().substr(1));
```
**TypeScript version**
```ts snakeToCamel.ts
const snakeToCamel = (str: string): string => str.toLowerCase().replace(/(_\w)/g, (m) => m.toUpperCase().substr(1));
```
**Examples**
```js examples.js
snakeToCamel('HELLO_world'); // 'helloWorld'
```
================================================
FILE: contents/convert-the-name-of-an-excel-column-to-number.mdx
================================================
---
category: String
created: '2020-05-25'
title: Convert the name of an Excel column to number
updated: '2021-10-13'
---
**JavaScript version**
```js getIndex.js
const getIndex = (col) => col.split('').reduce((prev, next) => prev * 26 + parseInt(next, 36) - 9, 0);
```
**TypeScript version**
```ts getIndex.ts
const getIndex = (col: string): number => col.split('').reduce((prev, next) => prev * 26 + parseInt(next, 36) - 9, 0);
```
**Examples**
```js examples.js
getIndex('A'); // 1
getIndex('B'); // 2
getIndex('C'); // 3
getIndex('Z'); // 26
getIndex('AA'); // 27
getIndex('AB'); // 28
getIndex('AC'); // 29
getIndex('AZ'); // 52
getIndex('AAA'); // 703
getIndex('AAB'); // 704
```
================================================
FILE: contents/convert-url-parameters-to-object.mdx
================================================
---
category: Misc
created: '2021-02-01'
title: Convert URL parameters to object
updated: '2021-10-13'
---
**JavaScript version**
```js getUrlParams.js
const getUrlParams = (query) =>
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 }),
{}
);
```
**TypeScript version**
```ts getUrlParams.ts
const getUrlParams = (query: string): Record<string, string> => (
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>)
);
```
**Examples**
```js examples.js
getUrlParams(location.search); // Get the parameters of the current URL
getUrlParams('foo=Foo&bar=Bar'); // { foo: "Foo", bar: "Bar" }
// Duplicate key
getUrlParams('foo=Foo&foo=Fuzz&bar=Bar'); // { foo: ["Foo", "Fuzz"], bar: "Bar" }
```
================================================
FILE: contents/count-by-the-properties-of-an-array-of-objects.mdx
================================================
---
category: Array
created: '2020-06-14'
title: Count by the properties of an array of objects
updated: '2021-10-13'
---
**JavaScript version**
```js countBy.js
const countBy = (arr, prop) => arr.reduce((prev, curr) => ((prev[curr[prop]] = ++prev[curr[prop]] || 1), prev), {});
```
**TypeScript version**
```ts countBy.ts
const countBy = <T extends Record<string, string>, K extends keyof T>(arr: T[], prop: K): Record<string, number> => (
arr.reduce((prev, curr) => ((prev[curr[prop]] = ++prev[curr[prop]] || 1), prev), {} as Record<string, number>)
);
```
**Example**
```js example.js
countBy(
[
{ branch: 'audi', model: 'q8', year: '2019' },
{ branch: 'audi', model: 'rs7', year: '2020' },
{ branch: 'ford', model: 'mustang', year: '2019' },
{ branch: 'ford', model: 'explorer', year: '2020' },
{ branch: 'bmw', model: 'x7', year: '2020' },
],
'branch'
);
// { 'audi': 2, 'ford': 2, 'bmw': 1 }
```
================================================
FILE: contents/count-the-number-of-words-in-a-string.mdx
================================================
---
category: String
created: '2021-05-26'
title: Count the number of words in a string
updated: '2021-10-13'
---
**JavaScript version**
```js countWords.js
const countWords = (str) => str.trim().split(/\s+/).length;
```
**TypeScript version**
```ts countWords.ts
const countWords = (str: string): number => str.trim().split(/\s+/).length;
```
**Examples**
```js examples.js
countWords('Hello World'); // 2
countWords('Hello World'); // 2
countWords(' Hello World '); // 2
```
================================================
FILE: contents/count-the-occurrences-of-a-character-in-a-string.mdx
================================================
---
category: String
created: '2021-04-19'
title: Count the occurrences of a character in a string
updated: '2021-10-13'
---
**JavaScript version**
```js countOccurrences.js
const countOccurrences = (str, char) => [...str].reduce((a, v) => (v === char ? a + 1 : a), 0);
// Or
const countOccurrences = (str, char) => str.split('').reduce((a, v) => (v === char ? a + 1 : a), 0);
// Or
const countOccurrences = (str, char) => [...str].filter((item) => item === char).length;
// Or
const countOccurrences = (str, char) => str.split('').filter((item) => item === char).length;
```
**TypeScript version**
```ts countOccurrences.ts
const countOccurrences = (str: string, char: string): number => [...str].reduce((a, v) => (v === char ? a + 1 : a), 0);
// Or
const countOccurrences = (str: string, char: string): number =>
str.split('').reduce((a, v) => (v === char ? a + 1 : a), 0);
// Or
const countOccurrences = (str: string, char: string): number => [...str].filter((item) => item === char).length;
// Or
const countOccurrences = (str: string, char: string): number => str.split('').filter((item) => item === char).length;
```
**Examples**
```js examples.js
countOccurrences('a.b.c.d.e', '.'); // 4
```
================================================
FILE: contents/count-the-occurrences-of-a-value-in-an-array.mdx
================================================
---
category: Array
created: '2020-06-11'
title: Count the occurrences of a value in an array
updated: '2021-10-22'
---
**JavaScript version**
```js countOccurrences.js
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
// Or
const countOccurrences = (arr, val) => arr.filter((item) => item === val).length;
```
**TypeScript version**
```ts countOccurrences.ts
const countOccurrences = <T,_>(arr: T[], val: T): number => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
// Or
const countOccurrences = <T,_>(arr: T[], val: T): number => arr.filter((item) => item === val).length;
```
**Examples**
```js examples.js
countOccurrences([2, 1, 3, 3, 2, 3], 2); // 2
countOccurrences(['a', 'b', 'a', 'c', 'a', 'b'], 'a'); // 3
```
================================================
FILE: contents/count-the-occurrences-of-array-elements.mdx
================================================
---
category: Array
created: '2020-06-11'
title: Count the occurrences of array elements
updated: '2021-10-13'
---
**JavaScript version**
```js countOccurrences.js
const countOccurrences = (arr) => arr.reduce((prev, curr) => ((prev[curr] = ++prev[curr] || 1), prev), {});
```
**TypeScript version**
```ts countOccurrences.ts
const countOccurrences = <T extends string | number,>(arr: T[]): Record<T, number> => (
arr.reduce((prev, curr) => ((prev[curr] = ++prev[curr] || 1), prev), {}as Record<T, number>)
);
```
**Examples**
```js examples.js
countOccurrences([2, 1, 3, 3, 2, 3]); // { '1': 1, '2': 2, '3': 3 }
countOccurrences(['a', 'b', 'a', 'c', 'a', 'b']); // { 'a': 3, 'b': 2, 'c': 1 }
```
================================================
FILE: contents/create-a-function-that-accepts-a-single-argument.mdx
================================================
---
category: Function
created: '2021-03-13'
title: Create a function that accepts a single argument
---
**JavaScript version**
```js unary.js
const unary = (fn) => (arg) => fn(arg);
```
**Examples**
```js examples.js
['1', '2', '3', '4', '5'].map(unary(parseInt)); // [1, 2, 3, 4, 5]
```
================================================
FILE: contents/create-an-array-of-cumulative-sum.mdx
================================================
---
category: Array
created: '2020-04-19'
title: Create an array of cumulative sum
updated: '2021-10-13'
---
**JavaScript version**
```js accumulate.js
const accumulate = (arr) =>
arr.map(
(
(sum) => (value) =>
(sum += value)
)(0)
);
// Or
const accumulate = (arr) => arr.reduce((a, b, i) => (i === 0 ? [b] : [...a, b + a[i - 1]]), [0]);
```
**TypeScript version**
```ts accumulate.ts
const accumulate = (arr: number[]): number[] =>
arr.map(
(
(sum) => (value: number) =>
(sum += value)
)(0)
);
// Or
const accumulate = (arr: number[]): number[] => arr.reduce((a, b, i) => (i === 0 ? [b] : [...a, b + a[i - 1]]), [0]);
```
**Example**
```js example.js
accumulate([1, 2, 3, 4]); // [1, 3, 6, 10]
// 1 = 1
// 1 + 2 = 3
// 1 + 2 + 3 = 6
// 1 + 2 + 3 + 4 = 10
```
================================================
FILE: contents/create-an-array-of-numbers-in-the-given-range.mdx
================================================
---
category: Array
contributors:
- jonrandy
- Augusto Moura
- Tsvika10
created: '2020-04-19'
title: Create an array of numbers in the given range
updated: '2021-10-13'
---
**JavaScript version**
```js range.js
const range = (min, max) => [...Array(max - min + 1).keys()].map((i) => i + min);
// Or
const range = (min, max) =>
Array(max - min + 1)
.fill(0)
.map((_, i) => min + i);
// Or
const range = (min, max) => Array.from({ length: max - min + 1 }, (_, i) => min + i);
```
**TypeScript version**
```ts range.ts
const range = (min: number, max: number): number[] => [...Array(max - min + 1).keys()].map((i) => i + min);
// Or
const range = (min: number, max: number): number[] =>
Array(max - min + 1)
.fill(0)
.map((_, i) => min + i);
// Or
const range = (min: number, max: number): number[] => Array.from({ length: max - min + 1 }, (_, i) => min + i);
```
**Example**
```js example.js
range(5, 10); // [5, 6, 7, 8, 9, 10]
```
================================================
FILE: contents/create-an-empty-function.mdx
================================================
---
category: Function
contributors:
- jnields
- naugtur
created: '2020-05-07'
title: Create an empty function
updated: '2020-05-27'
---
**JavaScript version**
```js noop.js
const noop = () => {};
// Or
const noop = Function();
// calling Function() might be detected as using eval by some security tools
```
================================================
FILE: contents/create-an-empty-map-that-does-not-have-properties.mdx
================================================
---
category: Object
created: '2020-04-19'
title: Create an empty map that does not have properties
---
**JavaScript version**
```js map.js
// `map` doesn't have any properties
const map = Object.create(null);
// The following `map` has `__proto__` property
// const map = {};
```
================================================
FILE: contents/create-an-object-from-the-pairs-of-key-and-value.mdx
================================================
---
category: Object
contributors:
- robinpokorny
created: '2020-05-18'
title: Create an object from the pairs of key and value
updated: '2020-05-20'
---
**JavaScript version**
```js toObj.js
const toObj = (arr) => Object.fromEntries(arr);
// Or
const toObj = (arr) => arr.reduce((a, c) => ((a[c[0]] = c[1]), a), {});
```
**Examples**
```js examples.js
toObj([
['a', 1],
['b', 2],
['c', 3],
]); // { a: 1, b: 2, c: 3 }
```
================================================
FILE: contents/create-cartesian-product.mdx
================================================
---
category: Array
contributors:
- robinpokorny
created: '2020-12-02'
title: Create cartesian product
updated: '2021-10-13'
---
**JavaScript version**
```js cartesian.js
const cartesian = (...sets) => sets.reduce((acc, set) => acc.flatMap((x) => set.map((y) => [...x, y])), [[]]);
```
**Example**
```js example.js
cartesian([1, 2], [3, 4]); // [ [1, 3], [1, 4], [2, 3], [2, 4] ]
/*
3 4
---------------
1 | [1, 3] [1, 4]
|
2 | [2, 3] [2, 4]
*/
```
================================================
FILE: contents/curry-a-function.mdx
================================================
---
category: Function
created: '2020-05-15'
title: Curry a function
---
**JavaScript version**
```js curry.js
const curry = (fn, ...args) => (fn.length <= args.length ? fn(...args) : curry.bind(null, fn, ...args));
```
**Examples**
```js examples.js
const sum = (a, b, c) => a + b + c;
curry(sum)(1)(2)(3); // 6
curry(sum)(1, 2, 3); // 6
curry(sum, 1)(2, 3); // 6
curry(sum, 1)(2)(3); // 6
curry(sum, 1, 2)(3); // 6
curry(sum, 1, 2, 3); // 6
```
================================================
FILE: contents/decapitalize-a-string.mdx
================================================
---
category: String
created: '2021-02-21'
title: Decapitalize a string
updated: '2021-10-13'
---
**JavaScript version**
```js decapitalize.js
const decapitalize = (str) => `${str.charAt(0).toLowerCase()}${str.slice(1)}`;
// Or
const decapitalize = ([first, ...rest]) => `${first.toLowerCase()}${rest.join('')}`;
```
**TypeScript version**
```ts decapitalize.ts
const decapitalize = (str: string): string => `${str.charAt(0).toLowerCase()}${str.slice(1)}`;
// Or
const decapitalize = ([first, ...rest]: string): string => `${first.toLowerCase()}${rest.join('')}`;
```
**Examples**
```js examples.js
decapitalize('Hello world'); // 'hello world'
```
================================================
FILE: contents/decode-a-jwt-token.mdx
================================================
---
category: Misc
created: '2020-05-23'
title: Decode a JWT token
updated: '2021-10-13'
---
**JavaScript version**
```js decode.js
const decode = (token) =>
decodeURIComponent(
atob(token.split('.')[1].replace('-', '+').replace('_', '/'))
.split('')
.map((c) => `%${('00' + c.charCodeAt(0).toString(16)).slice(-2)}`)
.join('')
);
```
**TypeScript version**
```ts decode.ts
const decode = (token: string): string =>
decodeURIComponent(
atob(token.split('.')[1].replace('-', '+').replace('_', '/'))
.split('')
.map((c) => `%${('00' + c.charCodeAt(0).toString(16)).slice(-2)}`)
.join('')
);
```
**Examples**
```js examples.js
decode(`
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0I
joxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
`);
// { "sub": "1234567890", "name": "John Doe", "iat": 1516239022 }
```
================================================
FILE: contents/decode-html-entities.mdx
================================================
---
category: String
created: '2022-08-21'
title: Decode HTML entities
---
**JavaScript version**
```js decodeHtmlEntities.js
const decodeHtmlEntities = (str) => str.replace(/&#(\w+)(^\w|;)?/g, (_, dec) => String.fromCharCode(dec));
```
**TypeScript version**
```ts decodeHtmlEntities.ts
const decodeHtmlEntities = (str: string): string =>
str.replace(/&#(\w+)(^\w|;)?/g, (_, dec) => String.fromCharCode(dec));
```
================================================
FILE: contents/delay-the-evaluation-of-a-function.mdx
================================================
---
category: Function
created: '2020-05-12'
title: Delay the evaluation of a function
---
**JavaScript version**
```js thunkfy.js
// returns a new version of `fn` that returns values as lazy evaluable
const thunkfy =
(fn) =>
(...args) =>
() =>
fn(...args);
```
**Examples**
```js examples.js
const heavyComputation = (x) => doStuff(x);
const unnecessarySlow = manyThings.map(heavyComputation).find((result) => result.criteria);
const probablyFaster = manyThings.map(thunkfy(heavyComputation)).find((thunk) => thunk().criteria);
```
================================================
FILE: contents/detect-dark-mode.mdx
================================================
---
category: Misc
created: '2020-05-02'
title: Detect dark mode
updated: '2021-10-13'
---
**JavaScript version**
```js isDarkMode.js
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
```
**TypeScript version**
```ts isDarkMode.ts
const isDarkMode: boolean = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
```
================================================
FILE: contents/detect-internet-explorer-browser.mdx
================================================
---
category: DOM
created: '2020-05-09'
title: Detect Internet Explorer browser
updated: '2021-10-13'
---
**JavaScript version**
```js isIE.js
const isIE = !!document.documentMode;
```
**TypeScript version**
```ts isIE.ts
const isIE = !!(document as any).documentMode;
```
================================================
FILE: contents/detect-macos-browser.mdx
================================================
---
category: DOM
created: '2020-04-19'
title: Detect macOS browser
updated: '2021-10-13'
---
**JavaScript version**
```js isMacBrowser.js
const isMacBrowser = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
```
**TypeScript version**
```ts isMacBrowser.ts
const isMacBrowser: boolean = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
```
================================================
FILE: contents/determine-one-year-from-now.mdx
================================================
---
category: Date Time
created: '2022-08-21'
title: Determine one year from now
---
**JavaScript version**
```js plusOneYear.js
const plusOneYear = ((d) => new Date(d.setFullYear(d.getFullYear() + 1)))(new Date());
```
**TypeScript version**
```ts plusOneYear.ts
const plusOneYear: Date = ((d) => new Date(d.setFullYear(d.getFullYear() + 1)))(new Date());
```
## See also
- [Get the tomorrow date](https://phuoc.ng/collection/1-loc/get-the-tomorrow-date/)
- [Get the yesterday date](https://phuoc.ng/collection/1-loc/get-the-yesterday-date/)
================================================
FILE: contents/easing-functions.mdx
================================================
---
category: Misc
created: '2020-04-25'
title: Easing functions
updated: '2021-10-13'
---
**JavaScript version**
```js
// Some easing functions
// See https://gist.github.com/gre/1650294 and https://easings.net
const linear = (t) => t;
const easeInQuad = (t) => t * t;
const easeOutQuad = (t) => t * (2 - t);
const easeInOutQuad = (t) => (t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t);
const easeInCubic = (t) => t * t * t;
const easeOutCubic = (t) => --t * t * t + 1;
const easeInOutCubic = (t) => (t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1);
const easeInQuart = (t) => t * t * t * t;
const easeOutQuart = (t) => 1 - --t * t * t * t;
const easeInOutQuart = (t) => (t < 0.5 ? 8 * t * t * t * t : 1 - 8 * --t * t * t * t);
const easeInQuint = (t) => t * t * t * t * t;
const easeOutQuint = (t) => 1 + --t * t * t * t * t;
const easeInOutQuint = (t) => (t < 0.5 ? 16 * t * t * t * t * t : 1 + 16 * --t * t * t * t * t);
const easeInSine = (t) => 1 + Math.sin((Math.PI / 2) * t - Math.PI / 2);
const easeOutSine = (t) => Math.sin((Math.PI / 2) * t);
const easeInOutSine = (t) => (1 + Math.sin(Math.PI * t - Math.PI / 2)) / 2;
const easeInElastic = (t) => (0.04 - 0.04 / t) * Math.sin(25 * t) + 1;
const easeOutElastic = (t) => ((0.04 * t) / --t) * Math.sin(25 * t);
const easeInOutElastic = (t) =>
(t -= 0.5) < 0 ? (0.02 + 0.01 / t) * Math.sin(50 * t) : (0.02 - 0.01 / t) * Math.sin(50 * t) + 1;
```
**TypeScript version**
```ts linear.ts
const linear = (t: number): number => t;
const easeInQuad = (t: number): number => t * t;
const easeOutQuad = (t: number): number => t * (2 - t);
const easeInOutQuad = (t: number): number => (t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t);
const easeInCubic = (t: number): number => t * t * t;
const easeOutCubic = (t: number): number => --t * t * t + 1;
const easeInOutCubic = (t: number): number => (t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1);
const easeInQuart = (t: number): number => t * t * t * t;
const easeOutQuart = (t: number): number => 1 - --t * t * t * t;
const easeInOutQuart = (t: number): number => (t < 0.5 ? 8 * t * t * t * t : 1 - 8 * --t * t * t * t);
const easeInQuint = (t: number): number => t * t * t * t * t;
const easeOutQuint = (t: number): number => 1 + --t * t * t * t * t;
const easeInOutQuint = (t: number): number => (t < 0.5 ? 16 * t * t * t * t * t : 1 + 16 * --t * t * t * t * t);
const easeInSine = (t: number): number => 1 + Math.sin((Math.PI / 2) * t - Math.PI / 2);
const easeOutSine = (t: number): number => Math.sin((Math.PI / 2) * t);
const easeInOutSine = (t: number): number => (1 + Math.sin(Math.PI * t - Math.PI / 2)) / 2;
const easeInElastic = (t: number): number => (0.04 - 0.04 / t) * Math.sin(25 * t) + 1;
const easeOutElastic = (t: number): number => ((0.04 * t) / --t) * Math.sin(25 * t);
const easeInOutElastic = (t: number): number =>
(t -= 0.5) < 0 ? (0.02 + 0.01 / t) * Math.sin(50 * t) : (0.02 - 0.01 / t) * Math.sin(50 * t) + 1;
```
================================================
FILE: contents/empty-an-array.mdx
================================================
---
category: Array
created: '2020-04-19'
title: Empty an array
updated: '2021-10-22'
---
**JavaScript version**
```js empty.js
const empty = (arr) => (arr.length = 0);
// Or
arr = [];
```
**TypeScript version**
```ts empty.ts
const empty = <T,_>(arr: T[]) => (arr.length = 0);
// Or
arr = [];
```
================================================
FILE: contents/emulate-a-dice-throw.mdx
================================================
---
category: Misc
contributors:
- codepo8
created: '2020-05-01'
title: Emulate a dice throw
updated: '2021-10-13'
---
**JavaScript version**
```js throwdice.js
const throwdice = () => ~~(Math.random() * 6) + 1;
```
**TypeScript version**
```ts throwdice.ts
const throwdice = (): number => ~~(Math.random() * 6) + 1;
```
**Examples**
```js examples.js
throwdice(); // 4
throwdice(); // 1
throwdice(); // 6
```
================================================
FILE: contents/encode-a-url.mdx
================================================
---
category: Misc
created: '2020-05-03'
title: Encode a URL
updated: '2021-10-13'
---
**JavaScript version**
```js encode.js
// `encodeURIComponent` doesn't encode -_.!~*'()
const encode = (url) =>
encodeURIComponent(url)
.replace(/!/g, '%21')
.replace(/~/g, '%7E')
.replace(/\*/g, '%2A')
.replace(/'/g, '%27')
.replace(/\(/g, '%28')
.replace(/\)/g, '%29')
.replace(/%20/g, '+');
```
**TypeScript version**
```ts encode.ts
const encode = (url: string): string =>
encodeURIComponent(url)
.replace(/!/g, '%21')
.replace(/~/g, '%7E')
.replace(/\*/g, '%2A')
.replace(/'/g, '%27')
.replace(/\(/g, '%28')
.replace(/\)/g, '%29')
.replace(/%20/g, '+');
```
================================================
FILE: contents/escape-html-special-characters.mdx
================================================
---
category: String
created: '2020-05-29'
title: Escape HTML special characters
updated: '2021-10-13'
---
**JavaScript version**
```js escape.js
const escape = (str) =>
str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/'/g, ''')
.replace(/"/g, '"');
// Or
const escape = (str) =>
str.replace(/[&<>"']/g, (m) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[m]));
```
**TypeScript version**
```ts escape.ts
const escape = (str: string): string =>
str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/'/g, ''')
.replace(/"/g, '"');
// Or
const escape = (str: string): string =>
str.replace(/[&<>"']/g, (m) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[m]));
```
================================================
FILE: contents/execute-a-function-once.mdx
================================================
---
category: Function
created: '2020-05-13'
title: Execute a function once
---
**JavaScript version**
```js once.js
const once = (fn) =>
(
(ran = false) =>
() =>
ran ? fn : ((ran = !ran), (fn = fn()))
)();
```
**Examples**
```js examples.js
let n = 0;
const incOnce = once(() => ++n);
incOnce(); // n = 1
incOnce(); // n = 1
incOnce(); // n = 1
```
================================================
FILE: contents/extract-values-of-a-property-from-an-array-of-objects.mdx
================================================
---
category: Object
created: '2020-06-02'
title: Extract values of a property from an array of objects
---
**JavaScript version**
```js pluck.js
const pluck = (objs, property) => objs.map((obj) => obj[property]);
```
**Examples**
```js examples.js
pluck(
[
{ name: 'John', age: 20 },
{ name: 'Smith', age: 25 },
{ name: 'Peter', age: 30 },
],
'name'
); // ['John', 'Smith', 'Peter']
```
================================================
FILE: contents/extract-year-month-day-hour-minute-second-and-millisecond-from-a-date.mdx
================================================
---
category: Date Time
created: '2020-04-19'
title: 'Extract year, month, day, hour, minute, second and millisecond from a date'
updated: '2021-10-13'
---
**JavaScript version**
```js extract.js
// `date` is a `Date` object
const extract = (date) =>
date
.toISOString()
.split(/[^0-9]/)
.slice(0, -1);
// `extract` is an array of [year, month, day, hour, minute, second, millisecond]
```
**TypeScript version**
```ts extract.ts
const extract = (date: Date): string[] =>
date
.toISOString()
.split(/[^0-9]/)
.slice(0, -1);
```
================================================
FILE: contents/find-the-closest-number-from-an-array.mdx
================================================
---
category: Array
created: '2020-05-22'
title: Find the closest number from an array
updated: '2021-10-13'
---
**JavaScript version**
```js closest.js
// Find the number from `arr` which is closest to `n`
const closest = (arr, n) => arr.reduce((prev, curr) => (Math.abs(curr - n) < Math.abs(prev - n) ? curr : prev));
// Or
const closest = (arr, n) => arr.sort((a, b) => Math.abs(a - n) - Math.abs(b - n))[0];
```
**TypeScript version**
```ts closest.ts
const closest = (arr: number[], n: number): number =>
arr.reduce((prev, curr) => (Math.abs(curr - n) < Math.abs(prev - n) ? curr : prev));
// Or
const closest = (arr: number[], n: number): number => arr.sort((a, b) => Math.abs(a - n) - Math.abs(b - n))[0];
```
**Example**
```js example.js
closest([29, 87, 8, 78, 97, 20, 75, 33, 24, 17], 50); // 33
```
================================================
FILE: contents/find-the-index-of-the-last-matching-item-of-an-array.mdx
================================================
---
category: Array
created: '2020-12-31'
title: Find the index of the last matching item of an array
updated: '2021-10-22'
---
**JavaScript version**
```js lastIndex.js
const lastIndex = (arr, predicate) => arr.reduce((prev, curr, index) => (predicate(curr) ? index : prev), -1);
// Or
const lastIndex = (arr, predicate) => arr.map((item) => predicate(item)).lastIndexOf(true);
```
**TypeScript version**
```ts lastIndex.ts
const lastIndex = <T,_>(arr: T[], predicate: (a: T) => boolean): number => arr.reduce((prev, curr, index) => (predicate(curr) ? index : prev), -1);
// Or
const lastIndex = <T,_>(arr: T[], predicate: (a: T) => boolean): number => arr.map((item) => predicate(item)).lastIndexOf(true);
```
**Examples**
```js examples.js
lastIndex([1, 3, 5, 7, 9, 2, 4, 6, 8], (i) => i % 2 === 1); // 4
lastIndex([1, 3, 5, 7, 9, 8, 6, 4, 2], (i) => i > 6); // 5
```
================================================
FILE: contents/find-the-index-of-the-maximum-item-of-an-array.mdx
================================================
---
category: Array
created: '2021-04-20'
title: Find the index of the maximum item of an array
updated: '2021-10-13'
---
**JavaScript version**
```js indexOfMax.js
const indexOfMax = (arr) => arr.reduce((prev, curr, i, a) => (curr > a[prev] ? i : prev), 0);
```
**TypeScript version**
```ts indexOfMax.ts
const indexOfMax = (arr: number[]): number => arr.reduce((prev, curr, i, a) => (curr > a[prev] ? i : prev), 0);
```
**Examples**
```js examples.js
indexOfMax([1, 3, 9, 7, 5]); // 2
indexOfMax([1, 3, 7, 7, 5]); // 2
```
================================================
FILE: contents/find-the-index-of-the-minimum-item-of-an-array.mdx
================================================
---
category: Array
created: '2021-04-20'
title: Find the index of the minimum item of an array
updated: '2021-10-13'
---
**JavaScript version**
```js indexOfMin.js
const indexOfMin = (arr) => arr.reduce((prev, curr, i, a) => (curr < a[prev] ? i : prev), 0);
```
**TypeScript version**
```ts indexOfMin.ts
const indexOfMin = (arr: number[]): number => arr.reduce((prev, curr, i, a) => (curr < a[prev] ? i : prev), 0);
```
**Examples**
```js examples.js
indexOfMin([6, 4, 8, 2, 10]); // 3
indexOfMin([6, 4, 2, 2, 10]); // 2
```
================================================
FILE: contents/find-the-length-of-the-longest-string-in-an-array.mdx
================================================
---
category: Array
contributors:
- codepo8
created: '2020-04-30'
title: Find the length of the longest string in an array
updated: '2021-10-13'
---
**JavaScript version**
```js findLongest.js
const findLongest = (words) => Math.max(...words.map((el) => el.length));
```
**TypeScript version**
```ts findLongest.ts
const findLongest = (words: string[]): number => Math.max(...words.map((el) => el.length));
```
**Example**
```js example.js
findLongest(['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']); // 6
```
================================================
FILE: contents/find-the-maximum-item-of-an-array-by-given-key.mdx
================================================
---
category: Array
created: '2021-01-13'
title: Find the maximum item of an array by given key
updated: '2021-10-13'
---
**JavaScript version**
```js maxBy.js
const maxBy = (arr, key) => arr.reduce((a, b) => (a[key] >= b[key] ? a : b), {});
```
**TypeScript version**
```ts maxBy.ts
const maxBy = <T extends Record<string, any>, K extends keyof T>(arr: T[], key: K): T => (
arr.reduce((a, b) => (a[key] >= b[key] ? a : b), {} as T)
);
```
**Example**
```js example.js
const people = [
{ name: 'Bar', age: 24 },
{ name: 'Baz', age: 32 },
{ name: 'Foo', age: 42 },
{ name: 'Fuzz', age: 36 },
];
maxBy(people, 'age'); // { name: 'Foo', age: 42 }
```
================================================
FILE: contents/find-the-maximum-item-of-an-array.mdx
================================================
---
category: Array
created: '2020-04-19'
title: Find the maximum item of an array
updated: '2021-10-13'
---
**JavaScript version**
```js max.js
const max = (arr) => Math.max(...arr);
```
**TypeScript version**
```ts max.ts
const max = (arr: number[]): number => Math.max(...arr);
```
================================================
FILE: contents/find-the-minimum-item-of-an-array-by-given-key.mdx
================================================
---
category: Array
created: '2021-01-13'
title: Find the minimum item of an array by given key
updated: '2021-10-13'
---
**JavaScript version**
```js minBy.js
const minBy = (arr, key) => arr.reduce((a, b) => (a[key] < b[key] ? a : b), {});
```
**TypeScript version**
```ts minBy.ts
const minBy = <T extends Record<string, any>, K extends keyof T>(arr: T[], key: K): T => (
arr.reduce((a, b) => (a[key] < b[key] ? a : b), {} as T)
);
```
**Example**
```js example.js
const people = [
{ name: 'Bar', age: 24 },
{ name: 'Baz', age: 32 },
{ name: 'Foo', age: 42 },
{ name: 'Fuzz', age: 36 },
];
minBy(people, 'age'); // { name: 'Bar', age: 24 }
```
================================================
FILE: contents/find-the-minimum-item-of-an-array.mdx
================================================
---
category: Array
created: '2020-04-19'
title: Find the minimum item of an array
updated: '2021-10-13'
---
**JavaScript version**
```js min.js
const min = (arr) => Math.min(...arr);
```
**TypeScript version**
```ts min.ts
const min = (arr: number[]): number => Math.min(...arr);
```
================================================
FILE: contents/flatten-an-array.mdx
================================================
---
category: Array
contributors:
- nico2che
created: '2020-05-01'
title: Flatten an array
updated: '2021-10-13'
---
**JavaScript version**
```js flat.js
const flat = (arr) =>
[].concat.apply(
[],
arr.map((a) => (Array.isArray(a) ? flat(a) : a))
);
// Or
const flat = (arr) => arr.reduce((a, b) => (Array.isArray(b) ? [...a, ...flat(b)] : [...a, b]), []);
// Or
// See the browser compatibility at https://caniuse.com/#feat=array-flat
const flat = (arr) => arr.flat();
```
**Example**
```js example.js
flat(['cat', ['lion', 'tiger']]); // ['cat', 'lion', 'tiger']
```
================================================
FILE: contents/flip-the-arguments-of-a-function.mdx
================================================
---
category: Function
created: '2020-05-12'
title: Flip the arguments of a function
---
**JavaScript version**
```js flip.js
// Reverse the order of arguments
const flip =
(fn) =>
(...args) =>
fn(...args.reverse());
// For binary functions
const flip = (fn) => (b, a) => fn(a, b);
// Or for curried functions
const flip = (fn) => (b) => (a) => fn(a)(b);
```
**Examples**
```js examples.js
const isParent = (parent, child) => parent.children.includes(child);
const isChild = flip(isParent);
```
================================================
FILE: contents/format-a-date-for-the-given-locale.mdx
================================================
---
category: Date Time
created: '2020-05-06'
title: Format a date for the given locale
updated: '2021-10-13'
---
**JavaScript version**
```js
// `date` is a `Date` object
// `locale` is a locale (en-US, pt-BR, for example)
const format = (date, locale) => new Intl.DateTimeFormat(locale).format(date);
```
**TypeScript version**
```ts format.ts
const format = (date: Date, locale: string): string => new Intl.DateTimeFormat(locale).format(date);
```
**Example**
```js example.js
format(new Date(), 'pt-BR'); // 06/05/2020
```
================================================
FILE: contents/format-a-string.mdx
================================================
---
category: String
contributors:
- david-luna
created: '2021-11-10'
title: Format a string
---
**JavaScript version**
```js format.js
const format = (str, ...vals) => vals.reduce((s, v, i) => s.replace(new RegExp('\\{' + i + '\\}', 'g'), v), str);
```
**TypeScript version**
```ts
const format = (str: string, ...vals: unknown[]): string =>
vals.reduce((s, v, i) => s.replace(new RegExp('\\{' + i + '\\}', 'g'), v), str);
```
**Examples**
```js examples.js
const template = 'My name is {0} and I am {1} years old';
format(template, 'John', 30));
// My name is John and I am 30 years old
format(template, 'Jane', 20);
// My name is Jane and I am 20 years old
```
================================================
FILE: contents/generate-a-hash-of-a-string.mdx
================================================
---
category: String
created: '2021-03-21'
title: Generate a hash of a string
updated: '2021-10-13'
---
**JavaScript version**
```js hash.js
const hash = (str) => str.split('').reduce((prev, curr) => (Math.imul(31, prev) + curr.charCodeAt(0)) | 0, 0);
// Or
const hash = (str) => str.split('').reduce((prev, curr) => ((prev << 5) - prev + curr.charCodeAt(0)) | 0, 0);
```
**TypeScript version**
```ts hash.ts
const hash = (str: string): number =>
str.split('').reduce((prev, curr) => (Math.imul(31, prev) + curr.charCodeAt(0)) | 0, 0);
// Or
const hash = (str: string): number =>
str.split('').reduce((prev, curr) => ((prev << 5) - prev + curr.charCodeAt(0)) | 0, 0);
```
**Examples**
```js examples.js
hash('hello'); // 99162322
```
================================================
FILE: contents/generate-a-random-boolean.mdx
================================================
---
category: Random
created: '2020-05-05'
title: Generate a random boolean
updated: '2021-10-13'
---
**JavaScript version**
```js randomBoolean.js
const randomBoolean = () => Math.random() >= 0.5;
```
**TypeScript version**
```ts randomBoolean.ts
const randomBoolean = (): boolean => Math.random() >= 0.5;
```
================================================
FILE: contents/generate-a-random-floating-point-number-in-given-range.mdx
================================================
---
category: Random
created: '2020-05-05'
title: Generate a random floating point number in given range
updated: '2021-10-13'
---
**JavaScript version**
```js randomFloat.js
const randomFloat = (min, max) => Math.random() * (max - min) + min;
```
**TypeScript version**
```ts randomFloat.ts
const randomFloat = (min: number, max: number): number => Math.random() * (max - min) + min;
```
## See also
- [Generate a random integer in given range](https://phuoc.ng/collection/1-loc/generate-a-random-integer-in-given-range/)
- [Generate a weighted random number in given range](https://phuoc.ng/collection/1-loc/generate-a-weighted-random-number-in-given-range/)
================================================
FILE: contents/generate-a-random-hex-color.mdx
================================================
---
category: Random
contributors:
- robinpokorny
created: '2020-04-19'
title: Generate a random hex color
updated: '2021-10-13'
---
**JavaScript version**
```js randomColor.js
const randomColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`;
// Or
const randomColor = () => `#${(~~(Math.random() * (1 << 24))).toString(16)}`;
```
**TypeScript version**
```ts randomColor.ts
const randomColor = (): string => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`;
// Or
const randomColor = (): string => `#${(~~(Math.random() * (1 << 24))).toString(16)}`;
```
================================================
FILE: contents/generate-a-random-integer-in-given-range.mdx
================================================
---
category: Random
created: '2020-05-05'
title: Generate a random integer in given range
updated: '2021-10-13'
---
**JavaScript version**
```js randomInteger.js
const randomInteger = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
```
**TypeScript version**
```ts randomInteger.ts
const randomInteger = (min: number, max: number): number => Math.floor(Math.random() * (max - min + 1)) + min;
```
## See also
- [Generate a random floating point number in given range](https://phuoc.ng/collection/1-loc/generate-a-random-floating-point-number-in-given-range/)
- [Generate a weighted random number in given range](https://phuoc.ng/collection/1-loc/generate-a-weighted-random-number-in-given-range/)
================================================
FILE: contents/generate-a-random-ip-address.mdx
================================================
---
category: Random
contributors:
- PiyushSuthar
- Comet32
created: '2020-08-10'
title: Generate a random IP address
updated: '2023-08-09'
---
**JavaScript version**
```js randomIp.js
const randomIp = () =>
Array(4)
.fill(0)
.map((_, i) => Math.floor(Math.random() * 255) + (i === 0 ? 1 : 0))
.join('.');
```
**TypeScript version**
```ts randomIp.ts
const randomIp = (): string =>
Array(4)
.fill(0)
.map((_, i) => Math.floor(Math.random() * 255) + (i === 0 ? 1 : 0))
.join('.');
```
**Examples**
```js examples.js
randomIp(); // 175.89.174.131
```
================================================
FILE: contents/generate-a-random-sign.mdx
================================================
---
category: Random
created: '2021-04-10'
title: Generate a random sign
updated: '2021-10-13'
---
**JavaScript version**
```js randomSign.js
const randomSign = () => (Math.random() >= 0.5 ? 1 : -1);
```
**TypeScript version**
```ts randomSign.ts
const randomSign = (): number => (Math.random() >= 0.5 ? 1 : -1);
```
================================================
FILE: contents/generate-a-random-string-from-given-characters.mdx
================================================
---
category: Random
created: '2020-04-23'
title: Generate a random string from given characters
updated: '2021-10-13'
---
**JavaScript version**
```js generateString.js
const generateString = (length, chars) =>
Array(length)
.fill('')
.map((v) => chars[Math.floor(Math.random() * chars.length)])
.join('');
```
**TypeScript version**
```ts generateString.ts
const generateString = (length: number, chars: string) =>
Array(length)
.fill('')
.map((v) => chars[Math.floor(Math.random() * chars.length)])
.join('');
```
**Examples**
```js examples.js
generateString(10, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
```
================================================
FILE: contents/generate-a-random-string-using-node-crypto-module.mdx
================================================
---
category: Random
created: '2020-07-28'
title: Generate a random string using Node crypto module
updated: '2021-10-13'
---
**JavaScript version**
```js randomStr.js
const randomStr = () => require('crypto').randomBytes(32).toString('hex');
```
**TypeScript version**
```ts randomStr.ts
const randomStr = (): string => require('crypto').randomBytes(32).toString('hex');
```
================================================
FILE: contents/generate-a-random-string-with-given-length.mdx
================================================
---
category: Random
created: '2020-04-23'
title: Generate a random string with given length
updated: '2021-10-13'
---
**JavaScript version**
```js generateString.js
const generateString = (length) =>
Array(length)
.fill('')
.map((v) => Math.random().toString(36).charAt(2))
.join('');
```
**TypeScript version**
```ts generateString.ts
const generateString = (length: number): string =>
Array(length)
.fill('')
.map((v) => Math.random().toString(36).charAt(2))
.join('');
```
================================================
FILE: contents/generate-a-random-uuid.mdx
================================================
---
category: Random
contributors:
- w3bdesign
created: '2020-05-05'
title: Generate a random UUID
---
**JavaScript version**
```js uuid.js
const uuid = (a) =>
a
? (a ^ ((Math.random() * 16) >> (a / 4))).toString(16)
: ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, uuid);
```
================================================
FILE: contents/generate-a-weighted-random-number-in-given-range.mdx
================================================
---
category: Random
created: '2023-08-22'
description: one-liner function to generate a weighted random number in given range
openGraphCover: /og/1-loc/weighted-random.png
title: Generate a weighted random number in given range
---
**JavaScript version**
```js weightedRandom.js
const weightedRandom = (min, max) => ~~(Math.pow(Math.random(), 2) * (max - min)) + min;
```
**TypeScript version**
```ts weightedRandom.ts
const weightedRandom = (min: number, max: number): number => ~~(Math.pow(Math.random(), 2) * (max - min)) + min;
```
**Examples**
```js examples.js
weightedRandom(2, 10); // 7
weightedRandom(2, 10); // 6
weightedRandom(2, 10); // 4
weightedRandom(2, 10); // 3
weightedRandom(2, 10); // 5
```
## See also
- [Generate a random floating point number in given range](https://phuoc.ng/collection/1-loc/generate-a-random-floating-point-number-in-given-range/)
- [Generate a random integer in given range](https://phuoc.ng/collection/1-loc/generate-a-random-integer-in-given-range/)
================================================
FILE: contents/generate-an-array-of-alphabet-characters.mdx
================================================
---
category: Array
created: '2021-10-22'
title: Generate an array of alphabet characters
updated: '2021-10-22'
---
**JavaScript version**
```js alphabet.js
const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
// Or
const alphabet = [...'abcdefghijklmnopqrstuvwxyz'];
// Or
const alphabet = Array(26)
.fill(0)
.map((_, i) => String.fromCharCode(i + 97));
// Or
const alphabet = [...Array(26).keys()].map((i) => String.fromCharCode(i + 97));
// Or
const alphabet = [...Array(26)].map((_, i) => (i + 10).toString(36));
// Or
const alphabet = String.fromCharCode(
...' '
.repeat(26)
.split('')
.map((_, i) => i + 97)
).split('');
```
**TypeScript version**
```ts alphabet.ts
const alphabet: string[] = 'abcdefghijklmnopqrstuvwxyz'.split('');
// Or
const alphabet: string[] = [...'abcdefghijklmnopqrstuvwxyz'];
// Or
const alphabet: string[] = Array(26)
.fill(0)
.map((_, i) => String.fromCharCode(i + 97));
// Or
const alphabet: string[] = [...Array(26).keys()].map((i) => String.fromCharCode(i + 97));
// Or
const alphabet: string[] = [...Array(26)].map((_, i) => (i + 10).toString(36));
// Or
const alphabet: string[] = String.fromCharCode(
...' '
.repeat(26)
.split('')
.map((_, i) => i + 97)
).split('');
```
================================================
FILE: contents/generate-an-array-of-random-integers-in-a-given-range.mdx
================================================
---
category: Random
created: '2020-05-16'
title: Generate an array of random integers in a given range
updated: '2021-10-13'
---
**JavaScript version**
```js randomArrayInRange.js
const randomArrayInRange = (min, max, n) =>
Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min);
```
**TypeScript version**
```ts randomArrayInRange.ts
const randomArrayInRange = (min: number, max: number, n: number): number[] =>
Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min);
```
**Examples**
```js examples.js
randomArrayInRange(1, 100, 10); // [11, 82, 41, 35, 76, 83, 43, 15, 60, 54]
```
================================================
FILE: contents/generate-an-unique-and-increment-id.mdx
================================================
---
category: Misc
created: '2021-04-05'
title: Generate an unique and increment id
---
**JavaScript version**
```js uid.js
const uid = (() => ((id = 0), () => id++))();
```
**Examples**
```js examples.js
uid(); // 0
uid(); // 1
uid(); // 2
uid(); // 3
```
================================================
FILE: contents/get-a-random-item-and-remove-it-from-an-array.mdx
================================================
---
category: Random
created: '2021-01-16'
title: Get a random item and remove it from an array
updated: '2021-10-13'
---
**JavaScript version**
```js randomItem.js
const randomItem = (arr) => arr.splice((Math.random() * arr.length) | 0, 1);
```
**TypeScript version**
```ts randomItem.ts
const randomItem = <T,>(arr: T[]): T => arr.splice((Math.random() * arr.length) | 0, 1) as unknown as T;
```
**Examples**
```js examples.js
const arr = [1, 3, 5, 7, 9];
randomItem(arr); // 7
// arr = [1, 3, 5, 9]
```
================================================
FILE: contents/get-a-random-item-from-an-array.mdx
================================================
---
category: Random
contributors:
- jonrandy
created: '2020-04-19'
title: Get a random item from an array
updated: '2021-10-22'
---
**JavaScript version**
```js randomItem.js
const randomItem = (arr) => arr[(Math.random() * arr.length) | 0];
```
**TypeScript version**
```ts randomItem.ts
const randomItem = <T,_>(arr: T[]): T => arr[(Math.random() * arr.length) | 0];
```
================================================
FILE: contents/get-all-arrays-of-consecutive-elements.mdx
================================================
---
category: Array
created: '2021-04-10'
title: Get all arrays of consecutive elements
updated: '2021-10-22'
---
**JavaScript version**
```js getConsecutiveArrays.js
const getConsecutiveArrays = (arr, size) =>
size > arr.length ? [] : arr.slice(size - 1).map((_, i) => arr.slice(i, size + i));
```
**TypeScript version**
```ts getConsecutiveArrays.ts
const getConsecutiveArrays = <T,_>(arr: T[], size: number): T[][] => (size > arr.length ? [] : arr.slice(size - 1).map((_, i) => arr.slice(i, size + i)));
```
**Examples**
```js examples.js
getConsecutiveArrays([1, 2, 3, 4, 5], 2); // [[1, 2], [2, 3], [3, 4], [4, 5]]
getConsecutiveArrays([1, 2, 3, 4, 5], 3); // [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
getConsecutiveArrays([1, 2, 3, 4, 5], 6); // []
```
================================================
FILE: contents/get-all-nth-items-of-an-array.mdx
================================================
---
category: Array
created: '2021-02-20'
title: 'Get all n-th items of an array'
updated: '2021-10-22'
---
**JavaScript version**
```js getNthItems.js
const getNthItems = (arr, nth) => arr.filter((_, i) => i % nth === nth - 1);
```
**TypeScript version**
```ts getNthItems.ts
const getNthItems = <T,_>(arr: T[], nth: number): T[] => arr.filter((_, i) => i % nth === nth - 1);
```
**Examples**
```js examples.js
getNthItems([1, 2, 3, 4, 5, 6, 7, 8, 9], 2); // [2, 4, 6, 8]
getNthItems([1, 2, 3, 4, 5, 6, 7, 8, 9], 3); // [3, 6, 9]
```
================================================
FILE: contents/get-all-siblings-of-an-element.mdx
================================================
---
category: DOM
created: '2020-04-19'
title: Get all siblings of an element
updated: '2021-10-13'
---
**JavaScript version**
```js siblings.js
const siblings = (ele) => [].slice.call(ele.parentNode.children).filter((child) => child !== ele);
```
**TypeScript version**
```ts siblings.ts
const siblings = (ele: Node): Node[] =>
ele.parentNode ? [].slice.call(ele.parentNode.children).filter((child) => child !== ele) : [];
```
================================================
FILE: contents/get-all-subsets-of-an-array.mdx
================================================
---
category: Array
created: '2021-02-25'
title: Get all subsets of an array
updated: '2021-10-13'
---
**JavaScript version**
```js getSubsets.js
const getSubsets = (arr) => arr.reduce((prev, curr) => prev.concat(prev.map((k) => k.concat(curr))), [[]]);
```
**TypeScript version**
```ts getSubsets.ts
const getSubsets = <T,>(arr: T[]): T[][] => (
arr.reduce((prev, curr) => prev.concat(prev.map((k) => k.concat(curr))), [[]] as T[][])
);
```
**Examples**
```js examples.js
getSubsets([1, 2]); // [[], [1], [2], [1, 2]]
getSubsets([1, 2, 3]); // [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
```
================================================
FILE: contents/get-hours-and-minutes-from-decimal-time.mdx
================================================
---
category: Date Time
contributors:
- ognjenst
created: '2022-12-27'
title: Get the hours and minutes from the decimal time
---
**JavaScript version**
```js getHoursAndMinutes.js
const getHoursAndMinutes = (value) => [Math.floor(value), Math.floor((value * 60) % 60)];
```
**TypeScript version**
```ts getHoursAndMinutes.ts
const getHoursAndMinutes = (value: number): [number, number] => [Math.floor(value), Math.floor((value * 60) % 60)];
```
**Examples**
```js examples.js
getHoursAndMinutes(4.5); //[4, 30]
getHoursAndMinutes(7.89); // [7, 53]
```
================================================
FILE: contents/get-indices-of-a-value-in-an-array.mdx
================================================
---
category: Array
created: '2021-03-07'
title: Get indices of a value in an array
updated: '2021-10-13'
---
**JavaScript version**
```js indices.js
const indices = (arr, value) => arr.reduce((acc, v, i) => (v === value ? [...acc, i] : acc), []);
// Or
const indices = (arr, value) => arr.map((v, i) => (v === value ? i : false)).filter(Boolean);
```
**TypeScript version**
```ts indices.ts
const indices = <T,>(arr: T[], value: T): number[] => (
arr.reduce((acc, v, i) => (v === value ? [...acc, i] : acc), [] as number[])
);
// Or
const indices = <T,>(arr: T[], value: T): number[] => (
arr.map((v, i) => (v === value ? i : false)).filter(Boolean) as number[]
);
```
**Examples**
```js examples.js
indices(['h', 'e', 'l', 'l', 'o'], 'l'); // [2, 3]
indices(['h', 'e', 'l', 'l', 'o'], 'w'); // []
```
================================================
FILE: contents/get-random-items-of-an-array.mdx
================================================
---
category: Random
created: '2021-01-16'
title: Get random items of an array
---
**JavaScript version**
```js randomItems.js
const randomItems = (arr, count) =>
arr
.concat()
.reduce(
(p, _, __, arr) =>
p[0] < count ? [p[0] + 1, p[1].concat(arr.splice((Math.random() * arr.length) | 0, 1))] : p,
[0, []]
)[1];
```
**Examples**
```js examples.js
randomItems([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3); // [4, 8, 5]
randomItems(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'], 4); // ['e', 'c', 'h', 'j']
```
================================================
FILE: contents/get-the-arrays-of-digits-from-a-number.mdx
================================================
---
category: Number
created: '2020-05-16'
title: Get the arrays of digits from a number
updated: '2021-10-13'
---
**JavaScript version**
```js digitize.js
const digitize = (n) => `${n}`.split('').map((v) => parseInt(v, 10));
// Or
const digitize = (n) => [...`${n}`].map((v) => parseInt(v, 10));
```
**TypeScript version**
```ts digitize.ts
const digitize = (n: number): number[] => `${n}`.split('').map((v) => parseInt(v, 10));
// Or
const digitize = (n: number): number[] => [...`${n}`].map((v) => parseInt(v, 10));
```
**Examples**
```js examples.js
digitize(123); // [1, 2, 3]
```
================================================
FILE: contents/get-the-average-of-an-array.mdx
================================================
---
category: Array
created: '2020-04-19'
title: Get the average of an array
updated: '2021-10-13'
---
**JavaScript version**
```js average.js
const average = (arr) => arr.reduce((a, b) => a + b, 0) / arr.length;
```
**TypeScript version**
```ts average.ts
const average = (arr: number[]): number => arr.reduce((a, b) => a + b, 0) / arr.length;
```
================================================
FILE: contents/get-the-base-url-without-any-parameters.mdx
================================================
---
category: String
contributors:
- shawphy
created: '2020-06-20'
title: Get the base URL without any parameters
updated: '2021-10-13'
---
**JavaScript version**
```js baseUrl.js
const baseUrl = (url) => (url.indexOf('?') === -1 ? url : url.slice(0, url.indexOf('?')));
// Or
// Note that `includes` isn't supported in IE 11
const baseUrl = (url) => (url.includes('?') ? url.slice(0, url.indexOf('?')) : url);
// Or
const baseUrl = (url) => url.split('?')[0];
```
**TypeScript version**
```ts baseUrl.ts
const baseUrl = (url: string): string => (url.indexOf('?') === -1 ? url : url.slice(0, url.indexOf('?')));
// Or
// Note that `includes` isn't supported in IE 11
const baseUrl = (url: string): string => (url.includes('?') ? url.slice(0, url.indexOf('?')) : url);
// Or
const baseUrl = (url: string): string => url.split('?')[0];
```
**Examples**
```js examples.js
baseUrl('https://domain.com/path/sub/path?foo=bar&hello=world'); // 'https://domain.com/path/sub/path'
```
================================================
FILE: contents/get-the-center-point-of-a-dom-rect.mdx
================================================
---
category: DOM
created: '2023-12-09'
openGraphCover: /og/1-loc/get-center-point-dom-rect.png
title: Get the center point of a DOMRect
---
**JavaScript version**
```js getCenter.js
const getCenter = rect => [rect.left + rect.width / 2, rect.top + rect.height / 2];
```
**TypeScript version**
```ts getCenter.ts
const getCenter = (rect: DOMRect): [number, number] => [rect.left + rect.width / 2, rect.top + rect.height / 2];
```
**Examples**
```js example.js
getCenter(new DOMRect(0, 0, 200, 400)); // [100, 200]
```
================================================
FILE: contents/get-the-current-quarter-of-a-date.mdx
================================================
---
category: Date Time
created: '2021-02-25'
title: Get the current quarter of a date
updated: '2021-10-13'
---
**JavaScript version**
```js getQuarter.js
const getQuarter = (d = new Date()) => Math.ceil((d.getMonth() + 1) / 3);
```
**TypeScript version**
```ts getQuarter.ts
const getQuarter = (d = new Date()): number => Math.ceil((d.getMonth() + 1) / 3);
```
================================================
FILE: contents/get-the-current-timestamp-in-seconds.mdx
================================================
---
category: Date Time
created: '2020-04-19'
title: Get the current timestamp in seconds
updated: '2021-10-13'
---
**JavaScript version**
```js ts.js
const ts = () => Math.floor(new Date().getTime() / 1000);
```
**TypeScript version**
```ts ts.ts
const ts = (): number => Math.floor(new Date().getTime() / 1000);
```
================================================
FILE: contents/get-the-day-of-the-year-from-a-date.mdx
================================================
---
category: Date Time
created: '2020-05-16'
title: Get the day of the year from a date
updated: '2021-10-13'
---
**JavaScript version**
```js dayOfYear.js
// `date` is a Date object
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24));
```
**TypeScript version**
```ts dayOfYear.ts
const dayOfYear = (date: Date): number =>
Math.floor((date.valueOf() - new Date(date.getFullYear(), 0, 0).valueOf()) / (1000 * 60 * 60 * 24));
```
**Example**
```js example.js
dayOfYear(new Date(2020, 04, 16)); // 137
```
================================================
FILE: contents/get-the-file-extension-from-a-file-name.mdx
================================================
---
category: String
created: '2020-04-19'
title: Get the file extension from a file name
updated: '2021-10-13'
---
**JavaScript version**
```js ext.js
const ext = (fileName) => fileName.split('.').pop();
```
**TypeScript version**
```ts ext.ts
const ext = (fileName: string): string => fileName.split('.').pop();
```
================================================
FILE: contents/get-the-file-name-from-a-url.mdx
================================================
---
category: String
created: '2020-04-19'
title: Get the file name from a URL
updated: '2021-10-13'
---
**JavaScript version**
```js fileName.js
const fileName = (url: string): string => url.substring(url.lastIndexOf('/') + 1);
```
**TypeScript version**
```ts fileName.ts
const fileName = (url: string): string => url.substring(url.lastIndexOf('/') + 1);
```
**Examples**
```js examples.js
fileName('http://domain.com/path/to/document.pdf'); // 'document.pdf'
```
================================================
FILE: contents/get-the-first-date-in-the-month-of-a-date.mdx
================================================
---
category: Date Time
created: '2021-02-25'
title: Get the first date in the month of a date
updated: '2021-10-13'
---
**JavaScript version**
```js getFirstDate.js
const getFirstDate = (d = new Date()) => new Date(d.getFullYear(), d.getMonth(), 1);
```
**TypeScript version**
```ts getFirstDate.ts
const getFirstDate = (d = new Date()): Date => new Date(d.getFullYear(), d.getMonth(), 1);
```
================================================
FILE: contents/get-the-first-defined-and-non-null-argument.mdx
================================================
---
category: Misc
created: '2020-06-12'
title: Get the first defined and non null argument
updated: '2021-10-13'
---
**JavaScript version**
```js coalesce.js
const coalesce = (...args) => args.find((item) => item !== undefined && item !== null);
// Or
const coalesce = (...args) => args.find((item) => ![undefined, null].includes(item));
```
**TypeScript version**
```ts coalesce.ts
const coalesce = (...args: any[]): any[] => args.find((item) => item !== undefined && item !== null);
// Or
const coalesce = (...args: any[]): any[] => args.find((item) => ![undefined, null].includes(item));
```
**Examples**
```js examples.js
coalesce(undefined, null, 'helloworld', NaN); // 'helloworld'
```
================================================
FILE: contents/get-the-intersection-of-arrays.mdx
================================================
---
category: Array
contributors:
- vreymond
- robinpokorny
created: '2020-05-09'
title: Get the intersection of arrays
updated: '2021-10-22'
---
**JavaScript version**
```js getIntersection.js
const getIntersection = (a, ...arr) => [...new Set(a)].filter((v) => arr.every((b) => b.includes(v)));
```
**TypeScript version**
```ts getIntersection.ts
const getIntersection = <T,_>(a: T[], ...arr: T[][]): T[] => [...new Set(a)].filter((v) => arr.every((b) => b.includes(v)));
```
**Examples**
```js examples.js
getIntersection([1, 2, 3], [2, 3, 4, 5]); // [2, 3]
getIntersection([1, 2, 3], [2, 3, 4, 5], [1, 3, 5]); // [3]
```
================================================
FILE: contents/get-the-intersection-range-between-two-ranges.mdx
================================================
---
category: Number
created: '2023-12-07'
openGraphCover: /og/1-loc/get-intersection-range-between-two-ranges.png
title: Get the intersection range between two ranges
---
**JavaScript version**
```js intersection.js
const intersection = (a, b) => (a[0] > b[1] || a[1] < b[0]) ? [] : [Math.max(a[0], b[0]), Math.min(a[1], b[1])];
```
**TypeScript version**
```ts intersection.ts
const 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])];
```
**Examples**
```js examples.js
intersection([0, 20], [15, 35]); // [15, 20]
intersection([0, 20], [40, 50]); // []
```
================================================
FILE: contents/get-the-last-date-in-the-month-of-a-date.mdx
================================================
---
category: Date Time
created: '2021-02-25'
title: Get the last date in the month of a date
updated: '2021-10-13'
---
**JavaScript version**
```js getLastDate.js
const getLastDate = (d = new Date()) => new Date(d.getFullYear(), d.getMonth() + 1, 0);
```
**TypeScript version**
```ts getLastDate.ts
const getLastDate = (d = new Date()): Date => new Date(d.getFullYear(), d.getMonth() + 1, 0);
```
================================================
FILE: contents/get-the-length-of-a-string-in-bytes.mdx
================================================
---
category: String
created: '2020-05-16'
title: Get the length of a string in bytes
updated: '2021-10-13'
---
**JavaScript version**
```js bytes.js
const bytes = (str) => new Blob([str]).size;
```
**TypeScript version**
```ts bytes.ts
const bytes = (str: string): number => new Blob([str]).size;
```
**Examples**
```js examples.js
bytes('hello world'); // 11
bytes('🎉'); // 4
```
================================================
FILE: contents/get-the-month-name-of-a-date.mdx
================================================
---
category: Date Time
created: '2020-05-05'
title: Get the month name of a date
updated: '2021-10-13'
---
**JavaScript version**
```js getMonthName.js
// `date` is a Date object
const getMonthName = (date) =>
[
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
' November',
'December',
][date.getMonth()];
```
**TypeScript version**
```ts getMonthName.ts
const getMonthName = (date: Date): string =>
[
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
' November',
'December',
][date.getMonth()];
```
================================================
FILE: contents/get-the-number-of-a-character-in-a-string.mdx
================================================
---
category: String
created: '2020-08-02'
title: Get the number of a character in a string
updated: '2021-10-13'
---
**JavaScript version**
```js characterCount.js
const characterCount = (str, char) => str.split(char).length - 1;
// Or
const characterCount = (str, char) => str.replace(new RegExp(String.raw`[^${char}]`, 'g'), '').length;
```
**TypeScript version**
```ts characterCount.ts
const characterCount = (str: string, char: string): number => str.split(char).length - 1;
// Or
const characterCount = (str: string, char: string): number =>
str.replace(new RegExp(String.raw`[^${char}]`, 'g'), '').length;
```
**Examples**
```js examples.js
characterCount('192.168.1.1', '.'); // 3
characterCount('star wars', 's'); // 2
```
================================================
FILE: contents/get-the-number-of-days-in-given-month.mdx
================================================
---
category: Date Time
created: '2020-04-19'
title: Get the number of days in given month
updated: '2021-10-13'
---
**JavaScript version**
```js daysInMonth.js
// `month` is zero-based index
const daysInMonth = (month, year) => new Date(year, month, 0).getDate();
```
**TypeScript version**
```ts daysInMonth.ts
const daysInMonth = (month: number, year: number): number => new Date(year, month, 0).getDate();
```
================================================
FILE: contents/get-the-position-of-an-element-relative-to-the-document.mdx
================================================
---
category: DOM
created: '2021-04-21'
title: Get the position of an element relative to the document
updated: '2021-10-13'
---
**JavaScript version**
```js getPosition.js
const getPosition = (ele) => (
(r = ele.getBoundingClientRect()), { left: r.left + window.scrollX, top: r.top + window.scrollY }
);
```
**Example**
```js example.js
getPosition(document.body); // { left: 0, top: 0 }
```
================================================
FILE: contents/get-the-rank-of-an-array-of-numbers.mdx
================================================
---
category: Array
created: '2020-04-19'
title: Get the rank of an array of numbers
updated: '2021-10-13'
---
**JavaScript version**
```js ranking.js
const ranking = (arr) => arr.map((x, y, z) => z.filter((w) => w > x).length + 1);
```
**TypeScript version**
```ts ranking.ts
const ranking = (arr: number[]): number[] => arr.map((x, y, z) => z.filter((w) => w > x).length + 1);
```
**Examples**
```js examples.js
ranking([80, 65, 90, 50]); // [2, 3, 1, 4]
ranking([80, 80, 70, 50]); // [1, 1, 3, 4]
ranking([80, 80, 80, 50]); // [1, 1, 1, 4]
```
================================================
FILE: contents/get-the-selected-text.mdx
================================================
---
category: DOM
created: '2020-04-19'
title: Get the selected text
updated: '2021-10-13'
---
**JavaScript version**
```js getSelectedText.js
const getSelectedText = () => window.getSelection().toString();
```
================================================
FILE: contents/get-the-sum-of-an-array-of-numbers.mdx
================================================
---
category: Array
created: '2020-04-19'
title: Get the sum of an array of numbers
updated: '2021-10-13'
---
**JavaScript version**
```js sum.js
const sum = (arr) => arr.reduce((a, b) => a + b, 0);
```
**TypeScript version**
```ts sum.ts
const sum = (arr: number[]): number => arr.reduce((a, b) => a + b, 0);
```
================================================
FILE: contents/get-the-timezone-string.mdx
================================================
---
category: Date Time
created: '2021-02-25'
title: Get the timezone string
updated: '2021-10-13'
---
**JavaScript version**
```js getTimezone.js
const getTimezone = () => Intl.DateTimeFormat().resolvedOptions().timeZone;
```
**TypeScript version**
```ts getTimezone.ts
const getTimezone = (): string => Intl.DateTimeFormat().resolvedOptions().timeZone;
```
**Example**
```js example.js
getTimezone(); // 'Asia/Saigon'
```
================================================
FILE: contents/get-the-tomorrow-date.mdx
================================================
---
category: Date Time
created: '2020-05-21'
title: Get the tomorrow date
updated: '2021-10-13'
---
**JavaScript version**
```js tomorrow.js
const tomorrow = ((d) => new Date(d.setDate(d.getDate() + 1)))(new Date());
// Or
const tomorrow = new Date(new Date().valueOf() + 1000 * 60 * 60 * 24);
```
**TypeScript version**
```ts tomorrow.ts
const tomorrow: Date = ((d) => new Date(d.setDate(d.getDate() + 1)))(new Date());
// Or
const tomorrow: Date = new Date(new Date().valueOf() + 1000 * 60 * 60 * 24);
```
## See also
- [Determine one year from now](https://phuoc.ng/collection/1-loc/determine-one-year-from-now/)
- [Get the yesterday date](https://phuoc.ng/collection/1-loc/get-the-yesterday-date/)
================================================
FILE: contents/get-the-total-number-of-days-in-a-year.mdx
================================================
---
category: Date Time
created: '2021-04-10'
title: Get the total number of days in a year
updated: '2021-10-13'
---
**JavaScript version**
```js numberOfDays.js
const numberOfDays = (year) => ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 366 : 365);
// Or
const numberOfDays = (year) => (new Date(year, 1, 29).getDate() === 29 ? 366 : 365);
```
**TypeScript version**
```ts numberOfDays.ts
const numberOfDays = (year: number): number => ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 366 : 365);
// Or
const numberOfDays = (year: number): number => (new Date(year, 1, 29).getDate() === 29 ? 366 : 365);
```
================================================
FILE: contents/get-the-unique-values-of-an-array.mdx
================================================
---
category: Array
contributors:
- vreymond
created: '2020-04-19'
title: Get the unique values of an array
updated: '2021-10-13'
---
**JavaScript version**
```js unique.js
const unique = (arr) => [...new Set(arr)];
// Or
const unique = (arr) => arr.filter((el, i, array) => array.indexOf(el) === i);
// Or
const unique = (arr) => arr.reduce((acc, el) => (acc.includes(el) ? acc : [...acc, el]), []);
```
**TypeScript version**
```ts unique.ts
const unique = <T,>(arr: T[]): T[] => [...new Set(arr)];
// Or
const unique = <T,>(arr: T[]): T[] => arr.filter((el, i, array) => array.indexOf(el) === i);
// Or
const unique = <T,>(arr: T[]): T[] => arr.reduce((acc, el) => (acc.includes(el) ? acc : [...acc, el]), [] as T[]);
```
================================================
FILE: contents/get-the-value-at-given-path-of-an-object.mdx
================================================
---
category: Object
created: '2020-05-13'
title: Get the value at given path of an object
---
**JavaScript version**
```js getValue.js
const getValue = (path, obj) => path.split('.').reduce((acc, c) => acc && acc[c], obj);
```
**Examples**
```js examples.js
getValue('a.b', { a: { b: 'Hello World' } }); // 'Hello World';
```
================================================
FILE: contents/get-the-value-of-a-cookie.mdx
================================================
---
category: Misc
created: '2020-05-28'
title: Get the value of a cookie
---
**JavaScript version**
```js cookie.js
const cookie = (name) => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();
```
**Examples**
```js examples.js
cookie('_ga'); // GA1.2.825309271.1581874719
```
================================================
FILE: contents/get-the-value-of-a-param-from-a-url.mdx
================================================
---
category: Misc
created: '2020-04-23'
title: Get the value of a param from a URL
updated: '2021-10-13'
---
**JavaScript version**
```js getParam.js
const getParam = (url, param) => new URLSearchParams(new URL(url).search).get(param);
```
**TypeScript version**
```ts getParam.ts
const getParam = (url: string, param: string): string | null => new URLSearchParams(new URL(url).search).get(param);
```
**Examples**
```js examples.js
getParam('http://domain.com?message=hello', 'message'); // 'hello'
```
================================================
FILE: contents/get-the-weekday-of-a-date.mdx
================================================
---
category: Date Time
created: '2020-05-05'
title: Get the weekday of a date
updated: '2021-10-13'
---
**JavaScript version**
```js getWeekday.js
// `date` is a Date object
const getWeekday = (date) =>
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][date.getDay()];
```
**TypeScript version**
```ts getWeekday.ts
const getWeekday = (date: Date): string =>
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][date.getDay()];
```
================================================
FILE: contents/get-the-yesterday-date.mdx
================================================
---
category: Date Time
created: '2020-05-21'
title: Get the yesterday date
updated: '2021-10-13'
---
**JavaScript version**
```js yesterday.js
const yesterday = ((d) => new Date(d.setDate(d.getDate() - 1)))(new Date());
// Or
const yesterday = new Date(new Date().valueOf() - 1000 * 60 * 60 * 24);
```
**TypeScript version**
```ts yesterday.ts
const yesterday: Date = ((d) => new Date(d.setDate(d.getDate() - 1)))(new Date());
// Or
const yesterday: Date = new Date(new Date().valueOf() - 1000 * 60 * 60 * 24);
```
## See also
- [Determine one year from now](https://phuoc.ng/collection/1-loc/determine-one-year-from-now/)
- [Get the tomorrow date](https://phuoc.ng/collection/1-loc/get-the-tomorrow-date/)
================================================
FILE: contents/get-type-of-a-variable-in-string.mdx
================================================
---
category: Misc
created: '2021-01-12'
title: Get type of a variable in string
updated: '2021-10-13'
---
**JavaScript version**
```js getTypeOf.js
const getTypeOf = (obj) => Object.prototype.toString.call(obj).match(/\[object (.*)\]/)[1];
```
**TypeScript version**
```ts getTypeOf.ts
const getTypeOf = (obj: any): string => (Object.prototype.toString.call(obj).match(/\[object (.*)\]/) as string[])[1];
```
**Examples**
```js examples.js
getTypeOf('hello world'); // String
getTypeOf(1000); // Number
getTypeOf(Infinity); // Number
getTypeOf(true); // Boolean
getTypeOf(Symbol()); // Symbol
getTypeOf(null); // Null
getTypeOf(undefined); // Undefined
getTypeOf({}); // Object
getTypeOf([]); // Array
getTypeOf(/[a-z]/g); // RegExp
getTypeOf(new Date(2021)); // Date
getTypeOf(new Error()); // Error
getTypeOf(function () {}); // Function
getTypeOf((a, b) => a + b); // Function
getTypeOf(async () => {}); // AsyncFunction
getTypeOf(document); // HTMLDocument
```
================================================
FILE: contents/get-union-of-arrays.mdx
================================================
---
category: Array
created: '2020-05-09'
title: Get union of arrays
updated: '2021-10-22'
---
**JavaScript version**
```js union.js
const union = (...arr) => [...new Set(arr.flat())];
```
**TypeScript version**
```ts union.ts
const union = <T,_>(...arr: T[][]): T[] => [...new Set(arr.flat())];
```
**Example**
```js example.js
union([1, 2], [2, 3], [3]); // [1, 2, 3]
```
================================================
FILE: contents/get-unique-arr-obj.mdx
================================================
---
category: Object
contributors:
- gpbuavv
created: '2023-02-17'
title: Returns an object with unique values by key
---
**JavaScript version**
```js
export const getUniqueArrObj = (arrObj, keyUnique) => [...new Map(arrObj.map((item) => [item[keyUnique], item])).values()];
```
**Example**
```js example.js
// Example
getUniqueArrObj([{ k: 1, e: 1 }, { k: 1, e: 1 }, { k: 3, e: 1 }], 'k'); // [{ k: 1, e: 1 }, { k: 3, e: 1 }]
```
================================================
FILE: contents/go-back-to-the-previous-page.mdx
================================================
---
category: DOM
created: '2020-04-19'
title: Go back to the previous page
updated: '2021-10-13'
---
**JavaScript version**
```js
history.back();
// Or
history.go(-1);
```
================================================
FILE: contents/group-an-array-of-objects-by-a-key.mdx
================================================
---
category: Array
created: '2020-06-03'
title: Group an array of objects by a key
updated: '2021-10-13'
---
**JavaScript version**
```js groupBy.js
const groupBy = (arr, key) =>
arr.reduce((acc, item) => ((acc[item[key]] = [...(acc[item[key]] || []), item]), acc), {});
```
**TypeScript version**
```ts groupBy.ts
const groupBy = <T extends Record<string, any>, K extends keyof T>(arr: T[], key: K): Record<string, T[]> => (
arr.reduce((acc, item) => ((acc[item[key]] = [...(acc[item[key]] || []), item]), acc), {} as Record<string, T[]>)
);
```
**Example**
```js example.js
groupBy(
[
{ branch: 'audi', model: 'q8', year: '2019' },
{ branch: 'audi', model: 'rs7', year: '2020' },
{ branch: 'ford', model: 'mustang', year: '2019' },
{ branch: 'ford', model: 'explorer', year: '2020' },
{ branch: 'bmw', model: 'x7', year: '2020' },
],
'branch'
);
/*
{
audi: [
{ branch: 'audi', model: 'q8', year: '2019' },
{ branch: 'audi', model: 'rs7', year: '2020' }
],
bmw: [
{ branch: 'bmw', model: 'x7', year: '2020' }
],
ford: [
{ branch: 'ford', model: 'mustang', year: '2019' },
{ branch: 'ford', model: 'explorer', year: '2020' }
],
}
*/
```
================================================
FILE: contents/hide-an-element.mdx
================================================
---
category: DOM
contributors:
- iamdileepkumar
- islamozbek
created: '2020-04-19'
title: Hide an element
updated: '2021-10-13'
---
**JavaScript version**
```js hide.js
// Pick the method that is suitable for your use case
const hide = (ele) => (ele.style.display = 'none');
// Or
const hide = (ele) => (ele.style.visibility = 'hidden');
// Or
const hide = (ele) => (ele.hidden = true);
```
**TypeScript version**
```ts hide.ts
const hide = (ele: HTMLElement): string => (ele.style.display = 'none');
// Or
const hide = (ele: HTMLElement): string => (ele.style.visibility = 'hidden');
// Or
const hide = (ele: HTMLElement): boolean => (ele.hidden = true);
```
================================================
FILE: contents/identity-function.mdx
================================================
---
category: Function
created: '2020-05-07'
title: Identity function
---
**JavaScript version**
```js identity.js
const identity = (x) => x;
```
================================================
FILE: contents/immutably-rename-object-keys.mdx
================================================
---
category: Object
contributors:
- imyangyong
created: '2021-01-11'
title: Immutably rename object keys
---
**JavaScript version**
```js renameKeys.js
const renameKeys = (keysMap, obj) =>
Object.keys(obj).reduce((acc, key) => ({ ...acc, ...{ [keysMap[key] || key]: obj[key] } }), {});
```
**Examples**
```js examples.js
const obj = { a: 1, b: 2, c: 3 };
const keysMap = { a: 'd', b: 'e', c: 'f' };
renameKeys(keysMap, obj); // { d: 1, e: 2, f: 3 }
```
================================================
FILE: contents/initialize-the-current-date-but-set-time-to-midnight.mdx
================================================
---
category: Date Time
created: '2021-04-20'
title: Initialize the current date but set time to midnight
updated: '2021-10-13'
---
**JavaScript version**
```js midnightOfToday.js
const midnightOfToday = () => new Date(new Date().setHours(0, 0, 0, 0));
```
**TypeScript version**
```ts midnightOfToday.ts
const midnightOfToday = (): Date => new Date(new Date().setHours(0, 0, 0, 0));
```
================================================
FILE: contents/insert-an-element-after-other-one.mdx
================================================
---
category: DOM
created: '2020-04-19'
title: Insert an element after other one
updated: '2021-10-13'
---
**JavaScript version**
```js insertAfter.js
const insertAfter = (ele, anotherEle) => anotherEle.parentNode.insertBefore(ele, anotherEle.nextSibling);
// Or
const insertAfter = (ele, anotherEle) => anotherEle.insertAdjacentElement('afterend', ele);
```
**TypeScript version**
```ts insertAfter.ts
const insertAfter = (ele: Element, anotherEle: Element): Element | null =>
anotherEle.parentNode ? anotherEle.parentNode.insertBefore(ele, anotherEle.nextSibling) : null;
// Or
const insertAfter = (ele: Element, anotherEle: Element): Element | null =>
anotherEle.insertAdjacentElement('afterend', ele);
```
================================================
FILE: contents/insert-an-element-before-other-one.mdx
================================================
---
category: DOM
created: '2020-04-19'
title: Insert an element before other one
updated: '2021-10-13'
---
**JavaScript version**
```js insertBefore.js
const insertBefore = (ele, anotherEle) => anotherEle.parentNode.insertBefore(ele, anotherEle);
// Or
const insertBefore = (ele, anotherEle) => anotherEle.insertAdjacentElement('beforebegin', ele);
```
**TypeScript version**
```ts insertBefore.ts
const insertBefore = (ele: Element, anotherEle: Element): Element | null =>
anotherEle.parentNode ? anotherEle.parentNode.insertBefore(ele, anotherEle) : null;
// Or
const insertBefore = (ele: Element, anotherEle: Element) => anotherEle.insertAdjacentElement('beforebegin', ele);
```
================================================
FILE: contents/insert-given-html-after-an-element.mdx
================================================
---
category: DOM
created: '2020-04-19'
title: Insert given HTML after an element
updated: '2021-10-13'
---
**JavaScript version**
```js insertHtmlAfter.js
const insertHtmlAfter = (html, ele) => ele.insertAdjacentHTML('afterend', html);
```
**TypeScript version**
```ts insertHtmlAfter.ts
const insertHtmlAfter = (html: string, ele: Element): void => ele.insertAdjacentHTML('afterend', html);
```
================================================
FILE: contents/insert-given-html-before-an-element.mdx
================================================
---
category: DOM
created: '2020-04-19'
title: Insert given HTML before an element
updated: '2021-10-13'
---
**JavaScript version**
```js insertHtmlBefore.js
const insertHtmlBefore = (html, ele) => ele.insertAdjacentHTML('beforebegin', html);
```
**TypeScript version**
```ts insertHtmlBefore.ts
const insertHtmlBefore = (html: string, ele: Element): void => ele.insertAdjacentHTML('beforebegin', html);
```
================================================
FILE: contents/intersperse-element-between-elements.mdx
================================================
---
category: Array
contributors:
- iamandrewluca
created: '2021-12-24'
title: Intersperse element between elements
---
**JavaScript version**
```js intersperse.js
const intersperse = (a, s) => [...Array(2 * a.length - 1)].map((_, i) => (i % 2 ? s : a[i / 2]));
```
**TypeScript version**
```ts
const intersperse = <T>(a: T[], s: T): T[] => [...Array(2 * a.length - 1)].map((_, i) => (i % 2 ? s : a[i / 2]));
```
**Examples**
```tsx
intersperse(['A', 'B', 'C'], '/'); // ['A', '/', 'B', '/', 'C']
intersperse([<li>A</li>, <li>B</li>, <li>C</li>], <li>/</li>); // [<li>A</li>, <li>/</li>, <li>B</li>, <li>/</li>, <li>C</li>]
```
================================================
FILE: contents/invert-keys-and-values-of-an-object.mdx
================================================
---
category: Object
contributors:
- johandalabacka
created: '2020-05-15'
title: Invert keys and values of an object
updated: '2020-12-27'
---
**JavaScript version**
```js invert.js
const invert = (obj) => Object.keys(obj).reduce((res, k) => Object.assign(res, { [obj[k]]: k }), {});
// Or
const invert = (obj) => Object.fromEntries(Object.entries(obj).map(([k, v]) => [v, k]));
```
**Examples**
```js examples.js
invert({ a: '1', b: '2', c: '3' }); // { 1: 'a', 2: 'b', 3: 'c' }
```
================================================
FILE: contents/linear-scale-number-in-ranges.mdx
================================================
---
category: Math
contributors:
- iamandrewluca
created: '2023-09-28'
title: Linear Scale of a Number between two ranges
---
**JavaScript version**
```js linear-scale.js
function linearScale(value, inMin, inMax, outMin, outMax) {
return ((value - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin;
}
```
**TypeScript version**
```ts linear-scale.ts
function linearScale(value: number, inMin: number, inMax: number, outMin: number, outMax: number) {
return ((value - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin;
}
```
**Examples**
```js examples.js
linearScale(5, 0, 10, 0, 100); // 50
linearScale(10, 10, 20, 0, 100); // 0
linearScale(3, 0, 9, 0, 90); // 30
```
## See also
- [Normalize the ratio of a number in a range](https://phuoc.ng/collection/1-loc/normalize-the-ratio-of-a-number-in-a-range)
- [Calculate the linear interpolation between two numbers](https://phuoc.ng/collection/1-loc/calculate-the-linear-interpolation-between-two-numbers)
================================================
FILE: contents/linear-scale-of-a-number-between-two-ranges.mdx
================================================
---
author: iamandrewluca
category: Math
contributors:
- iamandrewluca
created: '2023-09-28'
openGraphCover: /og/1-loc/linear-scale-number-between-two-ranges.png
title: Linear scale of a number between two ranges
---
**JavaScript version**
```js linear-scale.js
const linearScale = (value, inMin, inMax, outMin, outMax) =>
((value - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin;
```
**TypeScript version**
```ts linear-scale.ts
const linearScale = (value: number, inMin: number, inMax: number, outMin: number, outMax: number): number =>
((value - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin;
```
**Examples**
```js examples.js
linearScale(5, 0, 10, 0, 100); // 50
linearScale(10, 10, 20, 0, 100); // 0
linearScale(3, 0, 9, 0, 90); // 30
```
## See also
- [Normalize the ratio of a number in a range](https://phuoc.ng/collection/1-loc/normalize-the-ratio-of-a-number-in-a-range/)
- [Calculate the linear interpolation between two numbers](https://phuoc.ng/collection/1-loc/calculate-the-linear-interpolation-between-two-numbers/)
================================================
FILE: contents/logical-xor-operator.mdx
================================================
---
category: Function
created: '2020-05-13'
title: Logical xor operator
---
**JavaScript version**
```js
// returns `true` if one of the arguments is truthy and the other is falsy
const xor = (a, b) => (a && !b) || (!a && b);
// Or
const xor = (a, b) => !(!a && !b) && !(a && b);
// Or
const xor = (a, b) => Boolean(!a ^ !b);
```
**Examples**
```js examples.js
xor(true, true); // false
xor(false, false); // false
xor(true, false); // true
xor(false, true); // true
```
================================================
FILE: contents/make-the-first-character-of-a-string-lowercase.mdx
================================================
---
category: String
created: '2020-05-03'
title: Make the first character of a string lowercase
updated: '2021-10-13'
---
**JavaScript version**
```js lowercaseFirst.js
const lowercaseFirst = (str) => `${str.charAt(0).toLowerCase()}${str.slice(1)}`;
```
**TypeScript version**
```ts lowercaseFirst.ts
const lowercaseFirst = (str: string): string => `${str.charAt(0).toLowerCase()}${str.slice(1)}`;
```
**Examples**
```js examples.js
lowercaseFirst('Hello World'); // 'hello World'
```
================================================
FILE: contents/memoize-a-function.mdx
================================================
---
category: Function
contributors:
- Kikobeats
created: '2020-05-16'
title: Memoize a function
updated: '2021-10-06'
---
**JavaScript version**
```js memoize.js
const memoize = (fn) =>
(
(cache = Object.create(null)) =>
(arg) =>
cache[arg] || (cache[arg] = fn(arg))
)();
```
**Examples**
```js examples.js
// Calculate Fibonacci numbers
const fibo = memoize((n) => (n <= 2 ? 1 : fibo(n - 1) + fibo(n - 2)));
fibo(1); // 1
fibo(2); // 1
fibo(3); // 2
fibo(4); // 3
fibo(5); // 5
fibo(6); // 8
```
================================================
FILE: contents/merge-two-arrays.mdx
================================================
---
category: Array
created: '2020-04-19'
title: Merge two arrays
updated: '2021-10-22'
---
**JavaScript version**
```js merge.js
// Merge but don't remove the duplications
const merge = (a, b) => a.concat(b);
// Or
const merge = (a, b) => [...a, ...b];
// Merge and remove the duplications
const merge = (a, b) => [...new Set(a.concat(b))];
// Or
const merge = (a, b) => [...new Set([...a, ...b])];
```
**TypeScript version**
```ts merge.ts
// Merge but don't remove the duplications
const merge = <T,_>(a: T[], b: T[]): T[] => a.concat(b);
// Or
const merge = <T,_>(a: T[], b: T[]): T[] => [...a, ...b];
// Merge and remove the duplications
const merge = <T,_>(a: T[], b: T[]): T[] => [...new Set(a.concat(b))];
// Or
const merge = <T,_>(a: T[], b: T[]): T[] => [...new Set([...a, ...b])];
```
================================================
FILE: contents/multiply-arguments.mdx
================================================
---
category: Number
created: '2020-05-05'
title: Multiply arguments
updated: '2021-10-13'
---
**JavaScript version**
```js mul.js
const mul = (...args) => args.reduce((a, b) => a * b);
```
**TypeScript version**
```ts mul.ts
const mul = (...args: number[]): number => args.reduce((a, b) => a * b);
```
**Examples**
```js examples.js
mul(1, 2, 3, 4); // 24
```
================================================
FILE: contents/normalize-file-path-slashes.mdx
================================================
---
category: String
created: '2020-05-15'
title: Normalize file path slashes
updated: '2021-10-13'
---
**JavaScript version**
```js normalizePath.js
const normalizePath = (path) => path.replace(/[\\/]+/g, '/');
```
**TypeScript version**
```ts normalizePath.ts
const normalizePath = (path: string): string => path.replace(/[\\/]+/g, '/');
```
**Examples**
```js examples.js
normalizePath('\\foo\\bar\\baz\\'); // /foo/bar/baz/
normalizePath('.//foo//bar///////baz/'); // ./foo/bar/baz/
```
================================================
FILE: contents/normalize-the-ratio-of-a-number-in-a-range.mdx
================================================
---
category: Math
created: '2021-05-24'
title: Normalize the ratio of a number in a range
updated: '2021-10-13'
---
**JavaScript version**
```js normalizeRatio.js
const normalizeRatio = (value, min, max) => (value - min) / (max - min);
```
**TypeScript version**
```ts normalizeRatio.ts
const normalizeRatio = (value: number, min: number, max: number): number => (value - min) / (max - min);
```
## See also
- [Calculate the linear interpolation between two numbers](https://phuoc.ng/collection/1-loc/calculate-the-linear-interpolation-between-two-numbers/)
- [Linear scale of a number between two ranges](https://phuoc.ng/collection/1-loc/linear-scale-of-a-number-between-two-ranges/)
================================================
FILE: contents/omit-a-subset-of-properties-from-an-object.mdx
================================================
---
category: Object
created: '2020-05-13'
title: Omit a subset of properties from an object
---
**JavaScript version**
```js omit.js
const omit = (obj, keys) =>
Object.keys(obj)
.filter((k) => !keys.includes(k))
.reduce((res, k) => Object.assign(res, { [k]: obj[k] }), {});
```
**Examples**
```js examples.js
omit({ a: '1', b: '2', c: '3' }, ['a', 'b']); // { c: '3' }
```
================================================
FILE: contents/partially-apply-a-function.mdx
================================================
---
category: Function
created: '2020-05-13'
title: Partially apply a function
---
**JavaScript version**
```js partial.js
const partial =
(fn, ...a) =>
(...b) =>
fn(...a, ...b);
```
**Examples**
```js examples.js
const sum = (x, y) => x + y;
const inc = partial(sum, 1);
inc(9); // 10
```
================================================
FILE: contents/partition-an-array-based-on-a-condition.mdx
================================================
---
category: Array
contributors:
- TangSY
created: '2020-05-13'
title: Partition an array based on a condition
updated: '2021-10-22'
---
**JavaScript version**
```js partition.js
const partition = (arr, criteria) => arr.reduce((acc, i) => (acc[criteria(i) ? 0 : 1].push(i), acc), [[], []]);
```
**TypeScript version**
```ts partition.ts
const partition = <T,_>(arr: T[], criteria: (a: T) => boolean): T[][] => arr.reduce((acc, i) => (acc[criteria(i) ? 0 : 1].push(i), acc), [[], []]);
```
**Example**
```js example.js
partition([1, 2, 3, 4, 5], (n) => n % 2); // [[1, 3, 5], [2, 4]]
```
================================================
FILE: contents/pick-a-random-property-of-an-object.mdx
================================================
---
category: Random
created: '2021-04-19'
title: Pick a random property of an object
updated: '2021-10-13'
---
**JavaScript version**
```js randomProp.js
const randomProp = (obj) => Object.keys(obj)[(Math.random() * Object.keys(obj).length) | 0];
```
**TypeScript version**
```ts randomProp.ts
const randomProp = (obj: object): any => Object.keys(obj)[(Math.random() * Object.keys(obj).length) | 0];
```
**Examples**
```js examples.js
const colors = {
aqua: '#00ffff',
azure: '#f0ffff',
beige: '#f5f5dc',
black: '#000000',
blue: '#0000ff',
brown: '#a52a2a',
cyan: '#00ffff',
darkblue: '#00008b',
darkcyan: '#008b8b',
darkgrey: '#a9a9a9',
darkgreen: '#006400',
darkkhaki: '#bdb76b',
darkmagenta: '#8b008b',
darkolivegreen: '#556b2f',
darkorange: '#ff8c00',
darkorchid: '#9932cc',
darkred: '#8b0000',
darksalmon: '#e9967a',
darkviolet: '#9400d3',
fuchsia: '#ff00ff',
gold: '#ffd700',
green: '#008000',
indigo: '#4b0082',
khaki: '#f0e68c',
lightblue: '#add8e6',
lightcyan: '#e0ffff',
lightgreen: '#90ee90',
lightgrey: '#d3d3d3',
lightpink: '#ffb6c1',
lightyellow: '#ffffe0',
lime: '#00ff00',
magenta: '#ff00ff',
maroon: '#800000',
navy: '#000080',
olive: '#808000',
orange: '#ffa500',
pink: '#ffc0cb',
purple: '#800080',
violet: '#800080',
red: '#ff0000',
silver: '#c0c0c0',
white: '#ffffff',
yellow: '#ffff00',
};
randomProp(colors); // 'red'
```
================================================
FILE: contents/pick-a-subset-of-properties-of-an-object.mdx
================================================
---
category: Object
created: '2020-05-13'
title: Pick a subset of properties of an object
---
**JavaScript version**
```js pick.js
const pick = (obj, keys) =>
Object.keys(obj)
.filter((k) => keys.includes(k))
.reduce((res, k) => Object.assign(res, { [k]: obj[k] }), {});
```
**Examples**
```js examples.js
pick({ a: '1', b: '2', c: '3' }, ['a', 'b']); // { a: '1', b: '2' }
```
================================================
FILE: contents/pick-random-lines-from-a-text-document.mdx
================================================
---
category: Random
created: '2021-06-01'
title: Pick random lines from a text document
---
**JavaScript version**
```js randomLines.js
const randomLines = (str, count) =>
str
.split(/\r?\n/)
.reduce(
(p, _, __, arr) =>
p[0] < count ? [p[0] + 1, p[1].concat(arr.splice((Math.random() * arr.length) | 0, 1))] : p,
[0, []]
)[1];
```
**Examples**
```js examples.js
randomLines(
`one
two
three
four
five`,
2
);
// ['one', 'four']
```
================================================
FILE: contents/prefix-an-integer-with-zeros.mdx
================================================
---
category: Number
contributors:
- VincentRoth
created: '2020-04-23'
title: Prefix an integer with zeros
updated: '2021-10-13'
---
**JavaScript version**
```js prefixWithZeros.js
const prefixWithZeros = (n, length) => (n / Math.pow(10, length)).toFixed(length).substr(2);
// Or
const prefixWithZeros = (n, length) => `${Array(length).join('0')}${n}`.slice(-length);
// Or
const prefixWithZeros = (n, length) => String(n).padStart(length, '0');
```
**TypeScript version**
```ts prefixWithZeros.ts
const prefixWithZeros = (n: number, length: number): string => (n / Math.pow(10, length)).toFixed(length).substr(2);
// Or
const prefixWithZeros = (n: number, length: number): string => `${Array(length).join('0')}${n}`.slice(-length);
// Or
const prefixWithZeros = (n: number, length: number): string => String(n).padStart(length, '0');
```
**Examples**
```js examples.js
prefixWithZeros(42, 5); // '00042'
```
================================================
FILE: contents/prepend-a-line-number-to-each-line-of-a-text-document.mdx
================================================
---
category: String
created: '2021-06-07'
title: Prepend a line number to each line of a text document
updated: '2021-10-13'
---
**JavaScript version**
```js prependNumbers.js
const prependNumbers = (str) =>
str
.split(/\r?\n/)
.map((line, i) => `${(i + 1).toString().padStart(2, ' ')} ${line}`)
.join('\n');
```
**TypeScript version**
```ts prependNumbers.ts
const prependNumbers = (str: string): string =>
str
.split(/\r?\n/)
.map((line, i) => `${(i + 1).toString().padStart(2, ' ')} ${line}`)
.join('\n');
```
**Examples**
```js examples.js
prependNumbers(`one
two
three
four`);
/* Output */
/*
1 one
2 two
3 three
4 four
*/
```
================================================
FILE: contents/redirect-the-page-to-https-if-it-is-in-http.mdx
================================================
---
category: Misc
created: '2020-05-31'
title: Redirect the page to HTTPS if it is in HTTP
updated: '2021-10-13'
---
**JavaScript version**
```js redirectHttps.js
const redirectHttps = () =>
location.protocol === 'https:' ? {} : location.replace(`https://${location.href.split('//')[1]}`);
// Or
const redirectHttps = () => (location.protocol === 'https:' ? {} : (location.protocol = 'https:'));
```
**TypeScript version**
```ts redirectHttps.ts
const redirectHttps = (): void =>
location.protocol === 'https:' ? void 0 : location.replace(`https://${location.href.split('//')[1]}`);
// Or
const redirectHttps = (): string => (location.protocol === 'https:' ? '' : (location.protocol = 'https:'));
```
================================================
FILE: contents/redirect-to-another-page.mdx
================================================
---
category: DOM
created: '2020-04-19'
title: Redirect to another page
updated: '2021-10-13'
---
**JavaScript version**
```js goTo.js
const goTo = (url) => (location.href = url);
```
**TypeScript version**
```ts goTo.ts
const goTo = (url: string): string => (location.href = url);
```
================================================
FILE: contents/reload-the-current-page.mdx
================================================
---
category: DOM
created: '2020-04-19'
title: Reload the current page
updated: '2021-10-13'
---
**JavaScript version**
```js reload.js
const reload = () => location.reload();
// Or
const reload = () => (location.href = location.href);
```
**TypeScript version**
```ts reload.ts
const reload = (): void => location.reload();
// Or
const reload = (): string => (location.href = location.href);
```
================================================
FILE: contents/remove-all-null-and-undefined-properties-from-an-object.mdx
================================================
---
category: Object
contributors:
- jjswifty
created: '2021-04-20'
title: Remove all null and undefined properties from an object
updated: '2023-05-15'
---
**JavaScript version**
```js removeNullUndefined.js
const removeNullUndefined = (obj) => Object.entries(obj).reduce((a, [k, v]) => (v == null ? a : ((a[k] = v), a)), {});
// Or
const removeNullUndefined = (obj) =>
Object.entries(obj)
.filter(([_, v]) => v != null)
.reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {});
// Or
const removeNullUndefined = (obj) => Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));
```
**TypeScript version**
```ts
const removeNullUndefined = <T extends Record<string, any>>(obj: T) =>
Object.entries(obj).reduce((a: any, [k, v]) =>
(v == null ? a : ((a[k] = v), a)), {}) as {
[K in keyof T as T[K] extends null | undefined ? never : K]: T[K]
};
// Or
const removeNullUndefined = <T extends Record<string, any>>(obj: T) =>
Object.entries(obj)
.filter(([_, v]) => v != null)
.reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {}) as {
[K in keyof T as T[K] extends null | undefined ? never : K]: T[K]
};
// Or
const removeNullUndefined = <T extends Record<string, any>>(obj: T) =>
Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null)) as {
[K in keyof T as T[K] extends null | undefined ? never : K]: T[K]
};
```
**Examples**
```js examples.js
removeNullUndefined({
foo: null,
bar: undefined,
fuzz: 42,
}); // { fuzz: 42 }
```
================================================
FILE: contents/remove-duplicate-lines-of-a-text-document.mdx
================================================
---
category: String
created: '2021-05-31'
title: Remove duplicate lines of a text document
updated: '2021-10-13'
---
**JavaScript version**
```js removeDuplicateLines.js
const removeDuplicateLines = (str) => Array.from(new Set(str.split(/\r?\n/))).join('\n');
```
**TypeScript version**
```ts removeDuplicateLines.ts
const removeDuplicateLines = (str: string): string => Array.from(new Set(str.split(/\r?\n/))).join('\n');
```
**Examples**
```js examples.js
removeDuplicateLines(`one
three
two
three
one
four`);
/* Output */
/*
one
three
two
four
*/
```
================================================
FILE: contents/remove-duplicate-values-in-an-array.mdx
================================================
---
category: Array
created: '2021-03-07'
title: Remove duplicate values in an array
updated: '2021-10-22'
---
**JavaScript version**
```js removeDuplicate.js
const removeDuplicate = (arr) => arr.filter((i) => arr.indexOf(i) === arr.lastIndexOf(i));
```
**TypeScript version**
```ts removeDuplicate.ts
const removeDuplicate = <T,_>(arr: T[]): T[] => arr.filter((i) => arr.indexOf(i) === arr.lastIndexOf(i));
```
**Example**
```js example.js
removeDuplicate(['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']); // ['h', 'e', 'w', 'r', 'd']
```
================================================
FILE: contents/remove-empty-lines-of-a-text-document.mdx
================================================
---
category: String
created: '2021-05-28'
title: Remove empty lines of a text document
updated: '2021-10-13'
---
**JavaScript version**
```js removeEmptyLines.js
const removeEmptyLines = (str) =>
str
.split(/\r?\n/)
.filter((line) => line.trim() !== '')
.join('\n');
```
**TypeScript version**
```ts removeEmptyLines.ts
const removeEmptyLines = (str: string): string =>
str
.split(/\r?\n/)
.filter((line) => line.trim() !== '')
.join('\n');
```
**Examples**
```js examples.js
removeEmptyLines(`red
green
blue
yellow`);
/* Output */
/*
red
green
blue
yellow
*/
```
================================================
FILE: contents/remove-falsy-values-from-array.mdx
================================================
---
category: Array
contributors:
- vreymond
created: '2020-05-09'
title: Remove falsy values from array
updated: '2021-10-22'
---
**JavaScript version**
```js removeFalsy.js
const removeFalsy = (arr) => arr.filter(Boolean);
```
**TypeScript version**
```ts remov
gitextract_mcm7t2nt/
├── .gitignore
├── LICENSE
├── README.md
└── contents/
├── add-am-pm-suffix-to-an-hour.mdx
├── add-an-ordinal-suffix-to-a-number.mdx
├── box-handler.mdx
├── calculate-fibonacci-numbers.mdx
├── calculate-the-angle-of-a-line-defined-by-two-points.mdx
├── calculate-the-average-of-arguments.mdx
├── calculate-the-distance-between-two-points.mdx
├── calculate-the-distance-to-the-bottom-of-a-page.mdx
├── calculate-the-division-of-arguments.mdx
├── calculate-the-factorial-of-a-number.mdx
├── calculate-the-linear-interpolation-between-two-numbers.mdx
├── calculate-the-midpoint-between-two-points.mdx
├── calculate-the-midpoint-of-a-given-range.mdx
├── calculate-the-mod-of-collection-index.mdx
├── calculate-the-number-of-difference-days-between-two-dates.mdx
├── calculate-the-number-of-months-between-two-dates.mdx
├── calculate-the-remainder-of-division-of-arguments.mdx
├── calculate-the-sum-of-arguments.mdx
├── capitalize-a-string.mdx
├── cast-a-value-as-an-array.mdx
├── check-if-a-character-is-a-digit.mdx
├── check-if-a-date-is-a-weekday.mdx
├── check-if-a-date-is-a-weekend.mdx
├── check-if-a-date-is-between-two-dates.mdx
├── check-if-a-date-is-today.mdx
├── check-if-a-date-occurs-in-the-current-year.mdx
├── check-if-a-flat-array-has-duplicate-values.mdx
├── check-if-a-given-dom-rect-is-contained-within-another-dom-rect.mdx
├── check-if-a-given-integer-is-a-prime-number.mdx
├── check-if-a-number-is-a-power-of-2.mdx
├── check-if-a-number-is-even.mdx
├── check-if-a-number-is-in-a-given-range.mdx
├── check-if-a-number-is-negative.mdx
├── check-if-a-number-is-odd.mdx
├── check-if-a-number-is-positive.mdx
├── check-if-a-path-is-relative.mdx
├── check-if-a-point-is-inside-a-rectangle.mdx
├── check-if-a-rectangle-contains-other-one.mdx
├── check-if-a-rectangle-overlaps-other-one.mdx
├── check-if-a-string-consists-of-a-repeated-character-sequence.mdx
├── check-if-a-string-contains-lower-case-characters.mdx
├── check-if-a-string-contains-only-ascii-characters.mdx
├── check-if-a-string-contains-only-digits.mdx
├── check-if-a-string-contains-only-letters-and-numbers.mdx
├── check-if-a-string-contains-only-letters.mdx
├── check-if-a-string-contains-upper-case-characters.mdx
├── check-if-a-string-contains-whitespace.mdx
├── check-if-a-string-is-a-hexadecimal-color.mdx
├── check-if-a-string-is-a-hexadecimal-number.mdx
├── check-if-a-string-is-a-mongo-db-object-id.mdx
├── check-if-a-string-is-a-palindrome.mdx
├── check-if-a-string-is-an-octal-number.mdx
├── check-if-a-string-is-lower-case.mdx
├── check-if-a-string-is-upper-case.mdx
├── check-if-a-url-is-absolute.mdx
├── check-if-a-value-is-a-business-identifier-code.mdx
├── check-if-a-value-is-a-function.mdx
├── check-if-a-value-is-a-generator-function.mdx
├── check-if-a-value-is-a-number.mdx
├── check-if-a-value-is-a-plain-object.mdx
├── check-if-a-value-is-a-regular-expression.mdx
├── check-if-a-value-is-a-string.mdx
├── check-if-a-value-is-an-async-function.mdx
├── check-if-a-value-is-an-object.mdx
├── check-if-a-value-is-base32-encoded.mdx
├── check-if-a-value-is-base58-encoded.mdx
├── check-if-a-value-is-base64-encoded.mdx
├── check-if-a-value-is-nil.mdx
├── check-if-a-year-is-leap-year.mdx
├── check-if-all-array-elements-are-equal-to-a-given-value.mdx
├── check-if-all-items-in-an-array-are-equal.mdx
├── check-if-an-array-contains-a-value-matching-some-criterias.mdx
├── check-if-an-array-is-empty.mdx
├── check-if-an-array-is-not-empty.mdx
├── check-if-an-array-is-subset-of-other-array.mdx
├── check-if-an-element-has-css-overflow.mdx
├── check-if-an-element-has-overflow.mdx
├── check-if-an-element-is-a-descendant-of-another.mdx
├── check-if-an-element-is-focused.mdx
├── check-if-an-object-is-a-promise.mdx
├── check-if-an-object-is-an-array.mdx
├── check-if-an-object-is-empty.mdx
├── check-if-multiple-objects-are-equal.mdx
├── check-if-the-code-is-running-in-jest.mdx
├── check-if-the-code-is-running-in-node-js.mdx
├── check-if-the-code-is-running-in-the-browser.mdx
├── check-if-the-touch-events-are-supported.mdx
├── check-if-two-dom-rects-intersect.mdx
├── check-if-two-strings-are-anagram.mdx
├── check-if-user-scrolls-to-the-bottom-of-the-page.mdx
├── clamp-a-number-between-two-values.mdx
├── clear-all-cookies.mdx
├── clone-an-array.mdx
├── compare-two-arrays-regardless-of-order.mdx
├── compare-two-arrays.mdx
├── compare-two-dates.mdx
├── compare-two-dom-rects-for-size-and-position-match.mdx
├── compose-functions-from-left-to-right.mdx
├── compose-functions.mdx
├── compute-the-greatest-common-divisor-between-two-numbers.mdx
├── convert-3-digits-color-to-6-digits-color.mdx
├── convert-a-base64-encoded-string-to-an-uint8-array.mdx
├── convert-a-date-to-yyyy-mm-dd-format.mdx
├── convert-a-lab-color-to-an-lch-color.mdx
├── convert-a-letter-to-associate-emoji.mdx
├── convert-a-number-to-equivalent-characters.mdx
├── convert-a-string-to-camel-case.mdx
├── convert-a-string-to-number.mdx
├── convert-a-string-to-pascal-case.mdx
├── convert-a-string-to-url-slug.mdx
├── convert-a-windows-file-path-to-unix-path.mdx
├── convert-an-array-of-objects-to-a-single-object.mdx
├── convert-an-array-of-strings-to-numbers.mdx
├── convert-an-lch-color-to-a-lab-color.mdx
├── convert-an-uint8-array-to-a-base64-encoded-string.mdx
├── convert-camel-case-to-kebab-case-and-vice-versa.mdx
├── convert-celsius-to-fahrenheit.mdx
├── convert-cookie-to-object.mdx
├── convert-decimal-to-binary-recursively.mdx
├── convert-degrees-to-radians.mdx
├── convert-fahrenheit-to-celsius.mdx
├── convert-hex-to-rgb.mdx
├── convert-radians-to-degrees.mdx
├── convert-rgb-color-to-hex.mdx
├── convert-seconds-to-hh-mm-ss-format.mdx
├── convert-snake-case-to-camel-case.mdx
├── convert-the-name-of-an-excel-column-to-number.mdx
├── convert-url-parameters-to-object.mdx
├── count-by-the-properties-of-an-array-of-objects.mdx
├── count-the-number-of-words-in-a-string.mdx
├── count-the-occurrences-of-a-character-in-a-string.mdx
├── count-the-occurrences-of-a-value-in-an-array.mdx
├── count-the-occurrences-of-array-elements.mdx
├── create-a-function-that-accepts-a-single-argument.mdx
├── create-an-array-of-cumulative-sum.mdx
├── create-an-array-of-numbers-in-the-given-range.mdx
├── create-an-empty-function.mdx
├── create-an-empty-map-that-does-not-have-properties.mdx
├── create-an-object-from-the-pairs-of-key-and-value.mdx
├── create-cartesian-product.mdx
├── curry-a-function.mdx
├── decapitalize-a-string.mdx
├── decode-a-jwt-token.mdx
├── decode-html-entities.mdx
├── delay-the-evaluation-of-a-function.mdx
├── detect-dark-mode.mdx
├── detect-internet-explorer-browser.mdx
├── detect-macos-browser.mdx
├── determine-one-year-from-now.mdx
├── easing-functions.mdx
├── empty-an-array.mdx
├── emulate-a-dice-throw.mdx
├── encode-a-url.mdx
├── escape-html-special-characters.mdx
├── execute-a-function-once.mdx
├── extract-values-of-a-property-from-an-array-of-objects.mdx
├── extract-year-month-day-hour-minute-second-and-millisecond-from-a-date.mdx
├── find-the-closest-number-from-an-array.mdx
├── find-the-index-of-the-last-matching-item-of-an-array.mdx
├── find-the-index-of-the-maximum-item-of-an-array.mdx
├── find-the-index-of-the-minimum-item-of-an-array.mdx
├── find-the-length-of-the-longest-string-in-an-array.mdx
├── find-the-maximum-item-of-an-array-by-given-key.mdx
├── find-the-maximum-item-of-an-array.mdx
├── find-the-minimum-item-of-an-array-by-given-key.mdx
├── find-the-minimum-item-of-an-array.mdx
├── flatten-an-array.mdx
├── flip-the-arguments-of-a-function.mdx
├── format-a-date-for-the-given-locale.mdx
├── format-a-string.mdx
├── generate-a-hash-of-a-string.mdx
├── generate-a-random-boolean.mdx
├── generate-a-random-floating-point-number-in-given-range.mdx
├── generate-a-random-hex-color.mdx
├── generate-a-random-integer-in-given-range.mdx
├── generate-a-random-ip-address.mdx
├── generate-a-random-sign.mdx
├── generate-a-random-string-from-given-characters.mdx
├── generate-a-random-string-using-node-crypto-module.mdx
├── generate-a-random-string-with-given-length.mdx
├── generate-a-random-uuid.mdx
├── generate-a-weighted-random-number-in-given-range.mdx
├── generate-an-array-of-alphabet-characters.mdx
├── generate-an-array-of-random-integers-in-a-given-range.mdx
├── generate-an-unique-and-increment-id.mdx
├── get-a-random-item-and-remove-it-from-an-array.mdx
├── get-a-random-item-from-an-array.mdx
├── get-all-arrays-of-consecutive-elements.mdx
├── get-all-nth-items-of-an-array.mdx
├── get-all-siblings-of-an-element.mdx
├── get-all-subsets-of-an-array.mdx
├── get-hours-and-minutes-from-decimal-time.mdx
├── get-indices-of-a-value-in-an-array.mdx
├── get-random-items-of-an-array.mdx
├── get-the-arrays-of-digits-from-a-number.mdx
├── get-the-average-of-an-array.mdx
├── get-the-base-url-without-any-parameters.mdx
├── get-the-center-point-of-a-dom-rect.mdx
├── get-the-current-quarter-of-a-date.mdx
├── get-the-current-timestamp-in-seconds.mdx
├── get-the-day-of-the-year-from-a-date.mdx
├── get-the-file-extension-from-a-file-name.mdx
├── get-the-file-name-from-a-url.mdx
├── get-the-first-date-in-the-month-of-a-date.mdx
├── get-the-first-defined-and-non-null-argument.mdx
├── get-the-intersection-of-arrays.mdx
├── get-the-intersection-range-between-two-ranges.mdx
├── get-the-last-date-in-the-month-of-a-date.mdx
├── get-the-length-of-a-string-in-bytes.mdx
├── get-the-month-name-of-a-date.mdx
├── get-the-number-of-a-character-in-a-string.mdx
├── get-the-number-of-days-in-given-month.mdx
├── get-the-position-of-an-element-relative-to-the-document.mdx
├── get-the-rank-of-an-array-of-numbers.mdx
├── get-the-selected-text.mdx
├── get-the-sum-of-an-array-of-numbers.mdx
├── get-the-timezone-string.mdx
├── get-the-tomorrow-date.mdx
├── get-the-total-number-of-days-in-a-year.mdx
├── get-the-unique-values-of-an-array.mdx
├── get-the-value-at-given-path-of-an-object.mdx
├── get-the-value-of-a-cookie.mdx
├── get-the-value-of-a-param-from-a-url.mdx
├── get-the-weekday-of-a-date.mdx
├── get-the-yesterday-date.mdx
├── get-type-of-a-variable-in-string.mdx
├── get-union-of-arrays.mdx
├── get-unique-arr-obj.mdx
├── go-back-to-the-previous-page.mdx
├── group-an-array-of-objects-by-a-key.mdx
├── hide-an-element.mdx
├── identity-function.mdx
├── immutably-rename-object-keys.mdx
├── initialize-the-current-date-but-set-time-to-midnight.mdx
├── insert-an-element-after-other-one.mdx
├── insert-an-element-before-other-one.mdx
├── insert-given-html-after-an-element.mdx
├── insert-given-html-before-an-element.mdx
├── intersperse-element-between-elements.mdx
├── invert-keys-and-values-of-an-object.mdx
├── linear-scale-number-in-ranges.mdx
├── linear-scale-of-a-number-between-two-ranges.mdx
├── logical-xor-operator.mdx
├── make-the-first-character-of-a-string-lowercase.mdx
├── memoize-a-function.mdx
├── merge-two-arrays.mdx
├── multiply-arguments.mdx
├── normalize-file-path-slashes.mdx
├── normalize-the-ratio-of-a-number-in-a-range.mdx
├── omit-a-subset-of-properties-from-an-object.mdx
├── partially-apply-a-function.mdx
├── partition-an-array-based-on-a-condition.mdx
├── pick-a-random-property-of-an-object.mdx
├── pick-a-subset-of-properties-of-an-object.mdx
├── pick-random-lines-from-a-text-document.mdx
├── prefix-an-integer-with-zeros.mdx
├── prepend-a-line-number-to-each-line-of-a-text-document.mdx
├── redirect-the-page-to-https-if-it-is-in-http.mdx
├── redirect-to-another-page.mdx
├── reload-the-current-page.mdx
├── remove-all-null-and-undefined-properties-from-an-object.mdx
├── remove-duplicate-lines-of-a-text-document.mdx
├── remove-duplicate-values-in-an-array.mdx
├── remove-empty-lines-of-a-text-document.mdx
├── remove-falsy-values-from-array.mdx
├── remove-spaces-from-a-string.mdx
├── repeat-a-string.mdx
├── repeat-an-array.mdx
├── replace-all-line-breaks-with-br-elements.mdx
├── replace-all-tab-characters-with-spaces.mdx
├── replace-an-element.mdx
├── replace-multiple-spaces-with-a-single-space.mdx
├── replace-the-first-given-number-of-characters-of-a-string-with-another-character.mdx
├── reverse-a-string.mdx
├── reverse-the-order-of-lines-of-a-text.mdx
├── round-a-number-to-a-given-number-of-digits.mdx
├── round-a-number-to-the-nearest-multiple-of-a-given-value.mdx
├── run-promises-in-sequence.mdx
├── scroll-to-top-of-the-page.mdx
├── serialize-form-data.mdx
├── shallow-copy-an-object.mdx
├── show-an-element.mdx
├── shuffle-an-array.mdx
├── sort-an-array-of-dates.mdx
├── sort-an-array-of-items-by-given-key.mdx
├── sort-an-array-of-numbers.mdx
├── sort-an-object-by-its-properties.mdx
├── sort-lines-of-a-text-document-in-the-alphabetical-order.mdx
├── sort-the-characters-of-a-string-in-the-alphabetical-order.mdx
├── split-an-array-into-chunks.mdx
├── strip-ansi-codes-from-a-string.mdx
├── strip-html-from-a-given-text.mdx
├── subtract-arguments.mdx
├── swap-case-of-characters-in-a-string.mdx
├── swap-the-rows-and-columns-of-a-matrix.mdx
├── swap-two-array-items.mdx
├── swap-two-variables.mdx
├── toggle-an-element.mdx
├── trim-slashes-at-the-beginning-and-the-end-of-a-string.mdx
├── trim-some-character.mdx
├── trim-the-file-extension-from-a-file-name.mdx
├── truncate-a-number-at-decimal.mdx
├── truncate-a-number-to-a-given-number-of-decimal-places-without-rounding.mdx
├── truncate-a-string-at-full-words.mdx
├── uncurry-a-function.mdx
├── unescape-html-special-characters.mdx
├── unzip-an-array-of-arrays.mdx
├── uppercase-the-first-character-of-each-word-in-a-string.mdx
├── validate-a-gregorian-date.mdx
├── wait-for-an-amount-of-time.mdx
├── wait-for-the-next-event-loop.mdx
├── wrap-a-number-between-two-values.mdx
└── zip-multiple-arrays.mdx
Condensed preview — 316 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (221K chars).
[
{
"path": ".gitignore",
"chars": 10,
"preview": ".DS_Store\n"
},
{
"path": "LICENSE",
"chars": 1064,
"preview": "MIT License\n\nCopyright (c) 2020 phuoc-ng\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\no"
},
{
"path": "README.md",
"chars": 495,
"preview": "# Favorite single line of code\n\nWhat's your favorite JavaScript single LOC (line of code)? Let me know!\n\n## Contributing"
},
{
"path": "contents/add-am-pm-suffix-to-an-hour.mdx",
"chars": 590,
"preview": "---\ncategory: Date Time\ncreated: '2021-02-20'\ntitle: Add AM PM suffix to an hour\nupdated: '2021-10-13'\n---\n\n**JavaScript"
},
{
"path": "contents/add-an-ordinal-suffix-to-a-number.mdx",
"chars": 637,
"preview": "---\ncategory: Number\ncreated: '2020-05-16'\ntitle: Add an ordinal suffix to a number\nupdated: '2021-10-13'\n---\n\n**JavaScr"
},
{
"path": "contents/box-handler.mdx",
"chars": 941,
"preview": "---\ncategory: Function\ncontributors:\n - Valeriy Arbachakov\ncreated: '2020-07-15'\ntitle: Box handler\nupdated: '2020-08"
},
{
"path": "contents/calculate-fibonacci-numbers.mdx",
"chars": 571,
"preview": "---\ncategory: Number\ncreated: '2020-05-16'\ntitle: Calculate Fibonacci numbers\nupdated: '2021-10-13'\n---\n\n**JavaScript ve"
},
{
"path": "contents/calculate-the-angle-of-a-line-defined-by-two-points.mdx",
"chars": 673,
"preview": "---\ncategory: Math\ncreated: '2021-04-08'\ntitle: Calculate the angle of a line defined by two points\nupdated: '2021-10-13"
},
{
"path": "contents/calculate-the-average-of-arguments.mdx",
"chars": 432,
"preview": "---\ncategory: Number\ncreated: '2020-05-05'\ntitle: Calculate the average of arguments\nupdated: '2021-10-13'\n---\n\n**JavaSc"
},
{
"path": "contents/calculate-the-distance-between-two-points.mdx",
"chars": 469,
"preview": "---\ncategory: Math\ncreated: '2021-04-05'\ntitle: Calculate the distance between two points\nupdated: '2021-10-13'\n---\n\n**J"
},
{
"path": "contents/calculate-the-distance-to-the-bottom-of-a-page.mdx",
"chars": 925,
"preview": "---\ncategory: DOM\ncreated: '2023-08-23'\ndescription: one-liner function to calculate how far you are from the bottom of "
},
{
"path": "contents/calculate-the-division-of-arguments.mdx",
"chars": 424,
"preview": "---\ncategory: Number\ncreated: '2020-05-05'\ntitle: Calculate the division of arguments\nupdated: '2021-10-13'\n---\n\n**JavaS"
},
{
"path": "contents/calculate-the-factorial-of-a-number.mdx",
"chars": 485,
"preview": "---\ncategory: Number\ncreated: '2020-05-19'\ntitle: Calculate the factorial of a number\nupdated: '2021-10-13'\n---\n\n**JavaS"
},
{
"path": "contents/calculate-the-linear-interpolation-between-two-numbers.mdx",
"chars": 643,
"preview": "---\ncategory: Math\ncreated: '2021-05-24'\ntitle: Calculate the linear interpolation between two numbers\nupdated: '2021-10"
},
{
"path": "contents/calculate-the-midpoint-between-two-points.mdx",
"chars": 619,
"preview": "---\ncategory: Math\ncreated: '2021-04-10'\nopenGraphCover: /og/1-loc/calculate-midpoint-two-points.png\ntitle: Calculate th"
},
{
"path": "contents/calculate-the-midpoint-of-a-given-range.mdx",
"chars": 513,
"preview": "---\ncategory: Math\ncreated: '2023-12-08'\nopenGraphCover: /og/1-loc/calculate-midpoint-given-range.png\ntitle: Calculate t"
},
{
"path": "contents/calculate-the-mod-of-collection-index.mdx",
"chars": 426,
"preview": "---\ncategory: Number\ncontributors:\n - marcobiedermann\ncreated: '2020-05-08'\ntitle: Calculate the mod of collection in"
},
{
"path": "contents/calculate-the-number-of-difference-days-between-two-dates.mdx",
"chars": 580,
"preview": "---\ncategory: Date Time\ncreated: '2020-04-19'\ntitle: Calculate the number of difference days between two dates\nupdated: "
},
{
"path": "contents/calculate-the-number-of-months-between-two-dates.mdx",
"chars": 691,
"preview": "---\ncategory: Date Time\ncontributors:\n - kwaimind\ncreated: '2020-07-27'\ntitle: Calculate the number of months between"
},
{
"path": "contents/calculate-the-remainder-of-division-of-arguments.mdx",
"chars": 426,
"preview": "---\ncategory: Number\ncreated: '2020-05-05'\ntitle: Calculate the remainder of division of arguments\nupdated: '2021-10-13'"
},
{
"path": "contents/calculate-the-sum-of-arguments.mdx",
"chars": 379,
"preview": "---\ncategory: Number\ncreated: '2020-05-05'\ntitle: Calculate the sum of arguments\nupdated: '2021-10-13'\n---\n\n**JavaScript"
},
{
"path": "contents/capitalize-a-string.mdx",
"chars": 895,
"preview": "---\ncategory: String\ncontributors:\n - Edmon Narmetov\n - fahimfaisaal\ncreated: '2023-04-11'\ntitle: Capitalize a str"
},
{
"path": "contents/cast-a-value-as-an-array.mdx",
"chars": 450,
"preview": "---\ncategory: Array\ntitle: Cast a value as an array\ncreated: '2021-04-04'\nupdated: '2021-10-22'\n---\n\n**JavaScript versio"
},
{
"path": "contents/check-if-a-character-is-a-digit.mdx",
"chars": 852,
"preview": "---\ncategory: Validator\ncreated: '2021-10-22'\ntitle: Check if a character is a digit\n---\n\n**JavaScript version**\n\n```js "
},
{
"path": "contents/check-if-a-date-is-a-weekday.mdx",
"chars": 372,
"preview": "---\ncategory: Validator\ncreated: '2021-02-25'\ntitle: Check if a date is a weekday\nupdated: '2021-10-13'\n---\n\n**JavaScrip"
},
{
"path": "contents/check-if-a-date-is-a-weekend.mdx",
"chars": 372,
"preview": "---\ncategory: Validator\ncreated: '2021-02-25'\ntitle: Check if a date is a weekend\nupdated: '2021-10-13'\n---\n\n**JavaScrip"
},
{
"path": "contents/check-if-a-date-is-between-two-dates.mdx",
"chars": 503,
"preview": "---\ncategory: Validator\ncreated: '2020-04-19'\ntitle: Check if a date is between two dates\nupdated: '2021-10-13'\n---\n\n**J"
},
{
"path": "contents/check-if-a-date-is-today.mdx",
"chars": 440,
"preview": "---\ncategory: Validator\ncreated: '2020-05-05'\ntitle: Check if a date is today\nupdated: '2021-10-13'\n---\n\n**JavaScript ve"
},
{
"path": "contents/check-if-a-date-occurs-in-the-current-year.mdx",
"chars": 442,
"preview": "---\ncategory: Validator\ncreated: '2021-04-13'\ntitle: Check if a date occurs in the current year\nupdated: '2021-10-13'\n--"
},
{
"path": "contents/check-if-a-flat-array-has-duplicate-values.mdx",
"chars": 765,
"preview": "---\ncategory: Validator\ncreated: '2021-02-25'\ntitle: Check if a flat array has duplicate values\nupdated: '2022-01-26'\n--"
},
{
"path": "contents/check-if-a-given-dom-rect-is-contained-within-another-dom-rect.mdx",
"chars": 1127,
"preview": "---\ncategory: DOM\ncreated: '2023-12-11'\nopenGraphCover: /og/1-loc/check-given-dom-rect-contained-within-another-dom-rect"
},
{
"path": "contents/check-if-a-given-integer-is-a-prime-number.mdx",
"chars": 549,
"preview": "---\ncategory: Validator\ncreated: '2020-04-19'\ntitle: Check if a given integer is a prime number\nupdated: '2021-10-13'\n--"
},
{
"path": "contents/check-if-a-number-is-a-power-of-2.mdx",
"chars": 422,
"preview": "---\ncategory: Validator\ncreated: '2020-04-19'\ntitle: Check if a number is a power of 2\nupdated: '2021-10-13'\n---\n\n**Java"
},
{
"path": "contents/check-if-a-number-is-even.mdx",
"chars": 765,
"preview": "---\ncategory: Validator\ncontributors:\n - chety\n - ietienam\n - Vadim-Moshev\n - marcobiedermann\ncreated: '2020"
},
{
"path": "contents/check-if-a-number-is-in-a-given-range.mdx",
"chars": 642,
"preview": "---\ncategory: Validator\ncreated: '2020-06-04'\ntitle: Check if a number is in a given range\nupdated: '2021-10-13'\n---\n\n**"
},
{
"path": "contents/check-if-a-number-is-negative.mdx",
"chars": 545,
"preview": "---\ncategory: Validator\ncontributors:\n - sadirde\n - tugsanunlu\ncreated: '2020-05-07'\ntitle: Check if a number is n"
},
{
"path": "contents/check-if-a-number-is-odd.mdx",
"chars": 635,
"preview": "---\ncategory: Validator\ncontributors:\n - ietienam\n - Namysh\n - marcobiedermann\ncreated: '2020-05-06'\ntitle: Che"
},
{
"path": "contents/check-if-a-number-is-positive.mdx",
"chars": 432,
"preview": "---\ncategory: Validator\ncontributors:\n - tugsanunlu\ncreated: '2020-05-07'\ntitle: Check if a number is positive\nupdate"
},
{
"path": "contents/check-if-a-path-is-relative.mdx",
"chars": 528,
"preview": "---\ncategory: String\ncreated: '2020-05-15'\ntitle: Check if a path is relative\nupdated: '2021-10-13'\n---\n\n**JavaScript ve"
},
{
"path": "contents/check-if-a-point-is-inside-a-rectangle.mdx",
"chars": 634,
"preview": "---\ncategory: Math\ncreated: '2021-04-05'\ntitle: Check if a point is inside a rectangle\nupdated: '2021-10-13'\n---\n\n**Java"
},
{
"path": "contents/check-if-a-rectangle-contains-other-one.mdx",
"chars": 590,
"preview": "---\ncategory: Math\ncreated: '2021-04-08'\ntitle: Check if a rectangle contains other one\nupdated: '2021-10-13'\n---\n\n**Jav"
},
{
"path": "contents/check-if-a-rectangle-overlaps-other-one.mdx",
"chars": 590,
"preview": "---\ncategory: Math\ncreated: '2021-04-08'\ntitle: Check if a rectangle overlaps other one\nupdated: '2021-10-13'\n---\n\n**Jav"
},
{
"path": "contents/check-if-a-string-consists-of-a-repeated-character-sequence.mdx",
"chars": 669,
"preview": "---\ncategory: String\ncreated: '2021-04-21'\ntitle: Check if a string consists of a repeated character sequence\nupdated: '"
},
{
"path": "contents/check-if-a-string-contains-lower-case-characters.mdx",
"chars": 503,
"preview": "---\ncategory: Validator\ncreated: '2020-05-16'\ntitle: Check if a string contains lower case characters\nupdated: '2021-10-"
},
{
"path": "contents/check-if-a-string-contains-only-ascii-characters.mdx",
"chars": 343,
"preview": "---\ncategory: Validator\ncreated: '2020-06-09'\ntitle: Check if a string contains only ASCII characters\nupdated: '2021-10-"
},
{
"path": "contents/check-if-a-string-contains-only-digits.mdx",
"chars": 560,
"preview": "---\ncategory: Validator\ncreated: '2020-05-09'\ntitle: Check if a string contains only digits\nupdated: '2021-10-13'\n---\n\n*"
},
{
"path": "contents/check-if-a-string-contains-only-letters-and-numbers.mdx",
"chars": 597,
"preview": "---\ncategory: Validator\ncreated: '2020-06-08'\ntitle: Check if a string contains only letters and numbers\nupdated: '2021-"
},
{
"path": "contents/check-if-a-string-contains-only-letters.mdx",
"chars": 488,
"preview": "---\ncategory: Validator\ncreated: '2020-06-07'\ntitle: Check if a string contains only letters\nupdated: '2021-10-13'\n---\n\n"
},
{
"path": "contents/check-if-a-string-contains-upper-case-characters.mdx",
"chars": 503,
"preview": "---\ncategory: Validator\ncreated: '2020-05-16'\ntitle: Check if a string contains upper case characters\nupdated: '2021-10-"
},
{
"path": "contents/check-if-a-string-contains-whitespace.mdx",
"chars": 466,
"preview": "---\ncategory: Validator\ncreated: '2020-04-19'\ntitle: Check if a string contains whitespace\nupdated: '2021-10-13'\n---\n\n**"
},
{
"path": "contents/check-if-a-string-is-a-hexadecimal-color.mdx",
"chars": 589,
"preview": "---\ncategory: Validator\ncreated: '2020-06-09'\ntitle: Check if a string is a hexadecimal color\nupdated: '2021-10-13'\n---\n"
},
{
"path": "contents/check-if-a-string-is-a-hexadecimal-number.mdx",
"chars": 725,
"preview": "---\ncategory: Validator\ncreated: '2020-06-10'\ntitle: Check if a string is a hexadecimal number\nupdated: '2021-10-13'\n---"
},
{
"path": "contents/check-if-a-string-is-a-mongo-db-object-id.mdx",
"chars": 655,
"preview": "---\ncategory: Validator\ncreated: '2021-04-10'\ntitle: Check if a string is a MongoDB ObjectId\nupdated: '2021-10-13'\n---\n\n"
},
{
"path": "contents/check-if-a-string-is-a-palindrome.mdx",
"chars": 506,
"preview": "---\ncategory: String\ncontributors:\n - marcobiedermann\ncreated: '2020-05-18'\ntitle: Check if a string is a palindrome\n"
},
{
"path": "contents/check-if-a-string-is-an-octal-number.mdx",
"chars": 331,
"preview": "---\ncategory: Validator\ncreated: '2021-04-10'\ntitle: Check if a string is an octal number\nupdated: '2021-10-13'\n---\n\n**J"
},
{
"path": "contents/check-if-a-string-is-lower-case.mdx",
"chars": 340,
"preview": "---\ncategory: Validator\ncreated: '2020-04-19'\ntitle: Check if a string is lower case\nupdated: '2021-10-13'\n---\n\n**JavaSc"
},
{
"path": "contents/check-if-a-string-is-upper-case.mdx",
"chars": 340,
"preview": "---\ncategory: Validator\ncreated: '2020-04-19'\ntitle: Check if a string is upper case\nupdated: '2021-10-13'\n---\n\n**JavaSc"
},
{
"path": "contents/check-if-a-url-is-absolute.mdx",
"chars": 566,
"preview": "---\ncategory: String\ncreated: '2020-05-15'\ntitle: Check if a URL is absolute\nupdated: '2021-10-13'\n---\n\n**JavaScript ver"
},
{
"path": "contents/check-if-a-value-is-a-business-identifier-code.mdx",
"chars": 401,
"preview": "---\ncategory: Validator\ncreated: '2021-04-10'\ntitle: Check if a value is a business identifier code\nupdated: '2021-10-13"
},
{
"path": "contents/check-if-a-value-is-a-function.mdx",
"chars": 475,
"preview": "---\ncategory: Function\ncreated: '2020-05-15'\ntitle: Check if a value is a function\n---\n\n**JavaScript version**\n\n```js is"
},
{
"path": "contents/check-if-a-value-is-a-generator-function.mdx",
"chars": 387,
"preview": "---\ncategory: Function\ncreated: '2020-05-15'\ntitle: Check if a value is a generator function\n---\n\n**JavaScript version**"
},
{
"path": "contents/check-if-a-value-is-a-number.mdx",
"chars": 399,
"preview": "---\ncategory: Validator\ncontributors:\n - nbayramberdiyev\ncreated: '2020-04-23'\ntitle: Check if a value is a number\nup"
},
{
"path": "contents/check-if-a-value-is-a-plain-object.mdx",
"chars": 768,
"preview": "---\ncategory: Validator\ncreated: '2020-05-13'\ntitle: Check if a value is a plain object\nupdated: '2021-10-13'\n---\n\n**Jav"
},
{
"path": "contents/check-if-a-value-is-a-regular-expression.mdx",
"chars": 406,
"preview": "---\ncategory: Validator\ncreated: '2020-05-14'\ntitle: Check if a value is a regular expression\nupdated: '2021-10-13'\n---\n"
},
{
"path": "contents/check-if-a-value-is-a-string.mdx",
"chars": 532,
"preview": "---\ncategory: Validator\ncreated: '2020-06-05'\ntitle: Check if a value is a string\nupdated: '2021-10-13'\n---\n\n**JavaScrip"
},
{
"path": "contents/check-if-a-value-is-an-async-function.mdx",
"chars": 412,
"preview": "---\ncategory: Function\ncreated: '2020-05-15'\ntitle: Check if a value is an async function\n---\n\n**JavaScript version**\n\n`"
},
{
"path": "contents/check-if-a-value-is-an-object.mdx",
"chars": 480,
"preview": "---\ncategory: Validator\ncreated: '2020-05-13'\ntitle: Check if a value is an object\nupdated: '2021-10-13'\n---\n\n**JavaScri"
},
{
"path": "contents/check-if-a-value-is-base32-encoded.mdx",
"chars": 391,
"preview": "---\ncategory: Validator\ncreated: '2021-04-10'\ntitle: Check if a value is base32 encoded\nupdated: '2021-10-13'\n---\n\n**Jav"
},
{
"path": "contents/check-if-a-value-is-base58-encoded.mdx",
"chars": 403,
"preview": "---\ncategory: Validator\ncreated: '2021-04-10'\ntitle: Check if a value is base58 encoded\nupdated: '2021-10-13'\n---\n\n**Jav"
},
{
"path": "contents/check-if-a-value-is-base64-encoded.mdx",
"chars": 481,
"preview": "---\ncategory: Validator\ncreated: '2021-04-10'\ntitle: Check if a value is base64 encoded\nupdated: '2021-10-13'\n---\n\n**Jav"
},
{
"path": "contents/check-if-a-value-is-nil.mdx",
"chars": 318,
"preview": "---\ncategory: Validator\ncontributors:\n - JeromeDeLeon\ncreated: '2020-05-06'\ntitle: Check if a value is nil\nupdated: '"
},
{
"path": "contents/check-if-a-year-is-leap-year.mdx",
"chars": 604,
"preview": "---\ncategory: Validator\ncreated: '2020-04-19'\ntitle: Check if a year is leap year\nupdated: '2021-10-13'\n---\n\n**JavaScrip"
},
{
"path": "contents/check-if-all-array-elements-are-equal-to-a-given-value.mdx",
"chars": 803,
"preview": "---\ncategory: Validator\ncontributors:\n - contributorpw\n - tugsanunlu\ncreated: '2020-05-08'\ntitle: Check if all arr"
},
{
"path": "contents/check-if-all-items-in-an-array-are-equal.mdx",
"chars": 696,
"preview": "---\ncategory: Validator\ncontributors:\n - manu2504\n - glennfaison\ncreated: '2020-04-19'\ntitle: Check if all items i"
},
{
"path": "contents/check-if-an-array-contains-a-value-matching-some-criterias.mdx",
"chars": 1020,
"preview": "---\ncategory: Validator\ncontributors:\n - chety\n - nemanjapesic\n - 31piy\n - aethernet\ncreated: '2020-05-10'\nt"
},
{
"path": "contents/check-if-an-array-is-empty.mdx",
"chars": 490,
"preview": "---\ncategory: Array\ncontributors:\n - inoyakaigor\n - elkarouani\ncreated: '2020-06-23'\ntitle: Check if an array is e"
},
{
"path": "contents/check-if-an-array-is-not-empty.mdx",
"chars": 527,
"preview": "---\ncategory: Validator\ncontributors:\n - fenilgandhi\n - marcobiedermann\ncreated: '2020-05-06'\ntitle: Check if an a"
},
{
"path": "contents/check-if-an-array-is-subset-of-other-array.mdx",
"chars": 790,
"preview": "---\ncategory: Validator\ncontributors:\n - lupu60\n - Rupesh Jaiswal\ncreated: '2020-05-10'\ntitle: Check if an array i"
},
{
"path": "contents/check-if-an-element-has-css-overflow.mdx",
"chars": 1166,
"preview": "---\ncategory: DOM\ncreated: '2023-12-15'\nopenGraphCover: /og/1-loc/check-element-has-css-overflow.png\ntags: CSS overflow,"
},
{
"path": "contents/check-if-an-element-has-overflow.mdx",
"chars": 1262,
"preview": "---\ncategory: DOM\ncreated: '2023-12-16'\nopenGraphCover: /og/1-loc/check-element-has-overflow.png\ntitle: Check if an elem"
},
{
"path": "contents/check-if-an-element-is-a-descendant-of-another.mdx",
"chars": 371,
"preview": "---\ncategory: DOM\ncreated: '2020-04-19'\ntitle: Check if an element is a descendant of another\nupdated: '2021-10-13'\n---\n"
},
{
"path": "contents/check-if-an-element-is-focused.mdx",
"chars": 329,
"preview": "---\ncategory: DOM\ncreated: '2020-04-19'\ntitle: Check if an element is focused\nupdated: '2021-10-13'\n---\n\n**JavaScript ve"
},
{
"path": "contents/check-if-an-object-is-a-promise.mdx",
"chars": 514,
"preview": "---\ncategory: Validator\ncontributors:\n - quantumsheep\ncreated: '2020-05-06'\ntitle: Check if an object is a Promise\nup"
},
{
"path": "contents/check-if-an-object-is-an-array.mdx",
"chars": 306,
"preview": "---\ncategory: Validator\ncreated: '2020-04-19'\ntitle: Check if an object is an array\nupdated: '2021-10-13'\n---\n\n**JavaScr"
},
{
"path": "contents/check-if-an-object-is-empty.mdx",
"chars": 599,
"preview": "---\ncategory: Validator\ncontributors:\n - robinpokorny\ncreated: '2020-04-19'\ntitle: Check if an object is empty\nupdate"
},
{
"path": "contents/check-if-multiple-objects-are-equal.mdx",
"chars": 610,
"preview": "---\ncategory: Object\ncontributors:\n - tugsanunlu\ncreated: '2020-05-20'\ntitle: Check if multiple objects are equal\nupd"
},
{
"path": "contents/check-if-the-code-is-running-in-jest.mdx",
"chars": 406,
"preview": "---\ncategory: Misc\ncreated: '2022-06-18'\ntitle: Check if the code is running in Jest\n---\n\n**JavaScript version**\n\n```js "
},
{
"path": "contents/check-if-the-code-is-running-in-node-js.mdx",
"chars": 428,
"preview": "---\ncategory: Misc\ncreated: '2020-05-02'\ntitle: Check if the code is running in NodeJS\nupdated: '2021-10-13'\n---\n\n**Java"
},
{
"path": "contents/check-if-the-code-is-running-in-the-browser.mdx",
"chars": 379,
"preview": "---\ncategory: Misc\ncreated: '2020-05-02'\ntitle: Check if the code is running in the browser\nupdated: '2021-10-13'\n---\n\n*"
},
{
"path": "contents/check-if-the-touch-events-are-supported.mdx",
"chars": 512,
"preview": "---\ncategory: DOM\ncreated: '2020-04-25'\ntitle: Check if the touch events are supported\nupdated: '2021-10-13'\n---\n\n**Java"
},
{
"path": "contents/check-if-two-dom-rects-intersect.mdx",
"chars": 813,
"preview": "---\ncategory: DOM\ncreated: '2023-12-12'\nopenGraphCover: /og/1-loc/check-two-dom-rects-intersect.png\ntitle: Check if two "
},
{
"path": "contents/check-if-two-strings-are-anagram.mdx",
"chars": 686,
"preview": "---\ncategory: String\ncontributors:\n - mahdiyar\ncreated: '2020-05-07'\ntitle: Check if two strings are anagram\nupdated:"
},
{
"path": "contents/check-if-user-scrolls-to-the-bottom-of-the-page.mdx",
"chars": 480,
"preview": "---\ncategory: DOM\ncreated: '2021-04-10'\ntitle: Check if user scrolls to the bottom of the page\nupdated: '2021-10-13'\n---"
},
{
"path": "contents/clamp-a-number-between-two-values.mdx",
"chars": 678,
"preview": "---\ncategory: Number\ncontributors:\n - r-i-c-h\ncreated: '2020-05-05'\ntitle: Clamp a number between two values\nupdated:"
},
{
"path": "contents/clear-all-cookies.mdx",
"chars": 757,
"preview": "---\ncategory: Misc\ncontributors:\n - iamandrewluca\ncreated: '2021-04-20'\ntitle: Clear all cookies\nupdated: '2021-10-13"
},
{
"path": "contents/clone-an-array.mdx",
"chars": 1023,
"preview": "---\ncategory: Array\ncontributors:\n - tahseenio\ncreated: '2020-05-07'\ntitle: Clone an array\nupdated: '2022-06-27'\n---\n"
},
{
"path": "contents/compare-two-arrays-regardless-of-order.mdx",
"chars": 718,
"preview": "---\ncategory: Array\ncontributors:\n - Rupesh Jaiswal\n - robinpokorny\n - dauom\n - elkarouani\ncreated: '2020-05"
},
{
"path": "contents/compare-two-arrays.mdx",
"chars": 690,
"preview": "---\ncategory: Array\ncreated: '2020-05-05'\ntitle: Compare two arrays\nupdated: '2021-10-22'\n---\n\n**JavaScript version**\n\n`"
},
{
"path": "contents/compare-two-dates.mdx",
"chars": 452,
"preview": "---\ncategory: Date Time\ncreated: '2020-04-19'\ntitle: Compare two dates\nupdated: '2021-10-13'\n---\n\n**JavaScript version**"
},
{
"path": "contents/compare-two-dom-rects-for-size-and-position-match.mdx",
"chars": 449,
"preview": "---\ncategory: DOM\ncreated: '2023-12-10'\nopenGraphCover: /og/1-loc/compare-two-dom-rects-size-position-match.png\ntitle: C"
},
{
"path": "contents/compose-functions-from-left-to-right.mdx",
"chars": 630,
"preview": "---\ncategory: Function\ncreated: '2020-05-12'\ntitle: Compose functions from left to right\n---\n\n**JavaScript version**\n\n``"
},
{
"path": "contents/compose-functions.mdx",
"chars": 625,
"preview": "---\ncategory: Function\ncreated: '2020-05-07'\ntitle: Compose functions\n---\n\n**JavaScript version**\n\n```js compose.js\n// C"
},
{
"path": "contents/compute-the-greatest-common-divisor-between-two-numbers.mdx",
"chars": 401,
"preview": "---\ncategory: Number\ncreated: '2020-04-23'\ntitle: Compute the greatest common divisor between two numbers\nupdated: '2021"
},
{
"path": "contents/convert-3-digits-color-to-6-digits-color.mdx",
"chars": 710,
"preview": "---\ncategory: Misc\ncreated: '2021-02-20'\ntitle: Convert 3 digits color to 6 digits color\nupdated: '2021-10-13'\n---\n\n**Ja"
},
{
"path": "contents/convert-a-base64-encoded-string-to-an-uint8-array.mdx",
"chars": 550,
"preview": "---\ncategory: String\ncreated: '2021-11-11'\ntitle: Convert a base64 encoded string to an uint8 array\n---\n\n**JavaScript ve"
},
{
"path": "contents/convert-a-date-to-yyyy-mm-dd-format.mdx",
"chars": 485,
"preview": "---\ncategory: Date Time\ncontributors:\n - ValchanOficial\ncreated: '2020-04-19'\ntitle: 'Convert a date to YYYY-MM-DD fo"
},
{
"path": "contents/convert-a-lab-color-to-an-lch-color.mdx",
"chars": 658,
"preview": "---\ncategory: Misc\ncreated: '2023-11-10'\nopenGraphCover: /og/1-loc/convert-lab-color-lch-color.png\ntitle: Convert a LAB "
},
{
"path": "contents/convert-a-letter-to-associate-emoji.mdx",
"chars": 501,
"preview": "---\ncategory: String\ncreated: '2020-08-02'\ntitle: Convert a letter to associate emoji\nupdated: '2021-10-13'\n---\n\n**JavaS"
},
{
"path": "contents/convert-a-number-to-equivalent-characters.mdx",
"chars": 670,
"preview": "---\ncategory: Number\ncreated: '2020-05-27'\ntitle: Convert a number to equivalent characters\nupdated: '2021-10-13'\n---\n\n*"
},
{
"path": "contents/convert-a-string-to-camel-case.mdx",
"chars": 666,
"preview": "---\ncategory: String\ncreated: '2020-05-16'\ntitle: Convert a string to camelCase\nupdated: '2021-10-13'\n---\n\n**JavaScript "
},
{
"path": "contents/convert-a-string-to-number.mdx",
"chars": 336,
"preview": "---\ncategory: Number\ncreated: '2020-04-19'\ntitle: Convert a string to number\nupdated: '2021-10-13'\n---\n\n**JavaScript ver"
},
{
"path": "contents/convert-a-string-to-pascal-case.mdx",
"chars": 664,
"preview": "---\ncategory: String\ncreated: '2020-05-15'\ntitle: Convert a string to PascalCase\nupdated: '2021-10-13'\n---\n\n**JavaScript"
},
{
"path": "contents/convert-a-string-to-url-slug.mdx",
"chars": 569,
"preview": "---\ncategory: String\ncreated: '2020-05-04'\ntitle: Convert a string to URL slug\nupdated: '2021-10-13'\n---\n\n**JavaScript v"
},
{
"path": "contents/convert-a-windows-file-path-to-unix-path.mdx",
"chars": 547,
"preview": "---\ncategory: String\ncreated: '2020-05-15'\ntitle: Convert a Windows file path to Unix path\nupdated: '2021-10-13'\n---\n\n**"
},
{
"path": "contents/convert-an-array-of-objects-to-a-single-object.mdx",
"chars": 1180,
"preview": "---\ncategory: Array\ncontributors:\n - ChoukseyKhushbu\n - wenyangliu\ncreated: '2020-05-04'\ntitle: Convert an array o"
},
{
"path": "contents/convert-an-array-of-strings-to-numbers.mdx",
"chars": 551,
"preview": "---\ncategory: Array\ncontributors:\n - jonrandy\ncreated: '2020-04-23'\ntitle: Convert an array of strings to numbers\nupd"
},
{
"path": "contents/convert-an-lch-color-to-a-lab-color.mdx",
"chars": 634,
"preview": "---\ncategory: Misc\ncreated: '2023-11-10'\nopenGraphCover: /og/1-loc/convert-lch-color-lab-color.png\ntitle: Convert an LCH"
},
{
"path": "contents/convert-an-uint8-array-to-a-base64-encoded-string.mdx",
"chars": 920,
"preview": "---\ncategory: String\ncreated: '2021-11-11'\ntitle: Convert an uint8 array to a base64 encoded string\n---\n\n**JavaScript ve"
},
{
"path": "contents/convert-camel-case-to-kebab-case-and-vice-versa.mdx",
"chars": 738,
"preview": "---\ncategory: String\ncreated: '2020-05-12'\ntitle: 'Convert camelCase to kebab-case and vice versa'\nupdated: '2021-10-13'"
},
{
"path": "contents/convert-celsius-to-fahrenheit.mdx",
"chars": 526,
"preview": "---\ncategory: Misc\ncontributors:\n - mizanmahi\ncreated: '2020-05-09'\ntitle: Convert Celsius to Fahrenheit\nupdated: '20"
},
{
"path": "contents/convert-cookie-to-object.mdx",
"chars": 332,
"preview": "---\ncategory: Misc\ncontributors:\n - João Luís Ribeiro Augusto\ncreated: '2020-06-27'\ntitle: Convert cookie to object\n-"
},
{
"path": "contents/convert-decimal-to-binary-recursively.mdx",
"chars": 479,
"preview": "---\ncategory: Number\ncontributors:\n - philosophercode\ncreated: '2020-12-11'\ntitle: Convert decimal to binary recursiv"
},
{
"path": "contents/convert-degrees-to-radians.mdx",
"chars": 321,
"preview": "---\ncategory: Math\ncreated: '2020-05-16'\ntitle: Convert degrees to radians\nupdated: '2021-10-13'\n---\n\n**JavaScript versi"
},
{
"path": "contents/convert-fahrenheit-to-celsius.mdx",
"chars": 480,
"preview": "---\ncategory: Misc\ncreated: '2021-04-08'\ntitle: Convert Fahrenheit to Celsius\nupdated: '2021-10-13'\n---\n\n**JavaScript ve"
},
{
"path": "contents/convert-hex-to-rgb.mdx",
"chars": 977,
"preview": "---\ncategory: Misc\ncreated: '2020-04-19'\ntitle: Convert hex to rgb\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n``"
},
{
"path": "contents/convert-radians-to-degrees.mdx",
"chars": 317,
"preview": "---\ncategory: Math\ncreated: '2021-04-05'\ntitle: Convert radians to degrees\nupdated: '2021-10-13'\n---\n\n**JavaScript versi"
},
{
"path": "contents/convert-rgb-color-to-hex.mdx",
"chars": 1040,
"preview": "---\ncategory: Misc\ncreated: '2020-04-19'\ntitle: Convert rgb color to hex\nupdated: '2021-10-13'\n---\n\n**JavaScript version"
},
{
"path": "contents/convert-seconds-to-hh-mm-ss-format.mdx",
"chars": 1071,
"preview": "---\ncategory: Date Time\ncreated: '2020-05-15'\ntitle: 'Convert seconds to hh:mm:ss format'\nupdated: '2021-10-13'\n---\n\n**J"
},
{
"path": "contents/convert-snake-case-to-camel-case.mdx",
"chars": 512,
"preview": "---\ncategory: String\ncreated: '2020-05-12'\ntitle: 'Convert snake_case to camelCase'\nupdated: '2021-10-13'\n---\n\n**JavaScr"
},
{
"path": "contents/convert-the-name-of-an-excel-column-to-number.mdx",
"chars": 694,
"preview": "---\ncategory: String\ncreated: '2020-05-25'\ntitle: Convert the name of an Excel column to number\nupdated: '2021-10-13'\n--"
},
{
"path": "contents/convert-url-parameters-to-object.mdx",
"chars": 952,
"preview": "---\ncategory: Misc\ncreated: '2021-02-01'\ntitle: Convert URL parameters to object\nupdated: '2021-10-13'\n---\n\n**JavaScript"
},
{
"path": "contents/count-by-the-properties-of-an-array-of-objects.mdx",
"chars": 965,
"preview": "---\ncategory: Array\ncreated: '2020-06-14'\ntitle: Count by the properties of an array of objects\nupdated: '2021-10-13'\n--"
},
{
"path": "contents/count-the-number-of-words-in-a-string.mdx",
"chars": 489,
"preview": "---\ncategory: String\ncreated: '2021-05-26'\ntitle: Count the number of words in a string\nupdated: '2021-10-13'\n---\n\n**Jav"
},
{
"path": "contents/count-the-occurrences-of-a-character-in-a-string.mdx",
"chars": 1215,
"preview": "---\ncategory: String\ncreated: '2021-04-19'\ntitle: Count the occurrences of a character in a string\nupdated: '2021-10-13'"
},
{
"path": "contents/count-the-occurrences-of-a-value-in-an-array.mdx",
"chars": 771,
"preview": "---\ncategory: Array\ncreated: '2020-06-11'\ntitle: Count the occurrences of a value in an array\nupdated: '2021-10-22'\n---\n"
},
{
"path": "contents/count-the-occurrences-of-array-elements.mdx",
"chars": 706,
"preview": "---\ncategory: Array\ncreated: '2020-06-11'\ntitle: Count the occurrences of array elements\nupdated: '2021-10-13'\n---\n\n**Ja"
},
{
"path": "contents/create-a-function-that-accepts-a-single-argument.mdx",
"chars": 293,
"preview": "---\ncategory: Function\ncreated: '2021-03-13'\ntitle: Create a function that accepts a single argument\n---\n\n**JavaScript v"
},
{
"path": "contents/create-an-array-of-cumulative-sum.mdx",
"chars": 896,
"preview": "---\ncategory: Array\ncreated: '2020-04-19'\ntitle: Create an array of cumulative sum\nupdated: '2021-10-13'\n---\n\n**JavaScri"
},
{
"path": "contents/create-an-array-of-numbers-in-the-given-range.mdx",
"chars": 993,
"preview": "---\ncategory: Array\ncontributors:\n - jonrandy\n - Augusto Moura\n - Tsvika10\ncreated: '2020-04-19'\ntitle: Create "
},
{
"path": "contents/create-an-empty-function.mdx",
"chars": 320,
"preview": "---\ncategory: Function\ncontributors:\n - jnields\n - naugtur\ncreated: '2020-05-07'\ntitle: Create an empty function\nu"
},
{
"path": "contents/create-an-empty-map-that-does-not-have-properties.mdx",
"chars": 284,
"preview": "---\ncategory: Object\ncreated: '2020-04-19'\ntitle: Create an empty map that does not have properties\n---\n\n**JavaScript ve"
},
{
"path": "contents/create-an-object-from-the-pairs-of-key-and-value.mdx",
"chars": 444,
"preview": "---\ncategory: Object\ncontributors:\n - robinpokorny\ncreated: '2020-05-18'\ntitle: Create an object from the pairs of ke"
},
{
"path": "contents/create-cartesian-product.mdx",
"chars": 478,
"preview": "---\ncategory: Array\ncontributors:\n - robinpokorny\ncreated: '2020-12-02'\ntitle: Create cartesian product\nupdated: '202"
},
{
"path": "contents/curry-a-function.mdx",
"chars": 451,
"preview": "---\ncategory: Function\ncreated: '2020-05-15'\ntitle: Curry a function\n---\n\n**JavaScript version**\n\n```js curry.js\nconst c"
},
{
"path": "contents/decapitalize-a-string.mdx",
"chars": 657,
"preview": "---\ncategory: String\ncreated: '2021-02-21'\ntitle: Decapitalize a string\nupdated: '2021-10-13'\n---\n\n**JavaScript version*"
},
{
"path": "contents/decode-a-jwt-token.mdx",
"chars": 988,
"preview": "---\ncategory: Misc\ncreated: '2020-05-23'\ntitle: Decode a JWT token\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n``"
},
{
"path": "contents/decode-html-entities.mdx",
"chars": 423,
"preview": "---\ncategory: String\ncreated: '2022-08-21'\ntitle: Decode HTML entities\n---\n\n**JavaScript version**\n\n```js decodeHtmlEnti"
},
{
"path": "contents/delay-the-evaluation-of-a-function.mdx",
"chars": 557,
"preview": "---\ncategory: Function\ncreated: '2020-05-12'\ntitle: Delay the evaluation of a function\n---\n\n**JavaScript version**\n\n```j"
},
{
"path": "contents/detect-dark-mode.mdx",
"chars": 396,
"preview": "---\ncategory: Misc\ncreated: '2020-05-02'\ntitle: Detect dark mode\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```j"
},
{
"path": "contents/detect-internet-explorer-browser.mdx",
"chars": 277,
"preview": "---\ncategory: DOM\ncreated: '2020-05-09'\ntitle: Detect Internet Explorer browser\nupdated: '2021-10-13'\n---\n\n**JavaScript "
},
{
"path": "contents/detect-macos-browser.mdx",
"chars": 345,
"preview": "---\ncategory: DOM\ncreated: '2020-04-19'\ntitle: Detect macOS browser\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n`"
},
{
"path": "contents/determine-one-year-from-now.mdx",
"chars": 553,
"preview": "---\ncategory: Date Time\ncreated: '2022-08-21'\ntitle: Determine one year from now\n---\n\n**JavaScript version**\n\n```js plus"
},
{
"path": "contents/easing-functions.mdx",
"chars": 2996,
"preview": "---\ncategory: Misc\ncreated: '2020-04-25'\ntitle: Easing functions\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```j"
},
{
"path": "contents/empty-an-array.mdx",
"chars": 304,
"preview": "---\ncategory: Array\ncreated: '2020-04-19'\ntitle: Empty an array\nupdated: '2021-10-22'\n---\n\n**JavaScript version**\n\n```js"
},
{
"path": "contents/emulate-a-dice-throw.mdx",
"chars": 420,
"preview": "---\ncategory: Misc\ncontributors:\n - codepo8\ncreated: '2020-05-01'\ntitle: Emulate a dice throw\nupdated: '2021-10-13'\n-"
},
{
"path": "contents/encode-a-url.mdx",
"chars": 774,
"preview": "---\ncategory: Misc\ncreated: '2020-05-03'\ntitle: Encode a URL\nupdated: '2021-10-13'\n---\n\n**JavaScript version**\n\n```js en"
},
{
"path": "contents/escape-html-special-characters.mdx",
"chars": 903,
"preview": "---\ncategory: String\ncreated: '2020-05-29'\ntitle: Escape HTML special characters\nupdated: '2021-10-13'\n---\n\n**JavaScript"
},
{
"path": "contents/execute-a-function-once.mdx",
"chars": 390,
"preview": "---\ncategory: Function\ncreated: '2020-05-13'\ntitle: Execute a function once\n---\n\n**JavaScript version**\n\n```js once.js\nc"
},
{
"path": "contents/extract-values-of-a-property-from-an-array-of-objects.mdx",
"chars": 428,
"preview": "---\ncategory: Object\ncreated: '2020-06-02'\ntitle: Extract values of a property from an array of objects\n---\n\n**JavaScrip"
},
{
"path": "contents/extract-year-month-day-hour-minute-second-and-millisecond-from-a-date.mdx",
"chars": 588,
"preview": "---\ncategory: Date Time\ncreated: '2020-04-19'\ntitle: 'Extract year, month, day, hour, minute, second and millisecond fro"
},
{
"path": "contents/find-the-closest-number-from-an-array.mdx",
"chars": 822,
"preview": "---\ncategory: Array\ncreated: '2020-05-22'\ntitle: Find the closest number from an array\nupdated: '2021-10-13'\n---\n\n**Java"
},
{
"path": "contents/find-the-index-of-the-last-matching-item-of-an-array.mdx",
"chars": 879,
"preview": "---\ncategory: Array\ncreated: '2020-12-31'\ntitle: Find the index of the last matching item of an array\nupdated: '2021-10-"
},
{
"path": "contents/find-the-index-of-the-maximum-item-of-an-array.mdx",
"chars": 531,
"preview": "---\ncategory: Array\ncreated: '2021-04-20'\ntitle: Find the index of the maximum item of an array\nupdated: '2021-10-13'\n--"
},
{
"path": "contents/find-the-index-of-the-minimum-item-of-an-array.mdx",
"chars": 533,
"preview": "---\ncategory: Array\ncreated: '2021-04-20'\ntitle: Find the index of the minimum item of an array\nupdated: '2021-10-13'\n--"
},
{
"path": "contents/find-the-length-of-the-longest-string-in-an-array.mdx",
"chars": 537,
"preview": "---\ncategory: Array\ncontributors:\n - codepo8\ncreated: '2020-04-30'\ntitle: Find the length of the longest string in an"
},
{
"path": "contents/find-the-maximum-item-of-an-array-by-given-key.mdx",
"chars": 674,
"preview": "---\ncategory: Array\ncreated: '2021-01-13'\ntitle: Find the maximum item of an array by given key\nupdated: '2021-10-13'\n--"
},
{
"path": "contents/find-the-maximum-item-of-an-array.mdx",
"chars": 289,
"preview": "---\ncategory: Array\ncreated: '2020-04-19'\ntitle: Find the maximum item of an array\nupdated: '2021-10-13'\n---\n\n**JavaScri"
},
{
"path": "contents/find-the-minimum-item-of-an-array-by-given-key.mdx",
"chars": 672,
"preview": "---\ncategory: Array\ncreated: '2021-01-13'\ntitle: Find the minimum item of an array by given key\nupdated: '2021-10-13'\n--"
},
{
"path": "contents/find-the-minimum-item-of-an-array.mdx",
"chars": 289,
"preview": "---\ncategory: Array\ncreated: '2020-04-19'\ntitle: Find the minimum item of an array\nupdated: '2021-10-13'\n---\n\n**JavaScri"
},
{
"path": "contents/flatten-an-array.mdx",
"chars": 602,
"preview": "---\ncategory: Array\ncontributors:\n - nico2che\ncreated: '2020-05-01'\ntitle: Flatten an array\nupdated: '2021-10-13'\n---"
},
{
"path": "contents/flip-the-arguments-of-a-function.mdx",
"chars": 517,
"preview": "---\ncategory: Function\ncreated: '2020-05-12'\ntitle: Flip the arguments of a function\n---\n\n**JavaScript version**\n\n```js "
},
{
"path": "contents/format-a-date-for-the-given-locale.mdx",
"chars": 533,
"preview": "---\ncategory: Date Time\ncreated: '2020-05-06'\ntitle: Format a date for the given locale\nupdated: '2021-10-13'\n---\n\n**Jav"
},
{
"path": "contents/format-a-string.mdx",
"chars": 680,
"preview": "---\ncategory: String\ncontributors:\n - david-luna\ncreated: '2021-11-10'\ntitle: Format a string\n---\n\n**JavaScript versi"
},
{
"path": "contents/generate-a-hash-of-a-string.mdx",
"chars": 750,
"preview": "---\ncategory: String\ncreated: '2021-03-21'\ntitle: Generate a hash of a string\nupdated: '2021-10-13'\n---\n\n**JavaScript ve"
},
{
"path": "contents/generate-a-random-boolean.mdx",
"chars": 315,
"preview": "---\ncategory: Random\ncreated: '2020-05-05'\ntitle: Generate a random boolean\nupdated: '2021-10-13'\n---\n\n**JavaScript vers"
},
{
"path": "contents/generate-a-random-floating-point-number-in-given-range.mdx",
"chars": 671,
"preview": "---\ncategory: Random\ncreated: '2020-05-05'\ntitle: Generate a random floating point number in given range\nupdated: '2021-"
},
{
"path": "contents/generate-a-random-hex-color.mdx",
"chars": 597,
"preview": "---\ncategory: Random\ncontributors:\n - robinpokorny\ncreated: '2020-04-19'\ntitle: Generate a random hex color\nupdated: "
},
{
"path": "contents/generate-a-random-integer-in-given-range.mdx",
"chars": 725,
"preview": "---\ncategory: Random\ncreated: '2020-05-05'\ntitle: Generate a random integer in given range\nupdated: '2021-10-13'\n---\n\n**"
},
{
"path": "contents/generate-a-random-ip-address.mdx",
"chars": 619,
"preview": "---\ncategory: Random\ncontributors:\n - PiyushSuthar\n - Comet32\ncreated: '2020-08-10'\ntitle: Generate a random IP ad"
},
{
"path": "contents/generate-a-random-sign.mdx",
"chars": 321,
"preview": "---\ncategory: Random\ncreated: '2021-04-10'\ntitle: Generate a random sign\nupdated: '2021-10-13'\n---\n\n**JavaScript version"
},
{
"path": "contents/generate-a-random-string-from-given-characters.mdx",
"chars": 700,
"preview": "---\ncategory: Random\ncreated: '2020-04-23'\ntitle: Generate a random string from given characters\nupdated: '2021-10-13'\n-"
},
{
"path": "contents/generate-a-random-string-using-node-crypto-module.mdx",
"chars": 380,
"preview": "---\ncategory: Random\ncreated: '2020-07-28'\ntitle: Generate a random string using Node crypto module\nupdated: '2021-10-13"
},
{
"path": "contents/generate-a-random-string-with-given-length.mdx",
"chars": 537,
"preview": "---\ncategory: Random\ncreated: '2020-04-23'\ntitle: Generate a random string with given length\nupdated: '2021-10-13'\n---\n\n"
},
{
"path": "contents/generate-a-random-uuid.mdx",
"chars": 311,
"preview": "---\ncategory: Random\ncontributors:\n - w3bdesign\ncreated: '2020-05-05'\ntitle: Generate a random UUID\n---\n\n**JavaScript"
},
{
"path": "contents/generate-a-weighted-random-number-in-given-range.mdx",
"chars": 1013,
"preview": "---\ncategory: Random\ncreated: '2023-08-22'\ndescription: one-liner function to generate a weighted random number in given"
},
{
"path": "contents/generate-an-array-of-alphabet-characters.mdx",
"chars": 1300,
"preview": "---\ncategory: Array\ncreated: '2021-10-22'\ntitle: Generate an array of alphabet characters\nupdated: '2021-10-22'\n---\n\n**J"
},
{
"path": "contents/generate-an-array-of-random-integers-in-a-given-range.mdx",
"chars": 655,
"preview": "---\ncategory: Random\ncreated: '2020-05-16'\ntitle: Generate an array of random integers in a given range\nupdated: '2021-1"
},
{
"path": "contents/generate-an-unique-and-increment-id.mdx",
"chars": 261,
"preview": "---\ncategory: Misc\ncreated: '2021-04-05'\ntitle: Generate an unique and increment id\n---\n\n**JavaScript version**\n\n```js u"
},
{
"path": "contents/get-a-random-item-and-remove-it-from-an-array.mdx",
"chars": 512,
"preview": "---\ncategory: Random\ncreated: '2021-01-16'\ntitle: Get a random item and remove it from an array\nupdated: '2021-10-13'\n--"
},
{
"path": "contents/get-a-random-item-from-an-array.mdx",
"chars": 382,
"preview": "---\ncategory: Random\ncontributors:\n - jonrandy\ncreated: '2020-04-19'\ntitle: Get a random item from an array\nupdated: "
},
{
"path": "contents/get-all-arrays-of-consecutive-elements.mdx",
"chars": 761,
"preview": "---\ncategory: Array\ncreated: '2021-04-10'\ntitle: Get all arrays of consecutive elements\nupdated: '2021-10-22'\n---\n\n**Jav"
},
{
"path": "contents/get-all-nth-items-of-an-array.mdx",
"chars": 541,
"preview": "---\ncategory: Array\ncreated: '2021-02-20'\ntitle: 'Get all n-th items of an array'\nupdated: '2021-10-22'\n---\n\n**JavaScrip"
},
{
"path": "contents/get-all-siblings-of-an-element.mdx",
"chars": 436,
"preview": "---\ncategory: DOM\ncreated: '2020-04-19'\ntitle: Get all siblings of an element\nupdated: '2021-10-13'\n---\n\n**JavaScript ve"
},
{
"path": "contents/get-all-subsets-of-an-array.mdx",
"chars": 614,
"preview": "---\ncategory: Array\ncreated: '2021-02-25'\ntitle: Get all subsets of an array\nupdated: '2021-10-13'\n---\n\n**JavaScript ver"
},
{
"path": "contents/get-hours-and-minutes-from-decimal-time.mdx",
"chars": 563,
"preview": "---\ncategory: Date Time\ncontributors:\n - ognjenst\ncreated: '2022-12-27'\ntitle: Get the hours and minutes from the dec"
},
{
"path": "contents/get-indices-of-a-value-in-an-array.mdx",
"chars": 819,
"preview": "---\ncategory: Array\ncreated: '2021-03-07'\ntitle: Get indices of a value in an array\nupdated: '2021-10-13'\n---\n\n**JavaScr"
},
{
"path": "contents/get-random-items-of-an-array.mdx",
"chars": 577,
"preview": "---\ncategory: Random\ncreated: '2021-01-16'\ntitle: Get random items of an array\n---\n\n**JavaScript version**\n\n```js random"
},
{
"path": "contents/get-the-arrays-of-digits-from-a-number.mdx",
"chars": 594,
"preview": "---\ncategory: Number\ncreated: '2020-05-16'\ntitle: Get the arrays of digits from a number\nupdated: '2021-10-13'\n---\n\n**Ja"
},
{
"path": "contents/get-the-average-of-an-array.mdx",
"chars": 353,
"preview": "---\ncategory: Array\ncreated: '2020-04-19'\ntitle: Get the average of an array\nupdated: '2021-10-13'\n---\n\n**JavaScript ver"
},
{
"path": "contents/get-the-base-url-without-any-parameters.mdx",
"chars": 990,
"preview": "---\ncategory: String\ncontributors:\n - shawphy\ncreated: '2020-06-20'\ntitle: Get the base URL without any parameters\nup"
}
]
// ... and 116 more files (download for full content)
About this extraction
This page contains the full source code of the phuocng/1loc GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 316 files (184.1 KB), approximately 69.9k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.