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 = {}): 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 = (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 = (arr: T[]): boolean => new Set(arr).size !== arr.length; // Or const hasDuplicateValues = (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 = (arr: T[], value: T): boolean => arr.every((item) => item === value); // Or const isEqual = (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 = (arr: T[]): boolean => arr.length > 0 && arr.every((item) => item === arr[0]); // Or const areEqual = (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 = (arr: T[], criteria: (a: T) => boolean): boolean => arr.some((v) => criteria(v)); // Or const contains = (arr: T[], criteria: (a: T) => boolean): boolean => arr.some(criteria); // Or const contains = (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 = (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 = (a: T[], b: T[]): boolean => new Set(b).size === new Set(b.concat(a)).size; // Or const isSubset = (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 = (arr: T[]): T[] => arr.slice(0); // Or const clone = (arr: T[]): T[] => [...arr]; // Or const clone = (arr: T[]): T[] => Array.from(arr); // Or const clone = (arr: T[]): T[] => arr.map((x) => x); // Or const clone = (arr: T[]): T[] => JSON.parse(JSON.stringify(arr)); // Or const clone = (arr: T[]): T[] => arr.concat([]); // Or const clone = (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 = (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 = (a: T[], b: T[]): boolean => JSON.stringify(a) === JSON.stringify(b); // Or const isEqual = (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 = , K extends keyof T>(arr: T[], key: K): Record => ( arr.reduce((a, b) => ({ ...a, [b[key]]: b }), {}) ); const toObject = , K extends keyof T>(arr: T[], key: K): Record => ( 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 => ( 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) ); ``` **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 = , K extends keyof T>(arr: T[], prop: K): Record => ( arr.reduce((prev, curr) => ((prev[curr[prop]] = ++prev[curr[prop]] || 1), prev), {} as Record) ); ``` **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 = (arr: T[], val: T): number => arr.reduce((a, v) => (v === val ? a + 1 : a), 0); // Or const countOccurrences = (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 = (arr: T[]): Record => ( arr.reduce((prev, curr) => ((prev[curr] = ++prev[curr] || 1), prev), {}as Record) ); ``` **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 = (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, '"'); // 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, '"'); // 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 = (arr: T[], predicate: (a: T) => boolean): number => arr.reduce((prev, curr, index) => (predicate(curr) ? index : prev), -1); // Or const lastIndex = (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 = , 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 = , 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 = (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 = (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 = (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 = (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 = (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 = (arr: T[], value: T): number[] => ( arr.reduce((acc, v, i) => (v === value ? [...acc, i] : acc), [] as number[]) ); // Or const indices = (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 = (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 = (arr: T[]): T[] => [...new Set(arr)]; // Or const unique = (arr: T[]): T[] => arr.filter((el, i, array) => array.indexOf(el) === i); // Or const unique = (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 = (...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 = , K extends keyof T>(arr: T[], key: K): Record => ( arr.reduce((acc, item) => ((acc[item[key]] = [...(acc[item[key]] || []), item]), acc), {} as Record) ); ``` **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 = (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([
  • A
  • ,
  • B
  • ,
  • C
  • ],
  • /
  • ); // [
  • A
  • ,
  • /
  • ,
  • B
  • ,
  • /
  • ,
  • C
  • ] ``` ================================================ 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 = (a: T[], b: T[]): T[] => a.concat(b); // Or const merge = (a: T[], b: T[]): T[] => [...a, ...b]; // Merge and remove the duplications const merge = (a: T[], b: T[]): T[] => [...new Set(a.concat(b))]; // Or const merge = (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 = (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 = >(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 = >(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 = >(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 = (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 removeFalsy.ts const removeFalsy = (arr: T[]): T[] => arr.filter(Boolean); ``` **Example** ```js example.js removeFalsy([0, 'a string', '', NaN, true, 5, undefined, 'another string', false]); // ['a string', true, 5, 'another string'] ``` ================================================ FILE: contents/remove-spaces-from-a-string.mdx ================================================ --- category: String created: '2020-05-03' title: Remove spaces from a string updated: '2021-10-13' --- **JavaScript version** ```js removeSpaces.js const removeSpaces = (str) => str.replace(/\s/g, ''); ``` **TypeScript version** ```ts removeSpaces.ts const removeSpaces = (str: string): string => str.replace(/\s/g, ''); ``` **Examples** ```js examples.js removeSpaces('hel lo wor ld'); // 'helloworld' ``` ================================================ FILE: contents/repeat-a-string.mdx ================================================ --- category: String contributors: - chety created: '2020-04-19' title: Repeat a string updated: '2021-10-13' --- **JavaScript version** ```js repeat.js const repeat = (str, numberOfTimes) => str.repeat(numberOfTimes); // Or const repeat = (str, numberOfTimes) => Array(numberOfTimes + 1).join(str); ``` **TypeScript version** ```ts repeat.ts const repeat = (str: string, numberOfTimes: number): string => str.repeat(numberOfTimes); // Or const repeat = (str: string, numberOfTimes: number): string => Array(numberOfTimes + 1).join(str); ``` ================================================ FILE: contents/repeat-an-array.mdx ================================================ --- category: Array created: '2021-07-21' title: Repeat an array updated: '2021-10-22' --- **JavaScript version** ```js repeat.js // `arr` is an array const repeat = (arr, n) => [].concat(...Array(n).fill(arr)); // Or const repeat = (arr, n) => Array(n).fill(arr).flat(); // Or const repeat = (arr, n) => Array(arr.length * n) .fill(0) .map((_, i) => arr[i % arr.length]); // Or const repeat = (arr, n) => Array.from({ length: arr.length * n }, (_, i) => arr[i % arr.length]); ``` **TypeScript version** ```ts repeat.ts const repeat = (arr: T[], n: number): T[] => [].concat(...Array(n).fill(arr)); // Or const repeat = (arr: T[], n: number): T[] => Array(n).fill(arr).flat(); // Or const repeat = (arr: T[], n: number): T[] => Array(arr.length * n) .fill(0) .map((_, i) => arr[i % arr.length]); // Or const repeat = (arr: T[], n: number): T[] => Array.from({ length: arr.length * n }, (_, i) => arr[i % arr.length]); ``` **Example** ```js example.js repeat([1, 2, 3], 3); // [1, 2, 3, 1, 2, 3, 1, 2, 3] ``` ================================================ FILE: contents/replace-all-line-breaks-with-br-elements.mdx ================================================ --- category: String created: '2020-04-19' title: Replace all line breaks with br elements updated: '2021-10-13' --- **JavaScript version** ```js nl2br.js const nl2br = (str) => str.replace(new RegExp('\r?\n', 'g'), '
    '); // In React str.split('\n').map((item, index) => ( {item}
    )); ``` **TypeScript version** ```ts nl2br.ts const nl2br = (str: string): string => str.replace(new RegExp('\r?\n', 'g'), '
    '); ``` ================================================ FILE: contents/replace-all-tab-characters-with-spaces.mdx ================================================ --- category: String created: '2021-05-27' title: Replace all tab characters with spaces updated: '2021-10-13' --- **JavaScript version** ```js replace.js const replace = (str, numSpaces = 4) => str.replaceAll('\t', ' '.repeat(numSpaces)); ``` **TypeScript version** ```ts replace.ts const replace = (str: string, numSpaces = 4): string => str.replaceAll('\t', ' '.repeat(numSpaces)); ``` ================================================ FILE: contents/replace-an-element.mdx ================================================ --- category: DOM created: '2020-04-19' title: Replace an element updated: '2021-10-13' --- **JavaScript version** ```js replace.js const replace = (ele, newEle) => ele.parentNode.replaceChild(newEle, ele); ``` **TypeScript version** ```ts replace.ts const replace = (ele: Element, newEle: Element): Element | null => ele.parentNode ? ele.parentNode.replaceChild(newEle, ele) : null; ``` ================================================ FILE: contents/replace-multiple-spaces-with-a-single-space.mdx ================================================ --- category: String created: '2020-05-09' title: Replace multiple spaces with a single space updated: '2021-10-13' --- **JavaScript version** ```js replaceSpaces.js // Replace spaces, tabs and new line characters const replaceSpaces = (str) => str.replace(/\s\s+/g, ' '); // Only replace spaces const replaceOnlySpaces = (str) => str.replace(/ +/g, ' '); ``` **TypeScript version** ```ts replaceSpaces.ts const replaceSpaces = (str: string): string => str.replace(/\s\s+/g, ' '); const replaceOnlySpaces = (str: string): string => str.replace(/ +/g, ' '); ``` **Examples** ```js examples.js replaceSpaces('this\n is \ta \rmessage'); // 'this is a message' ``` ================================================ FILE: contents/replace-the-first-given-number-of-characters-of-a-string-with-another-character.mdx ================================================ --- category: String created: '2020-06-15' title: Replace the first given number of characters of a string with another character updated: '2021-10-13' --- **JavaScript version** ```js mask.js const mask = (str, num, mask) => `${str}`.slice(num).padStart(`${str}`.length, mask); ``` **TypeScript version** ```ts mask.ts const mask = (str: string, num: number, mask: string): string => `${str}`.slice(num).padStart(`${str}`.length, mask); ``` **Examples** ```js examples.js mask(1234567890, 3, '*'); // ***4567890 ``` ================================================ FILE: contents/reverse-a-string.mdx ================================================ --- category: String created: '2020-04-19' title: Reverse a string updated: '2021-10-13' --- **JavaScript version** ```js reverse.js const reverse = (str) => str.split('').reverse().join(''); // Or const reverse = (str) => [...str].reverse().join(''); // Or const reverse = (str) => str.split('').reduce((rev, char) => `${char}${rev}`, ''); // Or const reverse = (str) => (str === '' ? '' : `${reverse(str.substr(1))}${str.charAt(0)}`); ``` **TypeScript version** ```ts reverse.ts const reverse = (str: string): string => str.split('').reverse().join(''); // Or const reverse = (str: string): string => [...str].reverse().join(''); // Or const reverse = (str: string): string => str.split('').reduce((rev, char) => `${char}${rev}`, ''); // Or const reverse = (str: string): string => (str === '' ? '' : `${reverse(str.substr(1))}${str.charAt(0)}`); ``` **Examples** ```js examples.js reverse('hello world'); // 'dlrow olleh' ``` ================================================ FILE: contents/reverse-the-order-of-lines-of-a-text.mdx ================================================ --- category: String created: '2021-05-30' title: Reverse the order of lines of a text updated: '2021-10-13' --- **JavaScript version** ```js reverseLines.js const reverseLines = (str) => str.split(/\r?\n/).reverse().join('\n'); ``` **TypeScript version** ```ts reverseLines.ts const reverseLines = (str: string): string => str.split(/\r?\n/).reverse().join('\n'); ``` **Examples** ```js examples.js reverseLines(`one two three`); /* Output */ /* three two one */ ``` ================================================ FILE: contents/round-a-number-to-a-given-number-of-digits.mdx ================================================ --- category: Number created: '2020-05-16' title: Round a number to a given number of digits updated: '2021-10-13' --- **JavaScript version** ```js round.js const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`); ``` **TypeScript version** ```ts round.ts const round = (n: number, decimals: number = 0): number => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`); ``` **Examples** ```js examples.js round(1.234567, 3); // 1.235 round(1.234567, 4); // 1.2346 ``` ================================================ FILE: contents/round-a-number-to-the-nearest-multiple-of-a-given-value.mdx ================================================ --- category: Math created: '2021-05-11' title: Round a number to the nearest multiple of a given value updated: '2021-10-13' --- **JavaScript version** ```js roundNearest.js const roundNearest = (value, nearest) => Math.round(value / nearest) * nearest; ``` **TypeScript version** ```ts roundNearest.ts const roundNearest = (value: number, nearest: number): number => Math.round(value / nearest) * nearest; ``` **Examples** ```js examples.js roundNearest(100, 30); // 90 roundNearest(200, 30); // 210 roundNearest(200, 40); // 200 ``` ================================================ FILE: contents/run-promises-in-sequence.mdx ================================================ --- category: Misc created: '2020-05-02' title: Run Promises in sequence updated: '2021-10-13' --- **JavaScript version** ```js run.js // `promises` is an array of `Promise` const run = (promises) => promises.reduce((p, c) => p.then((rp) => c.then((rc) => [...rp, rc])), Promise.resolve([])); ``` **TypeScript version** ```ts run.ts const run = (promises: Promise[]): Promise => promises.reduce((p, c) => p.then((rp) => c.then((rc) => [...rp, rc])), Promise.resolve([])); ``` **Examples** ```js examples.js run(promises).then((results) => { // `results` is an array of promise results in the same order }); ``` ================================================ FILE: contents/scroll-to-top-of-the-page.mdx ================================================ --- category: DOM created: '2020-04-19' title: Scroll to top of the page updated: '2021-10-13' --- **JavaScript version** ```js goToTop.js const goToTop = () => window.scrollTo(0, 0); ``` **TypeScript version** ```ts goToTop.ts const goToTop = (): void => window.scrollTo(0, 0); ``` ================================================ FILE: contents/serialize-form-data.mdx ================================================ --- category: DOM created: '2021-02-01' title: Serialize form data --- **JavaScript version** ```js serialize.js const serialize = (formEle) => Array.from(new FormData(formEle)).reduce( (p, [k, v]) => Object.assign({}, p, { [k]: p[k] ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v }), {} ); ``` ================================================ FILE: contents/shallow-copy-an-object.mdx ================================================ --- category: Object contributors: - Namysh created: '2020-05-13' title: Shallow copy an object updated: '2020-07-16' --- **JavaScript version** ```js shallowCopy.js const shallowCopy = obj => Object.assign({}, obj); // or const shallowCopy = obj => {...obj}; ``` ================================================ FILE: contents/show-an-element.mdx ================================================ --- category: DOM created: '2020-04-19' title: Show an element updated: '2021-10-13' --- **JavaScript version** ```js show.js const show = (ele) => (ele.style.display = ''); ``` **TypeScript version** ```ts show.ts const show = (ele: HTMLElement): string => (ele.style.display = ''); ``` ================================================ FILE: contents/shuffle-an-array.mdx ================================================ --- category: Array contributors: - elkarouani created: '2020-05-20' title: Shuffle an array updated: '2021-12-22' --- **JavaScript version** ```js shuffle.js const shuffle = (arr) => arr .map((a) => ({ sort: Math.random(), value: a })) .sort((a, b) => a.sort - b.sort) .map((a) => a.value); ``` **TypeScript version** ```ts shuffle.ts const shuffle = (arr: T[]): T[] => arr .map((a) => ({ sort: Math.random(), value: a })) .sort((a, b) => a.sort - b.sort) .map((a) => a.value); ``` **Example** ```js example.js shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); // [9, 1, 10, 6, 8, 5, 2, 3, 7, 4] ``` ================================================ FILE: contents/sort-an-array-of-dates.mdx ================================================ --- category: Date Time created: '2020-04-19' title: Sort an array of dates updated: '2021-10-13' --- **JavaScript version** ```js sortDescending.js // `arr` is an array of `Date` items const sortDescending = (arr) => arr.sort((a, b) => a.getTime() > b.getTime()); const sortAscending = (arr) => arr.sort((a, b) => a.getTime() < b.getTime()); ``` **TypeScript version** ```ts sortDescending.ts const sortDescending = (arr: Date[]): Date[] => arr.sort((a, b) => a.getTime() - b.getTime()); const sortAscending = (arr: Date[]): Date[] => arr.sort((a, b) => b.getTime() - a.getTime()); ``` ================================================ FILE: contents/sort-an-array-of-items-by-given-key.mdx ================================================ --- category: Array created: '2021-01-13' title: Sort an array of items by given key updated: '2021-10-13' --- **JavaScript version** ```js sortBy.js const sortBy = (arr, k) => arr.concat().sort((a, b) => (a[k] > b[k] ? 1 : a[k] < b[k] ? -1 : 0)); ``` **TypeScript version** ```ts sortBy.ts const sortBy = , K extends keyof T>(arr: T[], k: K): T[] => ( arr.concat().sort((a, b) => (a[k] > b[k] ? 1 : a[k] < b[k] ? -1 : 0)) ); ``` **Example** ```js example.js const people = [ { name: 'Foo', age: 42 }, { name: 'Bar', age: 24 }, { name: 'Fuzz', age: 36 }, { name: 'Baz', age: 32 }, ]; sortBy(people, 'age'); // [ // { name: 'Bar', age: 24 }, // { name: 'Baz', age: 32 }, // { name: 'Fuzz', age: 36 }, // { name: 'Foo', age: 42 }, // ] ``` ================================================ FILE: contents/sort-an-array-of-numbers.mdx ================================================ --- category: Array created: '2020-05-20' title: Sort an array of numbers updated: '2021-10-13' --- **JavaScript version** ```js sort.js const sort = (arr) => arr.sort((a, b) => a - b); ``` **TypeScript version** ```ts sort.ts const sort = (arr: number[]): number[] => arr.sort((a, b) => a - b); ``` **Example** ```js example.js sort([1, 5, 2, 4, 3]); // [1, 2, 3, 4, 5] ``` ================================================ FILE: contents/sort-an-object-by-its-properties.mdx ================================================ --- category: Object created: '2021-04-20' title: Sort an object by its properties --- **JavaScript version** ```js sort.js const sort = (obj) => Object.keys(obj) .sort() .reduce((p, c) => ((p[c] = obj[c]), p), {}); ``` **Examples** ```js examples.js const colors = { white: '#ffffff', black: '#000000', red: '#ff0000', green: '#008000', blue: '#0000ff', }; sort(colors); /* { black: '#000000', blue: '#0000ff', green: '#008000', red: '#ff0000', white: '#ffffff', } */ ``` ================================================ FILE: contents/sort-lines-of-a-text-document-in-the-alphabetical-order.mdx ================================================ --- category: String created: '2021-05-26' title: Sort lines of a text document in the alphabetical order updated: '2021-10-13' --- **JavaScript version** ```js sortLines.js const sortLines = (str) => str.split(/\r?\n/).sort().join('\n'); // Reverse the order const reverseSortedLines = (str) => str.split(/\r?\n/).sort().reverse().join('\n'); ``` **TypeScript version** ```ts sortLines.ts const sortLines = (str: string): string => str.split(/\r?\n/).sort().join('\n'); // Reverse the order const reverseSortedLines = (str: string): string => str.split(/\r?\n/).sort().reverse().join('\n'); ``` **Examples** ```js examples.js sortLines(`Thaddeus Mullen Kareem Marshall Ferdinand Valentine Hasad Lindsay Mufutau Berg Knox Tyson Kasimir Fletcher Colton Sharp Adrian Rosales Theodore Rogers`); /* Output */ /* Adrian Rosales Colton Sharp Ferdinand Valentine Hasad Lindsay Kareem Marshall Kasimir Fletcher Knox Tyson Mufutau Berg Thaddeus Mullen Theodore Rogers */ ``` ================================================ FILE: contents/sort-the-characters-of-a-string-in-the-alphabetical-order.mdx ================================================ --- category: String created: '2020-05-16' title: Sort the characters of a string in the alphabetical order updated: '2021-10-13' --- **JavaScript version** ```js sort.js const sort = (str) => str .split('') .sort((a, b) => a.localeCompare(b)) .join(''); ``` **TypeScript version** ```ts sort.ts const sort = (str: string): string => str .split('') .sort((a, b) => a.localeCompare(b)) .join(''); ``` **Examples** ```js examples.js sort('hello world'); // dehllloorw ``` ================================================ FILE: contents/split-an-array-into-chunks.mdx ================================================ --- category: Array created: '2020-05-13' title: Split an array into chunks updated: '2021-10-13' --- **JavaScript version** ```js chunk.js const chunk = (arr, size) => arr.reduce((acc, e, i) => (i % size ? acc[acc.length - 1].push(e) : acc.push([e]), acc), []); ``` **TypeScript version** ```ts chunk.ts const chunk = (arr: T[], size: number): T[][] => ( arr.reduce((acc, e, i) => (i % size ? acc[acc.length - 1].push(e) : acc.push([e]), acc), [] as T[][]) ); ``` **Examples** ```js examples.js chunk([1, 2, 3, 4, 5, 6, 7, 8], 3); // [[1, 2, 3], [4, 5, 6], [7, 8]] chunk([1, 2, 3, 4, 5, 6, 7, 8], 4); // [[1, 2, 3, 4], [5, 6, 7, 8]] ``` ================================================ FILE: contents/strip-ansi-codes-from-a-string.mdx ================================================ --- category: String created: '2020-06-07' title: Strip ANSI codes from a string updated: '2021-10-13' --- **JavaScript version** ```js stripAnsiCodes.js const stripAnsiCodes = (str) => str.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, ''); ``` **TypeScript version** ```ts stripAnsiCodes.ts const stripAnsiCodes = (str: string): string => str.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, ''); ``` **Examples** ```js examples.js stripAnsiCodes('\u001B[4mcake\u001B[0m'); // 'cake' stripAnsiCodes('\u001B[0m\u001B[4m\u001B[42m\u001B[31mfoo\u001B[39m\u001B[49m\u001B[24mfoo\u001B[0m'); // 'foofoo' ``` ================================================ FILE: contents/strip-html-from-a-given-text.mdx ================================================ --- category: DOM created: '2020-04-19' title: Strip HTML from a given text updated: '2021-10-13' --- **JavaScript version** ```js stripHtml.js const stripHtml = (html) => new DOMParser().parseFromString(html, 'text/html').body.textContent || ''; ``` **TypeScript version** ```ts stripHtml.ts const stripHtml = (html: string): string => new DOMParser().parseFromString(html, 'text/html').body.textContent || ''; ``` ================================================ FILE: contents/subtract-arguments.mdx ================================================ --- category: Number created: '2020-05-05' title: Subtract arguments updated: '2021-10-13' --- **JavaScript version** ```js subtract.js const subtract = (...args) => args.reduce((a, b) => a - b); ``` **TypeScript version** ```ts subtract.ts const subtract = (...args: number[]): number => args.reduce((a, b) => a - b); ``` **Examples** ```js examples.js subtract(1, 2, 3, 4); // -8 ``` ================================================ FILE: contents/swap-case-of-characters-in-a-string.mdx ================================================ --- category: String created: '2021-02-20' title: Swap case of characters in a string updated: '2021-10-13' --- **JavaScript version** ```js swapCase.js const swapCase = (str) => str .split('') .map((c) => (c === c.toLowerCase() ? c.toUpperCase() : c.toLowerCase())) .join(''); ``` **TypeScript version** ```ts swapCase.ts const swapCase = (str: string): string => str .split('') .map((c) => (c === c.toLowerCase() ? c.toUpperCase() : c.toLowerCase())) .join(''); ``` **Examples** ```js examples.js swapCase('Hello World'); // 'hELLO wORLD' ``` ================================================ FILE: contents/swap-the-rows-and-columns-of-a-matrix.mdx ================================================ --- category: Array created: '2020-05-24' title: Swap the rows and columns of a matrix updated: '2021-10-13' --- **JavaScript version** ```js transpose.js const transpose = (matrix) => matrix[0].map((col, i) => matrix.map((row) => row[i])); // Or const transpose = (matrix) => matrix[0].map((col, c) => matrix.map((row, r) => matrix[r][c])); // Or const transpose = (matrix) => matrix.reduce((prev, next) => next.map((item, i) => (prev[i] || []).concat(next[i])), []); ``` **TypeScript version** ```ts transpose.ts const transpose = (matrix: T[][]): T[][] => matrix[0].map((col, i) => matrix.map((row) => row[i])); // Or const transpose = (matrix: T[][]): T[][] => matrix[0].map((col, c) => matrix.map((row, r) => matrix[r][c])); // Or const transpose = (matrix: T[][]): T[][] => ( matrix.reduce((prev, next) => next.map((item, i) => (prev[i] || []).concat(next[i])), [] as T[][]) ); ``` **Examples** ```js examples.js transpose([ // [ [1, 2, 3], // [1, 4, 7], [4, 5, 6], // [2, 5, 8], [7, 8, 9], // [3, 6, 9], ]); // ] ``` ================================================ FILE: contents/swap-two-array-items.mdx ================================================ --- category: Array created: '2021-03-13' title: Swap two array items updated: '2021-10-22' --- **JavaScript version** ```js swapItems.js // `i` must be less than `j` const swapItems = (a, i, j) => (a[i] && a[j] && [...a.slice(0, i), a[j], ...a.slice(i + 1, j), a[i], ...a.slice(j + 1)]) || a; ``` **TypeScript version** ```ts swapItems.ts const swapItems = (a: T[], i: number, j: number): T[] => (a[i] && a[j] && [...a.slice(0, i), a[j], ...a.slice(i + 1, j), a[i], ...a.slice(j + 1)]) || a; ``` **Example** ```js example.js swapItems([1, 2, 3, 4, 5], 1, 4); // [1, 5, 3, 4, 2] ``` ================================================ FILE: contents/swap-two-variables.mdx ================================================ --- category: Misc created: '2020-04-19' title: Swap two variables updated: '2020-09-05' --- **JavaScript version** ```js [a, b] = [b, a]; // Or a = [b, (b = a)][0]; // Or a = ((x) => x)(b, (b = a)); // Or // (only works with numbers) a = b + ((b = a), 0); a = b * ((b = a), 1); ``` ================================================ FILE: contents/toggle-an-element.mdx ================================================ --- category: DOM contributors: - islamozbek created: '2020-04-19' title: Toggle an element updated: '2021-10-13' --- **JavaScript version** ```js toggle.js const toggle = (ele) => (ele.style.display = ele.style.display === 'none' ? 'block' : 'none'); // Or const toggle = (ele) => (ele.hidden = !ele.hidden); ``` **TypeScript version** ```ts toggle.ts const toggle = (ele: HTMLElement): string => (ele.style.display = ele.style.display === 'none' ? 'block' : 'none'); // Or const toggle = (ele: HTMLElement): boolean => (ele.hidden = !ele.hidden); ``` ================================================ FILE: contents/trim-slashes-at-the-beginning-and-the-end-of-a-string.mdx ================================================ --- category: String created: '2020-06-01' title: Trim slashes at the beginning and the end of a string updated: '2021-10-13' --- **JavaScript version** ```js trimSlashes.js const trimSlashes = (str) => str.replace(/^\/+|\/+$/g, ''); // Or const trimSlashes = (str) => str.split('/').filter(Boolean).join('/'); ``` **TypeScript version** ```ts trimSlashes.ts const trimSlashes = (str: string): string => str.replace(/^\/+|\/+$/g, ''); // Or const trimSlashes = (str: string): string => str.split('/').filter(Boolean).join('/'); ``` **Examples** ```js examples.js trimSlashes('//hello/world///'); // hello/world ``` ================================================ FILE: contents/trim-some-character.mdx ================================================ --- category: String contributors: - mahdiyar created: '2020-06-04' title: Trim some character updated: '2021-10-13' --- **JavaScript version** ```js trim.js const trim = (str, char) => str.split(char).filter(Boolean).join(); ``` **TypeScript version** ```ts trim.ts const trim = (str: string, char: string): string => str.split(char).filter(Boolean).join(); ``` **Examples** ```js examples.js trim('/hello world//', '/'); // hello world trim('"hello world"', '"'); // hello world trim(' hello world ', ' '); // hello world ``` ================================================ FILE: contents/trim-the-file-extension-from-a-file-name.mdx ================================================ --- category: String created: '2020-05-30' title: Trim the file extension from a file name updated: '2021-10-13' --- **JavaScript version** ```js trimExt.js const trimExt = (fileName) => (fileName.indexOf('.') === -1 ? fileName : fileName.split('.').slice(0, -1).join('.')); ``` **TypeScript version** ```ts trimExt.ts const trimExt = (fileName: string): string => fileName.indexOf('.') === -1 ? fileName : fileName.split('.').slice(0, -1).join('.'); ``` **Examples** ```js examples.js trimExt('document'); // document trimExt('document.pdf'); // document trimExt('document.2020.pdf'); // document.2020 ``` ================================================ FILE: contents/truncate-a-number-at-decimal.mdx ================================================ --- category: Number contributors: - onelifemedia created: '2020-08-05' title: Truncate a number at decimal updated: '2021-10-13' --- **JavaScript version** ```js truncate.js const truncate = (n) => ~~n; ``` **TypeScript version** ```ts truncate.ts const truncate = (n: number): number => ~~n; ``` **Examples** ```js examples.js truncate(25.198726354); // 25 truncate(-25.198726354); // -25 ``` ================================================ FILE: contents/truncate-a-number-to-a-given-number-of-decimal-places-without-rounding.mdx ================================================ --- category: Number contributors: - onelifemedia created: '2020-05-28' title: Truncate a number to a given number of decimal places without rounding updated: '2021-10-13' --- **JavaScript version** ```js toFixed.js const toFixed = (n, fixed) => `${n}`.match(new RegExp(`^-?\\d+(?:\.\\d{0,${fixed}})?`))[0]; // Or const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed); ``` **TypeScript version** ```ts toFixed.ts const toFixed = (n: number, fixed: number): number => +(`${n}`.match(new RegExp(`^-?\\d+(?:\.\\d{0,${fixed}})?`)) as string[])[0]; // Or const toFixed = (n: number, fixed: number): number => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed); ``` **Examples** ```js examples.js toFixed(25.198726354, 1); // 25.1 toFixed(25.198726354, 2); // 25.19 toFixed(25.198726354, 3); // 25.198 toFixed(25.198726354, 4); // 25.1987 toFixed(25.198726354, 5); // 25.19872 toFixed(25.198726354, 6); // 25.198726 ``` ================================================ FILE: contents/truncate-a-string-at-full-words.mdx ================================================ --- category: String created: '2020-05-29' title: Truncate a string at full words updated: '2021-10-13' --- **JavaScript version** ```js truncate.js const truncate = (str, max, suffix) => str.length < max ? str : `${str.substr(0, str.substr(0, max - suffix.length).lastIndexOf(' '))}${suffix}`; ``` **TypeScript version** ```ts truncate.ts const truncate = (str: string, max: number, suffix: string = '...'): string => str.length < max ? str : `${str.substr(0, str.substr(0, max - suffix.length).lastIndexOf(' '))}${suffix}`; ``` **Examples** ```js examples.js truncate('This is a long message', 20, '...'); // 'This is a long...' ``` ================================================ FILE: contents/uncurry-a-function.mdx ================================================ --- category: Function created: '2020-05-15' title: Uncurry a function --- **JavaScript version** ```js // `fn` is a curried function // `n` is the depth of parameters const uncurry = (fn, n = 1) => (...args) => ( (acc) => (args) => args.reduce((x, y) => x(y), acc) )(fn)(args.slice(0, n)); ``` **Examples** ```js examples.js const sum = (a) => (b) => (c) => a + b + c; uncurry(sum, 1)(1)(2)(3); // 6 uncurry(sum, 2)(1, 2)(3); // 6 uncurry(sum, 3)(1, 2, 3); // 6 ``` ================================================ FILE: contents/unescape-html-special-characters.mdx ================================================ --- category: String created: '2020-05-29' title: Unescape HTML special characters updated: '2021-10-13' --- **JavaScript version** ```js unescape.js const unescape = (str) => str .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/�*39;/g, "'") .replace(/"/g, '"'); ``` **TypeScript version** ```ts unescape.ts const unescape = (str: string): string => str .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/�*39;/g, "'") .replace(/"/g, '"'); ``` ================================================ FILE: contents/unzip-an-array-of-arrays.mdx ================================================ --- category: Array created: '2020-05-15' title: Unzip an array of arrays updated: '2021-10-13' --- **JavaScript version** ```js unzip.js const unzip = (arr) => arr.reduce( (acc, c) => (c.forEach((v, i) => acc[i].push(v)), acc), Array.from({ length: Math.max(...arr.map((a) => a.length)) }, (_) => []) ); ``` **Example** ```js example.js unzip([ ['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5], ]); // [['a', 'b', 'c', 'd', 'e'], [1, 2, 3, 4, 5]] /* a 1 b 2 c 3 d 4 e 5 */ ``` ================================================ FILE: contents/uppercase-the-first-character-of-each-word-in-a-string.mdx ================================================ --- category: String created: '2020-05-03' title: Uppercase the first character of each word in a string updated: '2021-10-13' --- **JavaScript version** ```js uppercaseWords.js const uppercaseWords = (str) => str .split(' ') .map((w) => `${w.charAt(0).toUpperCase()}${w.slice(1)}`) .join(' '); // Or const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase()); ``` **TypeScript version** ```ts uppercaseWords.ts const uppercaseWords = (str: string): string => str .split(' ') .map((w) => `${w.charAt(0).toUpperCase()}${w.slice(1)}`) .join(' '); // Or const uppercaseWords = (str: string): string => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase()); ``` **Examples** ```js examples.js uppercaseWords('hello world'); // 'Hello World' ``` ================================================ FILE: contents/validate-a-gregorian-date.mdx ================================================ --- category: Validator created: '2020-05-03' title: Validate a Gregorian date updated: '2021-10-13' --- **JavaScript version** ```js // `m`: the month (zero-based index) // `d`: the day // `y`: the year const isValidDate = (m, d, y) => 0 <= m && m <= 11 && 0 < y && y < 32768 && 0 < d && d <= new Date(y, m, 0).getDate(); ``` **TypeScript version** ```ts isValidDate.ts const isValidDate = (m: number, d: number, y: number): boolean => 0 <= m && m <= 11 && 0 < y && y < 32768 && 0 < d && d <= new Date(y, m, 0).getDate(); ``` ================================================ FILE: contents/wait-for-an-amount-of-time.mdx ================================================ --- category: Misc contributors: - furkankose created: '2020-05-06' openGraphCover: /og/1-loc/wait-amount-time.png title: Wait for an amount of time updated: '2021-10-13' --- **JavaScript version** ```js wait.js const wait = async (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)); ``` **TypeScript version** ```ts wait.ts const wait = async (milliseconds: number) => new Promise((resolve) => setTimeout(resolve, milliseconds)); ``` ## See also - [Wait for the next event loop](https://phuoc.ng/collection/1-loc/wait-for-the-next-event-loop/) ================================================ FILE: contents/wait-for-the-next-event-loop.mdx ================================================ --- category: Misc created: '2023-12-14' openGraphCover: /og/1-loc/wait-next-event-loop.png tags: event loop, next tick, requestAnimationFrame, setTimeout(0) title: Wait for the next event loop --- In JavaScript, there may be times when you need to wait for the next event loop before executing a block of code. For example, you might want to ensure that certain updates to the DOM have been completed before running a function. To do this, you can create a `Promise` that resolves after the next event loop. The following `waitForNextLoop()` function uses `setTimeout` with a delay of `0` to queue a function call on the event loop. When this function is called, it resolves the `Promise`. This `Promise` can be used in other parts of your code to ensure that the next event loop has completed before proceeding. ```js waitForNextLoop.js const waitForNextLoop = async () => new Promise((resolve) => { setTimeout(() => { resolve(); }, 0); }); ``` Here's an example of how you can use the `waitForNextLoop()` function: ```js waitForNextLoop().then(() => { console.log('This code runs after the next event loop!'); }); ``` By using `requestAnimationFrame` instead of `setTimeout`, we can provide some performance benefits. This is because `requestAnimationFrame` allows the browser to optimize when to run your code. It also ensures that your code runs at a consistent frame rate, which can help prevent jank and stuttering in animations. Here's the modified version: ```ts nextTick.ts const nextTick = (): Promise => new Promise((resolve) => requestAnimationFrame(() => resolve())); ``` When you call `nextTick()`, it returns a new `Promise` that resolves when the next animation frame is ready to be rendered. This ensures that any updates to the UI or animations will be finished before the `Promise` resolves. Here's an example of how to use the `nextTick()` function: ```js async function doSomethingAsync() { await nextTick(); // Code here will run after the next animation frame } doSomethingAsync(); ``` ## See also - [setTimeout(0) vs requestAnimationFrame](https://phuoc.ng/collection/this-vs-that/set-timeout-zero-vs-request-animation-frame/) - [Wait for an amount of time](https://phuoc.ng/collection/1-loc/wait-for-an-amount-of-time/) ================================================ FILE: contents/wrap-a-number-between-two-values.mdx ================================================ --- category: Number contributors: - iamandrewluca created: '2021-12-13' title: Wrap a number between two values --- **JavaScript version** ```js wrap.js const wrap = (num, min, max) => ((((num - min) % (max - min)) + (max - min)) % (max - min)) + min; ``` **TypeScript version** ```ts const wrap = (num: number, min: number, max: number): number => ((((num - min) % (max - min)) + (max - min)) % (max - min)) + min; ``` **Examples** ```js examples.js wrap(11, 10, 25); // 11 wrap(10, 10, 25); // 10 wrap(9, 10, 25); // 25 wrap(24, 10, 25); // 24 wrap(25, 10, 25); // 25 wrap(26, 10, 25); // 10 ``` ## See also - [Clamp a number between two values](https://phuoc.ng/collection/1-loc/clamp-a-number-between-two-values/) ================================================ FILE: contents/zip-multiple-arrays.mdx ================================================ --- category: Array created: '2020-05-13' title: Zip multiple arrays updated: '2021-10-13' --- **JavaScript version** ```js zip.js const zip = (...arr) => Array.from({ length: Math.max(...arr.map((a) => a.length)) }, (_, i) => arr.map((a) => a[i])); ``` **Example** ```js example.js zip(['a', 'b', 'c', 'd', 'e'], [1, 2, 3, 4, 5]); // [['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5]] /* Does it look like a zipper? a 1 b 2 c 3 d 4 e 5 */ ```