├── .gitignore ├── contents ├── identity-function.mdx ├── go-back-to-the-previous-page.mdx ├── get-the-selected-text.mdx ├── shallow-copy-an-object.mdx ├── detect-internet-explorer-browser.mdx ├── generate-an-unique-and-increment-id.mdx ├── show-an-element.mdx ├── redirect-to-another-page.mdx ├── scroll-to-top-of-the-page.mdx ├── create-an-empty-map-that-does-not-have-properties.mdx ├── get-the-value-of-a-cookie.mdx ├── find-the-maximum-item-of-an-array.mdx ├── find-the-minimum-item-of-an-array.mdx ├── generate-a-random-uuid.mdx ├── serialize-form-data.mdx ├── check-if-an-object-is-an-array.mdx ├── create-a-function-that-accepts-a-single-argument.mdx ├── swap-two-variables.mdx ├── convert-radians-to-degrees.mdx ├── generate-a-random-boolean.mdx ├── generate-a-random-sign.mdx ├── convert-cookie-to-object.mdx ├── convert-degrees-to-radians.mdx ├── create-an-empty-function.mdx ├── empty-an-array.mdx ├── check-if-a-value-is-nil.mdx ├── get-the-sum-of-an-array-of-numbers.mdx ├── check-if-an-element-is-focused.mdx ├── get-the-current-timestamp-in-seconds.mdx ├── partially-apply-a-function.mdx ├── get-the-file-extension-from-a-file-name.mdx ├── check-if-a-string-is-an-octal-number.mdx ├── detect-macos-browser.mdx ├── get-the-value-at-given-path-of-an-object.mdx ├── check-if-a-string-is-lower-case.mdx ├── check-if-a-string-is-upper-case.mdx ├── get-the-average-of-an-array.mdx ├── check-if-a-string-contains-only-ascii-characters.mdx ├── convert-a-string-to-number.mdx ├── get-the-current-quarter-of-a-date.mdx ├── check-if-a-date-is-a-weekday.mdx ├── check-if-a-date-is-a-weekend.mdx ├── detect-dark-mode.mdx ├── check-if-an-element-is-a-descendant-of-another.mdx ├── multiply-arguments.mdx ├── replace-an-element.mdx ├── check-if-the-code-is-running-in-the-browser.mdx ├── get-a-random-item-from-an-array.mdx ├── check-if-a-value-is-a-generator-function.mdx ├── check-if-a-value-is-base32-encoded.mdx ├── generate-a-random-string-using-node-crypto-module.mdx ├── get-union-of-arrays.mdx ├── replace-all-tab-characters-with-spaces.mdx ├── calculate-the-sum-of-arguments.mdx ├── check-if-a-value-is-a-number.mdx ├── check-if-the-code-is-running-in-jest.mdx ├── insert-given-html-after-an-element.mdx ├── sort-an-array-of-numbers.mdx ├── check-if-a-value-is-base58-encoded.mdx ├── decode-html-entities.mdx ├── get-the-first-date-in-the-month-of-a-date.mdx ├── get-the-last-date-in-the-month-of-a-date.mdx ├── initialize-the-current-date-but-set-time-to-midnight.mdx ├── subtract-arguments.mdx ├── check-if-a-value-is-a-business-identifier-code.mdx ├── check-if-a-value-is-a-regular-expression.mdx ├── insert-given-html-before-an-element.mdx ├── strip-html-from-a-given-text.mdx ├── check-if-a-value-is-an-async-function.mdx ├── execute-a-function-once.mdx ├── omit-a-subset-of-properties-from-an-object.mdx ├── pick-a-subset-of-properties-of-an-object.mdx ├── get-the-length-of-a-string-in-bytes.mdx ├── reload-the-current-page.mdx ├── get-the-number-of-days-in-given-month.mdx ├── check-if-a-date-is-today.mdx ├── check-if-the-code-is-running-in-node-js.mdx ├── get-the-position-of-an-element-relative-to-the-document.mdx ├── get-unique-arr-obj.mdx ├── get-all-siblings-of-an-element.mdx ├── remove-spaces-from-a-string.mdx ├── truncate-a-number-at-decimal.mdx ├── get-the-timezone-string.mdx ├── calculate-the-division-of-arguments.mdx ├── check-if-a-date-occurs-in-the-current-year.mdx ├── compute-the-greatest-common-divisor-between-two-numbers.mdx ├── check-if-a-number-is-a-power-of-2.mdx ├── curry-a-function.mdx ├── emulate-a-dice-throw.mdx ├── calculate-the-average-of-arguments.mdx ├── calculate-the-remainder-of-division-of-arguments.mdx ├── compare-two-dates.mdx ├── cast-a-value-as-an-array.mdx ├── check-if-a-number-is-positive.mdx ├── compare-two-dom-rects-for-size-and-position-match.mdx ├── calculate-the-mod-of-collection-index.mdx ├── extract-values-of-a-property-from-an-array-of-objects.mdx ├── immutably-rename-object-keys.mdx ├── check-if-a-value-is-a-function.mdx ├── check-if-a-value-is-base64-encoded.mdx ├── get-the-file-name-from-a-url.mdx ├── calculate-the-distance-between-two-points.mdx ├── check-if-user-scrolls-to-the-bottom-of-the-page.mdx ├── create-an-object-from-the-pairs-of-key-and-value.mdx ├── convert-fahrenheit-to-celsius.mdx ├── get-the-weekday-of-a-date.mdx ├── check-if-a-date-is-between-two-dates.mdx ├── check-if-a-string-contains-whitespace.mdx ├── logical-xor-operator.mdx ├── invert-keys-and-values-of-an-object.mdx ├── check-if-a-value-is-an-object.mdx ├── convert-decimal-to-binary-recursively.mdx ├── create-cartesian-product.mdx ├── normalize-file-path-slashes.mdx ├── zip-multiple-arrays.mdx ├── check-if-an-object-is-a-promise.mdx ├── check-if-the-touch-events-are-supported.mdx ├── convert-a-date-to-yyyy-mm-dd-format.mdx ├── count-the-number-of-words-in-a-string.mdx ├── make-the-first-character-of-a-string-lowercase.mdx ├── calculate-the-factorial-of-a-number.mdx ├── calculate-the-midpoint-of-a-given-range.mdx ├── check-if-a-string-contains-only-letters.mdx ├── check-if-an-array-is-empty.mdx ├── convert-a-letter-to-associate-emoji.mdx ├── convert-snake-case-to-camel-case.mdx ├── get-the-value-of-a-param-from-a-url.mdx ├── check-if-a-string-is-a-palindrome.mdx ├── replace-all-line-breaks-with-br-elements.mdx ├── validate-a-gregorian-date.mdx ├── check-if-a-string-contains-lower-case-characters.mdx ├── check-if-a-string-contains-upper-case-characters.mdx ├── remove-falsy-values-from-array.mdx ├── reverse-the-order-of-lines-of-a-text.mdx ├── get-the-center-point-of-a-dom-rect.mdx ├── round-a-number-to-a-given-number-of-digits.mdx ├── uncurry-a-function.mdx ├── flip-the-arguments-of-a-function.mdx ├── get-a-random-item-and-remove-it-from-an-array.mdx ├── check-if-a-path-is-relative.mdx ├── check-if-a-value-is-a-string.mdx ├── determine-one-year-from-now.mdx ├── check-if-an-array-is-not-empty.mdx ├── convert-celsius-to-fahrenheit.mdx ├── format-a-date-for-the-given-locale.mdx ├── get-all-nth-items-of-an-array.mdx ├── repeat-a-string.mdx ├── trim-some-character.mdx ├── convert-a-base64-encoded-string-to-an-uint8-array.mdx ├── find-the-index-of-the-maximum-item-of-an-array.mdx ├── find-the-index-of-the-minimum-item-of-an-array.mdx ├── generate-a-random-string-with-given-length.mdx ├── remove-duplicate-values-in-an-array.mdx ├── convert-a-windows-file-path-to-unix-path.mdx ├── delay-the-evaluation-of-a-function.mdx ├── toggle-an-element.mdx ├── find-the-length-of-the-longest-string-in-an-array.mdx ├── get-the-rank-of-an-array-of-numbers.mdx ├── pick-random-lines-from-a-text-document.mdx ├── replace-the-first-given-number-of-characters-of-a-string-with-another-character.mdx ├── check-if-a-url-is-absolute.mdx ├── memoize-a-function.mdx ├── round-a-number-to-the-nearest-multiple-of-a-given-value.mdx ├── check-if-a-given-integer-is-a-prime-number.mdx ├── get-hours-and-minutes-from-decimal-time.mdx ├── get-random-items-of-an-array.mdx ├── sort-an-array-of-dates.mdx ├── wait-for-an-amount-of-time.mdx ├── get-the-day-of-the-year-from-a-date.mdx ├── check-if-a-number-is-negative.mdx ├── calculate-fibonacci-numbers.mdx ├── convert-an-array-of-strings-to-numbers.mdx ├── sort-an-object-by-its-properties.mdx ├── sort-the-characters-of-a-string-in-the-alphabetical-order.mdx ├── swap-two-array-items.mdx ├── check-if-a-string-contains-only-digits.mdx ├── check-if-an-object-is-empty.mdx ├── generate-a-random-hex-color.mdx ├── check-if-a-year-is-leap-year.mdx ├── convert-a-string-to-url-slug.mdx ├── add-am-pm-suffix-to-an-hour.mdx ├── calculate-the-number-of-difference-days-between-two-dates.mdx ├── check-if-a-rectangle-contains-other-one.mdx ├── check-if-a-rectangle-overlaps-other-one.mdx ├── check-if-a-string-is-a-hexadecimal-color.mdx ├── unzip-an-array-of-arrays.mdx ├── partition-an-array-based-on-a-condition.mdx ├── flatten-an-array.mdx ├── get-all-subsets-of-an-array.mdx ├── compose-functions.mdx ├── get-the-arrays-of-digits-from-a-number.mdx ├── check-if-a-string-contains-only-letters-and-numbers.mdx ├── check-if-multiple-objects-are-equal.mdx ├── remove-duplicate-lines-of-a-text-document.mdx ├── trim-the-file-extension-from-a-file-name.mdx ├── unescape-html-special-characters.mdx ├── run-promises-in-sequence.mdx ├── calculate-the-midpoint-between-two-points.mdx ├── extract-year-month-day-hour-minute-second-and-millisecond-from-a-date.mdx ├── get-the-total-number-of-days-in-a-year.mdx ├── intersperse-element-between-elements.mdx ├── swap-case-of-characters-in-a-string.mdx ├── compose-functions-from-left-to-right.mdx ├── get-the-intersection-of-arrays.mdx ├── calculate-the-linear-interpolation-between-two-numbers.mdx ├── truncate-a-string-at-full-words.mdx ├── check-if-a-number-is-in-a-given-range.mdx ├── convert-an-lch-color-to-a-lab-color.mdx ├── add-an-ordinal-suffix-to-a-number.mdx ├── check-if-a-string-is-a-mongo-db-object-id.mdx ├── generate-a-random-ip-address.mdx ├── split-an-array-into-chunks.mdx ├── decapitalize-a-string.mdx ├── trim-slashes-at-the-beginning-and-the-end-of-a-string.mdx ├── check-if-a-point-is-inside-a-rectangle.mdx ├── convert-a-string-to-camel-case.mdx ├── convert-a-string-to-pascal-case.mdx ├── generate-an-array-of-random-integers-in-a-given-range.mdx ├── convert-a-lab-color-to-an-lch-color.mdx ├── generate-a-random-floating-point-number-in-given-range.mdx ├── get-the-intersection-range-between-two-ranges.mdx ├── insert-an-element-before-other-one.mdx ├── normalize-the-ratio-of-a-number-in-a-range.mdx ├── shuffle-an-array.mdx ├── format-a-string.mdx ├── check-if-a-number-is-odd.mdx ├── check-if-a-string-consists-of-a-repeated-character-sequence.mdx ├── hide-an-element.mdx ├── strip-ansi-codes-from-a-string.mdx ├── calculate-the-angle-of-a-line-defined-by-two-points.mdx ├── check-if-two-strings-are-anagram.mdx ├── clamp-a-number-between-two-values.mdx ├── compare-two-arrays.mdx ├── replace-multiple-spaces-with-a-single-space.mdx ├── calculate-the-number-of-months-between-two-dates.mdx ├── find-the-minimum-item-of-an-array-by-given-key.mdx ├── count-the-occurrences-of-array-elements.mdx ├── find-the-maximum-item-of-an-array-by-given-key.mdx ├── generate-a-random-integer-in-given-range.mdx ├── get-the-tomorrow-date.mdx ├── convert-a-number-to-equivalent-characters.mdx ├── get-the-yesterday-date.mdx ├── insert-an-element-after-other-one.mdx ├── redirect-the-page-to-https-if-it-is-in-http.mdx ├── get-the-first-defined-and-non-null-argument.mdx ├── remove-empty-lines-of-a-text-document.mdx ├── check-if-all-items-in-an-array-are-equal.mdx ├── generate-a-random-string-from-given-characters.mdx ├── convert-the-name-of-an-excel-column-to-number.mdx ├── compare-two-arrays-regardless-of-order.mdx ├── convert-3-digits-color-to-6-digits-color.mdx ├── check-if-a-string-is-a-hexadecimal-number.mdx ├── convert-camel-case-to-kebab-case-and-vice-versa.mdx ├── get-all-arrays-of-consecutive-elements.mdx ├── get-the-unique-values-of-an-array.mdx ├── generate-a-hash-of-a-string.mdx ├── wrap-a-number-between-two-values.mdx ├── get-the-number-of-a-character-in-a-string.mdx ├── check-if-a-flat-array-has-duplicate-values.mdx ├── check-if-a-value-is-a-plain-object.mdx ├── clear-all-cookies.mdx ├── encode-a-url.mdx ├── prepend-a-line-number-to-each-line-of-a-text-document.mdx ├── count-the-occurrences-of-a-value-in-an-array.mdx ├── merge-two-arrays.mdx ├── check-if-two-dom-rects-intersect.mdx ├── check-if-an-array-is-subset-of-other-array.mdx ├── find-the-closest-number-from-an-array.mdx ├── get-indices-of-a-value-in-an-array.mdx ├── check-if-a-number-is-even.mdx ├── check-if-all-array-elements-are-equal-to-a-given-value.mdx ├── sort-an-array-of-items-by-given-key.mdx ├── get-the-month-name-of-a-date.mdx ├── uppercase-the-first-character-of-each-word-in-a-string.mdx ├── check-if-a-character-is-a-digit.mdx ├── find-the-index-of-the-last-matching-item-of-an-array.mdx ├── calculate-the-distance-to-the-bottom-of-a-page.mdx ├── capitalize-a-string.mdx ├── escape-html-special-characters.mdx ├── box-handler.mdx └── prefix-an-integer-with-zeros.mdx ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | -------------------------------------------------------------------------------- /contents/identity-function.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Function 3 | created: '2020-05-07' 4 | title: Identity function 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js identity.js 10 | const identity = (x) => x; 11 | ``` 12 | -------------------------------------------------------------------------------- /contents/go-back-to-the-previous-page.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: DOM 3 | created: '2020-04-19' 4 | title: Go back to the previous page 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js 11 | history.back(); 12 | 13 | // Or 14 | history.go(-1); 15 | ``` 16 | -------------------------------------------------------------------------------- /contents/get-the-selected-text.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: DOM 3 | created: '2020-04-19' 4 | title: Get the selected text 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js getSelectedText.js 11 | const getSelectedText = () => window.getSelection().toString(); 12 | ``` 13 | -------------------------------------------------------------------------------- /contents/shallow-copy-an-object.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Object 3 | contributors: 4 | - Namysh 5 | created: '2020-05-13' 6 | title: Shallow copy an object 7 | updated: '2020-07-16' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js shallowCopy.js 13 | const shallowCopy = obj => Object.assign({}, obj); 14 | 15 | // or 16 | const shallowCopy = obj => {...obj}; 17 | ``` 18 | -------------------------------------------------------------------------------- /contents/detect-internet-explorer-browser.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: DOM 3 | created: '2020-05-09' 4 | title: Detect Internet Explorer browser 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isIE.js 11 | const isIE = !!document.documentMode; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts isIE.ts 17 | const isIE = !!(document as any).documentMode; 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/generate-an-unique-and-increment-id.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Misc 3 | created: '2021-04-05' 4 | title: Generate an unique and increment id 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js uid.js 10 | const uid = (() => ((id = 0), () => id++))(); 11 | ``` 12 | 13 | **Examples** 14 | 15 | ```js examples.js 16 | uid(); // 0 17 | uid(); // 1 18 | uid(); // 2 19 | uid(); // 3 20 | ``` 21 | -------------------------------------------------------------------------------- /contents/show-an-element.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: DOM 3 | created: '2020-04-19' 4 | title: Show an element 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js show.js 11 | const show = (ele) => (ele.style.display = ''); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts show.ts 17 | const show = (ele: HTMLElement): string => (ele.style.display = ''); 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/redirect-to-another-page.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: DOM 3 | created: '2020-04-19' 4 | title: Redirect to another page 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js goTo.js 11 | const goTo = (url) => (location.href = url); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts goTo.ts 17 | const goTo = (url: string): string => (location.href = url); 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/scroll-to-top-of-the-page.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: DOM 3 | created: '2020-04-19' 4 | title: Scroll to top of the page 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js goToTop.js 11 | const goToTop = () => window.scrollTo(0, 0); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts goToTop.ts 17 | const goToTop = (): void => window.scrollTo(0, 0); 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/create-an-empty-map-that-does-not-have-properties.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Object 3 | created: '2020-04-19' 4 | title: Create an empty map that does not have properties 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js map.js 10 | // `map` doesn't have any properties 11 | const map = Object.create(null); 12 | 13 | // The following `map` has `__proto__` property 14 | // const map = {}; 15 | ``` 16 | -------------------------------------------------------------------------------- /contents/get-the-value-of-a-cookie.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Misc 3 | created: '2020-05-28' 4 | title: Get the value of a cookie 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js cookie.js 10 | const cookie = (name) => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift(); 11 | ``` 12 | 13 | **Examples** 14 | 15 | ```js examples.js 16 | cookie('_ga'); // GA1.2.825309271.1581874719 17 | ``` 18 | -------------------------------------------------------------------------------- /contents/find-the-maximum-item-of-an-array.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | created: '2020-04-19' 4 | title: Find the maximum item of an array 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js max.js 11 | const max = (arr) => Math.max(...arr); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts max.ts 17 | const max = (arr: number[]): number => Math.max(...arr); 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/find-the-minimum-item-of-an-array.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | created: '2020-04-19' 4 | title: Find the minimum item of an array 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js min.js 11 | const min = (arr) => Math.min(...arr); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts min.ts 17 | const min = (arr: number[]): number => Math.min(...arr); 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/generate-a-random-uuid.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Random 3 | contributors: 4 | - w3bdesign 5 | created: '2020-05-05' 6 | title: Generate a random UUID 7 | --- 8 | 9 | **JavaScript version** 10 | 11 | ```js uuid.js 12 | const uuid = (a) => 13 | a 14 | ? (a ^ ((Math.random() * 16) >> (a / 4))).toString(16) 15 | : ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, uuid); 16 | ``` 17 | -------------------------------------------------------------------------------- /contents/serialize-form-data.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: DOM 3 | created: '2021-02-01' 4 | title: Serialize form data 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js serialize.js 10 | const serialize = (formEle) => 11 | Array.from(new FormData(formEle)).reduce( 12 | (p, [k, v]) => Object.assign({}, p, { [k]: p[k] ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v }), 13 | {} 14 | ); 15 | ``` 16 | -------------------------------------------------------------------------------- /contents/check-if-an-object-is-an-array.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2020-04-19' 4 | title: Check if an object is an array 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isArray.js 11 | const isArray = (obj) => Array.isArray(obj); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts isArray.ts 17 | const isArray = (obj: any): boolean => Array.isArray(obj); 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/create-a-function-that-accepts-a-single-argument.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Function 3 | created: '2021-03-13' 4 | title: Create a function that accepts a single argument 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js unary.js 10 | const unary = (fn) => (arg) => fn(arg); 11 | ``` 12 | 13 | **Examples** 14 | 15 | ```js examples.js 16 | ['1', '2', '3', '4', '5'].map(unary(parseInt)); // [1, 2, 3, 4, 5] 17 | ``` 18 | -------------------------------------------------------------------------------- /contents/swap-two-variables.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Misc 3 | created: '2020-04-19' 4 | title: Swap two variables 5 | updated: '2020-09-05' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js 11 | [a, b] = [b, a]; 12 | 13 | // Or 14 | a = [b, (b = a)][0]; 15 | 16 | // Or 17 | a = ((x) => x)(b, (b = a)); 18 | 19 | // Or 20 | // (only works with numbers) 21 | a = b + ((b = a), 0); 22 | 23 | a = b * ((b = a), 1); 24 | ``` 25 | -------------------------------------------------------------------------------- /contents/convert-radians-to-degrees.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Math 3 | created: '2021-04-05' 4 | title: Convert radians to degrees 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js radsToDegs.js 11 | const radsToDegs = (rad) => (rad * 180) / Math.PI; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts radsToDegs.ts 17 | const radsToDegs = (rad: number): number => (rad * 180) / Math.PI; 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/generate-a-random-boolean.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Random 3 | created: '2020-05-05' 4 | title: Generate a random boolean 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js randomBoolean.js 11 | const randomBoolean = () => Math.random() >= 0.5; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts randomBoolean.ts 17 | const randomBoolean = (): boolean => Math.random() >= 0.5; 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/generate-a-random-sign.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Random 3 | created: '2021-04-10' 4 | title: Generate a random sign 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js randomSign.js 11 | const randomSign = () => (Math.random() >= 0.5 ? 1 : -1); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts randomSign.ts 17 | const randomSign = (): number => (Math.random() >= 0.5 ? 1 : -1); 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/convert-cookie-to-object.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Misc 3 | contributors: 4 | - João Luís Ribeiro Augusto 5 | created: '2020-06-27' 6 | title: Convert cookie to object 7 | --- 8 | 9 | **JavaScript version** 10 | 11 | ```js cookies.js 12 | const cookies = document.cookie 13 | .split(';') 14 | .map((item) => item.split('=')) 15 | .reduce((acc, [k, v]) => (acc[k.trim().replace('"', '')] = v) && acc, {}); 16 | ``` 17 | -------------------------------------------------------------------------------- /contents/convert-degrees-to-radians.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Math 3 | created: '2020-05-16' 4 | title: Convert degrees to radians 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js degsToRads.js 11 | const degsToRads = (deg) => (deg * Math.PI) / 180.0; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts degsToRads.ts 17 | const degsToRads = (deg: number): number => (deg * Math.PI) / 180.0; 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/create-an-empty-function.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Function 3 | contributors: 4 | - jnields 5 | - naugtur 6 | created: '2020-05-07' 7 | title: Create an empty function 8 | updated: '2020-05-27' 9 | --- 10 | 11 | **JavaScript version** 12 | 13 | ```js noop.js 14 | const noop = () => {}; 15 | 16 | // Or 17 | const noop = Function(); 18 | // calling Function() might be detected as using eval by some security tools 19 | ``` 20 | -------------------------------------------------------------------------------- /contents/empty-an-array.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | created: '2020-04-19' 4 | title: Empty an array 5 | updated: '2021-10-22' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js empty.js 11 | const empty = (arr) => (arr.length = 0); 12 | 13 | // Or 14 | arr = []; 15 | ``` 16 | 17 | **TypeScript version** 18 | 19 | ```ts empty.ts 20 | const empty = (arr: T[]) => (arr.length = 0); 21 | 22 | // Or 23 | arr = []; 24 | ``` 25 | -------------------------------------------------------------------------------- /contents/check-if-a-value-is-nil.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | contributors: 4 | - JeromeDeLeon 5 | created: '2020-05-06' 6 | title: Check if a value is nil 7 | updated: '2021-10-13' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js isNil.js 13 | const isNil = (value) => value == null; 14 | ``` 15 | 16 | **TypeScript version** 17 | 18 | ```ts isNil.ts 19 | const isNil = (value: any): boolean => value == null; 20 | ``` 21 | -------------------------------------------------------------------------------- /contents/get-the-sum-of-an-array-of-numbers.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | created: '2020-04-19' 4 | title: Get the sum of an array of numbers 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js sum.js 11 | const sum = (arr) => arr.reduce((a, b) => a + b, 0); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts sum.ts 17 | const sum = (arr: number[]): number => arr.reduce((a, b) => a + b, 0); 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/check-if-an-element-is-focused.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: DOM 3 | created: '2020-04-19' 4 | title: Check if an element is focused 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js hasFocus.js 11 | const hasFocus = (ele) => ele === document.activeElement; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts hasFocus.ts 17 | const hasFocus = (ele: Node): boolean => ele === document.activeElement; 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/get-the-current-timestamp-in-seconds.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Date Time 3 | created: '2020-04-19' 4 | title: Get the current timestamp in seconds 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js ts.js 11 | const ts = () => Math.floor(new Date().getTime() / 1000); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts ts.ts 17 | const ts = (): number => Math.floor(new Date().getTime() / 1000); 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/partially-apply-a-function.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Function 3 | created: '2020-05-13' 4 | title: Partially apply a function 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js partial.js 10 | const partial = 11 | (fn, ...a) => 12 | (...b) => 13 | fn(...a, ...b); 14 | ``` 15 | 16 | **Examples** 17 | 18 | ```js examples.js 19 | const sum = (x, y) => x + y; 20 | const inc = partial(sum, 1); 21 | inc(9); // 10 22 | ``` 23 | -------------------------------------------------------------------------------- /contents/get-the-file-extension-from-a-file-name.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2020-04-19' 4 | title: Get the file extension from a file name 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js ext.js 11 | const ext = (fileName) => fileName.split('.').pop(); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts ext.ts 17 | const ext = (fileName: string): string => fileName.split('.').pop(); 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/check-if-a-string-is-an-octal-number.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2021-04-10' 4 | title: Check if a string is an octal number 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isOctal.js 11 | const isOctal = (str) => /^(0o)?[0-7]+$/i.test(str); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts isOctal.ts 17 | const isOctal = (str: string): boolean => /^(0o)?[0-7]+$/i.test(str); 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/detect-macos-browser.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: DOM 3 | created: '2020-04-19' 4 | title: Detect macOS browser 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isMacBrowser.js 11 | const isMacBrowser = /Mac|iPod|iPhone|iPad/.test(navigator.platform); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts isMacBrowser.ts 17 | const isMacBrowser: boolean = /Mac|iPod|iPhone|iPad/.test(navigator.platform); 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/get-the-value-at-given-path-of-an-object.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Object 3 | created: '2020-05-13' 4 | title: Get the value at given path of an object 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js getValue.js 10 | const getValue = (path, obj) => path.split('.').reduce((acc, c) => acc && acc[c], obj); 11 | ``` 12 | 13 | **Examples** 14 | 15 | ```js examples.js 16 | getValue('a.b', { a: { b: 'Hello World' } }); // 'Hello World'; 17 | ``` 18 | -------------------------------------------------------------------------------- /contents/check-if-a-string-is-lower-case.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2020-04-19' 4 | title: Check if a string is lower case 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isLowerCase.js 11 | const isLowerCase = (str) => str === str.toLowerCase(); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts isLowerCase.ts 17 | const isLowerCase = (str: string): boolean => str === str.toLowerCase(); 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/check-if-a-string-is-upper-case.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2020-04-19' 4 | title: Check if a string is upper case 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isUpperCase.js 11 | const isUpperCase = (str) => str === str.toUpperCase(); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts isUpperCase.ts 17 | const isUpperCase = (str: string): boolean => str === str.toUpperCase(); 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/get-the-average-of-an-array.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | created: '2020-04-19' 4 | title: Get the average of an array 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js average.js 11 | const average = (arr) => arr.reduce((a, b) => a + b, 0) / arr.length; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts average.ts 17 | const average = (arr: number[]): number => arr.reduce((a, b) => a + b, 0) / arr.length; 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/check-if-a-string-contains-only-ascii-characters.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2020-06-09' 4 | title: Check if a string contains only ASCII characters 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isAscii.js 11 | const isAscii = (str) => /^[\x00-\x7F]+$/.test(str); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts isAscii.ts 17 | const isAscii = (str: string): boolean => /^[\x00-\x7F]+$/.test(str); 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/convert-a-string-to-number.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Number 3 | created: '2020-04-19' 4 | title: Convert a string to number 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js toNumber.js 11 | const toNumber = (str) => +str; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts toNumber.ts 17 | const toNumber = (str: string): number => +str; 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | toNumber('42'); // 42 24 | ``` 25 | -------------------------------------------------------------------------------- /contents/get-the-current-quarter-of-a-date.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Date Time 3 | created: '2021-02-25' 4 | title: Get the current quarter of a date 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js getQuarter.js 11 | const getQuarter = (d = new Date()) => Math.ceil((d.getMonth() + 1) / 3); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts getQuarter.ts 17 | const getQuarter = (d = new Date()): number => Math.ceil((d.getMonth() + 1) / 3); 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/check-if-a-date-is-a-weekday.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2021-02-25' 4 | title: Check if a date is a weekday 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isWeekday.js 11 | // `date` is a Date object 12 | const isWeekday = (date = new Date()) => date.getDay() % 6 !== 0; 13 | ``` 14 | 15 | **TypeScript version** 16 | 17 | ```ts isWeekday.ts 18 | const isWeekday = (date = new Date()): boolean => date.getDay() % 6 !== 0; 19 | ``` 20 | -------------------------------------------------------------------------------- /contents/check-if-a-date-is-a-weekend.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2021-02-25' 4 | title: Check if a date is a weekend 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isWeekend.js 11 | // `date` is a Date object 12 | const isWeekend = (date = new Date()) => date.getDay() % 6 === 0; 13 | ``` 14 | 15 | **TypeScript version** 16 | 17 | ```ts isWeekend.ts 18 | const isWeekend = (date = new Date()): boolean => date.getDay() % 6 === 0; 19 | ``` 20 | -------------------------------------------------------------------------------- /contents/detect-dark-mode.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Misc 3 | created: '2020-05-02' 4 | title: Detect dark mode 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isDarkMode.js 11 | const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts isDarkMode.ts 17 | const isDarkMode: boolean = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches; 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/check-if-an-element-is-a-descendant-of-another.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: DOM 3 | created: '2020-04-19' 4 | title: Check if an element is a descendant of another 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isDescendant.js 11 | const isDescendant = (child, parent) => parent.contains(child); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts isDescendant.ts 17 | const isDescendant = (child: Node, parent: Node): boolean => parent.contains(child); 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/multiply-arguments.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Number 3 | created: '2020-05-05' 4 | title: Multiply arguments 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js mul.js 11 | const mul = (...args) => args.reduce((a, b) => a * b); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts mul.ts 17 | const mul = (...args: number[]): number => args.reduce((a, b) => a * b); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | mul(1, 2, 3, 4); // 24 24 | ``` 25 | -------------------------------------------------------------------------------- /contents/replace-an-element.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: DOM 3 | created: '2020-04-19' 4 | title: Replace an element 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js replace.js 11 | const replace = (ele, newEle) => ele.parentNode.replaceChild(newEle, ele); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts replace.ts 17 | const replace = (ele: Element, newEle: Element): Element | null => 18 | ele.parentNode ? ele.parentNode.replaceChild(newEle, ele) : null; 19 | ``` 20 | -------------------------------------------------------------------------------- /contents/check-if-the-code-is-running-in-the-browser.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Misc 3 | created: '2020-05-02' 4 | title: Check if the code is running in the browser 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isBrowser.js 11 | const isBrowser = typeof window === 'object' && typeof document === 'object'; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts isBrowser.ts 17 | const isBrowser: boolean = typeof window === 'object' && typeof document === 'object'; 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/get-a-random-item-from-an-array.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Random 3 | contributors: 4 | - jonrandy 5 | created: '2020-04-19' 6 | title: Get a random item from an array 7 | updated: '2021-10-22' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js randomItem.js 13 | const randomItem = (arr) => arr[(Math.random() * arr.length) | 0]; 14 | ``` 15 | 16 | **TypeScript version** 17 | 18 | ```ts randomItem.ts 19 | const randomItem = (arr: T[]): T => arr[(Math.random() * arr.length) | 0]; 20 | ``` 21 | -------------------------------------------------------------------------------- /contents/check-if-a-value-is-a-generator-function.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Function 3 | created: '2020-05-15' 4 | title: Check if a value is a generator function 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js isGeneratorFunction.js 10 | const isGeneratorFunction = (v) => Object.prototype.toString.call(v) === '[object GeneratorFunction]'; 11 | ``` 12 | 13 | **Examples** 14 | 15 | ```js examples.js 16 | isGeneratorFunction(function () {}); // false 17 | isGeneratorFunction(function* () {}); // true 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/check-if-a-value-is-base32-encoded.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2021-04-10' 4 | title: Check if a value is base32 encoded 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isBase32.js 11 | const isBase32 = (value) => value.length % 8 === 0 && /^[A-Z2-7]+=*$/.test(value); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts isBase32.ts 17 | const isBase32 = (value: string): boolean => value.length % 8 === 0 && /^[A-Z2-7]+=*$/.test(value); 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/generate-a-random-string-using-node-crypto-module.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Random 3 | created: '2020-07-28' 4 | title: Generate a random string using Node crypto module 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js randomStr.js 11 | const randomStr = () => require('crypto').randomBytes(32).toString('hex'); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts randomStr.ts 17 | const randomStr = (): string => require('crypto').randomBytes(32).toString('hex'); 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/get-union-of-arrays.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | created: '2020-05-09' 4 | title: Get union of arrays 5 | updated: '2021-10-22' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js union.js 11 | const union = (...arr) => [...new Set(arr.flat())]; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts union.ts 17 | const union = (...arr: T[][]): T[] => [...new Set(arr.flat())]; 18 | ``` 19 | 20 | **Example** 21 | 22 | ```js example.js 23 | union([1, 2], [2, 3], [3]); // [1, 2, 3] 24 | ``` 25 | -------------------------------------------------------------------------------- /contents/replace-all-tab-characters-with-spaces.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2021-05-27' 4 | title: Replace all tab characters with spaces 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js replace.js 11 | const replace = (str, numSpaces = 4) => str.replaceAll('\t', ' '.repeat(numSpaces)); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts replace.ts 17 | const replace = (str: string, numSpaces = 4): string => str.replaceAll('\t', ' '.repeat(numSpaces)); 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/calculate-the-sum-of-arguments.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Number 3 | created: '2020-05-05' 4 | title: Calculate the sum of arguments 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js sum.js 11 | const sum = (...args) => args.reduce((a, b) => a + b); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts sum.ts 17 | const sum = (...args: number[]): number => args.reduce((a, b) => a + b); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | sum(1, 2, 3, 4); // 10 24 | ``` 25 | -------------------------------------------------------------------------------- /contents/check-if-a-value-is-a-number.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | contributors: 4 | - nbayramberdiyev 5 | created: '2020-04-23' 6 | title: Check if a value is a number 7 | updated: '2021-11-03' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js isNumber.js 13 | const isNumber = (value) => !isNaN(parseFloat(value)) && isFinite(value); 14 | ``` 15 | 16 | **TypeScript version** 17 | 18 | ```ts isNumber.ts 19 | const isNumber = (value: any): number => !isNaN(parseFloat(value)) && isFinite(value); 20 | ``` 21 | -------------------------------------------------------------------------------- /contents/check-if-the-code-is-running-in-jest.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Misc 3 | created: '2022-06-18' 4 | title: Check if the code is running in Jest 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js isRunningInJest.js 10 | const isRunningInJest = typeof process !== 'undefined' && process.env.JEST_WORKER_ID !== undefined; 11 | ``` 12 | 13 | **TypeScript version** 14 | 15 | ```ts isRunningInJest.ts 16 | const isRunningInJest: boolean = typeof process !== 'undefined' && process.env.JEST_WORKER_ID !== undefined; 17 | ``` 18 | -------------------------------------------------------------------------------- /contents/insert-given-html-after-an-element.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: DOM 3 | created: '2020-04-19' 4 | title: Insert given HTML after an element 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js insertHtmlAfter.js 11 | const insertHtmlAfter = (html, ele) => ele.insertAdjacentHTML('afterend', html); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts insertHtmlAfter.ts 17 | const insertHtmlAfter = (html: string, ele: Element): void => ele.insertAdjacentHTML('afterend', html); 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/sort-an-array-of-numbers.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | created: '2020-05-20' 4 | title: Sort an array of numbers 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js sort.js 11 | const sort = (arr) => arr.sort((a, b) => a - b); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts sort.ts 17 | const sort = (arr: number[]): number[] => arr.sort((a, b) => a - b); 18 | ``` 19 | 20 | **Example** 21 | 22 | ```js example.js 23 | sort([1, 5, 2, 4, 3]); // [1, 2, 3, 4, 5] 24 | ``` 25 | -------------------------------------------------------------------------------- /contents/check-if-a-value-is-base58-encoded.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2021-04-10' 4 | title: Check if a value is base58 encoded 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isBase58.js 11 | // It doesn't accept the I, O, l characters 12 | const isBase58 = (value) => /^[A-HJ-NP-Za-km-z1-9]*$/.test(value); 13 | ``` 14 | 15 | **TypeScript version** 16 | 17 | ```ts isBase58.ts 18 | const isBase58 = (value: string): boolean => /^[A-HJ-NP-Za-km-z1-9]*$/.test(value); 19 | ``` 20 | -------------------------------------------------------------------------------- /contents/decode-html-entities.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2022-08-21' 4 | title: Decode HTML entities 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js decodeHtmlEntities.js 10 | const decodeHtmlEntities = (str) => str.replace(/&#(\w+)(^\w|;)?/g, (_, dec) => String.fromCharCode(dec)); 11 | ``` 12 | 13 | **TypeScript version** 14 | 15 | ```ts decodeHtmlEntities.ts 16 | const decodeHtmlEntities = (str: string): string => 17 | str.replace(/&#(\w+)(^\w|;)?/g, (_, dec) => String.fromCharCode(dec)); 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/get-the-first-date-in-the-month-of-a-date.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Date Time 3 | created: '2021-02-25' 4 | title: Get the first date in the month of a date 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js getFirstDate.js 11 | const getFirstDate = (d = new Date()) => new Date(d.getFullYear(), d.getMonth(), 1); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts getFirstDate.ts 17 | const getFirstDate = (d = new Date()): Date => new Date(d.getFullYear(), d.getMonth(), 1); 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/get-the-last-date-in-the-month-of-a-date.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Date Time 3 | created: '2021-02-25' 4 | title: Get the last date in the month of a date 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js getLastDate.js 11 | const getLastDate = (d = new Date()) => new Date(d.getFullYear(), d.getMonth() + 1, 0); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts getLastDate.ts 17 | const getLastDate = (d = new Date()): Date => new Date(d.getFullYear(), d.getMonth() + 1, 0); 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/initialize-the-current-date-but-set-time-to-midnight.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Date Time 3 | created: '2021-04-20' 4 | title: Initialize the current date but set time to midnight 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js midnightOfToday.js 11 | const midnightOfToday = () => new Date(new Date().setHours(0, 0, 0, 0)); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts midnightOfToday.ts 17 | const midnightOfToday = (): Date => new Date(new Date().setHours(0, 0, 0, 0)); 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/subtract-arguments.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Number 3 | created: '2020-05-05' 4 | title: Subtract arguments 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js subtract.js 11 | const subtract = (...args) => args.reduce((a, b) => a - b); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts subtract.ts 17 | const subtract = (...args: number[]): number => args.reduce((a, b) => a - b); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | subtract(1, 2, 3, 4); // -8 24 | ``` 25 | -------------------------------------------------------------------------------- /contents/check-if-a-value-is-a-business-identifier-code.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2021-04-10' 4 | title: Check if a value is a business identifier code 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isBIC.js 11 | const isBIC = (value) => /^[a-zA-Z]{6}[a-zA-Z0-9]{2}([a-zA-Z0-9]{3})?$/.test(value); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts isBIC.ts 17 | const isBIC = (value: string): boolean => /^[a-zA-Z]{6}[a-zA-Z0-9]{2}([a-zA-Z0-9]{3})?$/.test(value); 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/check-if-a-value-is-a-regular-expression.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2020-05-14' 4 | title: Check if a value is a regular expression 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isRegExp.js 11 | const isRegExp = (value) => Object.prototype.toString.call(value) === '[object RegExp]'; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts isRegExp.ts 17 | const isRegExp = (value: any): boolean => Object.prototype.toString.call(value) === '[object RegExp]'; 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/insert-given-html-before-an-element.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: DOM 3 | created: '2020-04-19' 4 | title: Insert given HTML before an element 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js insertHtmlBefore.js 11 | const insertHtmlBefore = (html, ele) => ele.insertAdjacentHTML('beforebegin', html); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts insertHtmlBefore.ts 17 | const insertHtmlBefore = (html: string, ele: Element): void => ele.insertAdjacentHTML('beforebegin', html); 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/strip-html-from-a-given-text.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: DOM 3 | created: '2020-04-19' 4 | title: Strip HTML from a given text 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js stripHtml.js 11 | const stripHtml = (html) => new DOMParser().parseFromString(html, 'text/html').body.textContent || ''; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts stripHtml.ts 17 | const stripHtml = (html: string): string => new DOMParser().parseFromString(html, 'text/html').body.textContent || ''; 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/check-if-a-value-is-an-async-function.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Function 3 | created: '2020-05-15' 4 | title: Check if a value is an async function 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js isAsyncFunction.js 10 | const isAsyncFunction = (v) => Object.prototype.toString.call(v) === '[object AsyncFunction]'; 11 | ``` 12 | 13 | **Examples** 14 | 15 | ```js examples.js 16 | isAsyncFunction(function () {}); // false 17 | isAsyncFunction(function* () {}); // false 18 | isAsyncFunction(async function () {}); // true 19 | ``` 20 | -------------------------------------------------------------------------------- /contents/execute-a-function-once.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Function 3 | created: '2020-05-13' 4 | title: Execute a function once 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js once.js 10 | const once = (fn) => 11 | ( 12 | (ran = false) => 13 | () => 14 | ran ? fn : ((ran = !ran), (fn = fn())) 15 | )(); 16 | ``` 17 | 18 | **Examples** 19 | 20 | ```js examples.js 21 | let n = 0; 22 | const incOnce = once(() => ++n); 23 | incOnce(); // n = 1 24 | incOnce(); // n = 1 25 | incOnce(); // n = 1 26 | ``` 27 | -------------------------------------------------------------------------------- /contents/omit-a-subset-of-properties-from-an-object.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Object 3 | created: '2020-05-13' 4 | title: Omit a subset of properties from an object 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js omit.js 10 | const omit = (obj, keys) => 11 | Object.keys(obj) 12 | .filter((k) => !keys.includes(k)) 13 | .reduce((res, k) => Object.assign(res, { [k]: obj[k] }), {}); 14 | ``` 15 | 16 | **Examples** 17 | 18 | ```js examples.js 19 | omit({ a: '1', b: '2', c: '3' }, ['a', 'b']); // { c: '3' } 20 | ``` 21 | -------------------------------------------------------------------------------- /contents/pick-a-subset-of-properties-of-an-object.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Object 3 | created: '2020-05-13' 4 | title: Pick a subset of properties of an object 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js pick.js 10 | const pick = (obj, keys) => 11 | Object.keys(obj) 12 | .filter((k) => keys.includes(k)) 13 | .reduce((res, k) => Object.assign(res, { [k]: obj[k] }), {}); 14 | ``` 15 | 16 | **Examples** 17 | 18 | ```js examples.js 19 | pick({ a: '1', b: '2', c: '3' }, ['a', 'b']); // { a: '1', b: '2' } 20 | ``` 21 | -------------------------------------------------------------------------------- /contents/get-the-length-of-a-string-in-bytes.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2020-05-16' 4 | title: Get the length of a string in bytes 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js bytes.js 11 | const bytes = (str) => new Blob([str]).size; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts bytes.ts 17 | const bytes = (str: string): number => new Blob([str]).size; 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | bytes('hello world'); // 11 24 | bytes('🎉'); // 4 25 | ``` 26 | -------------------------------------------------------------------------------- /contents/reload-the-current-page.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: DOM 3 | created: '2020-04-19' 4 | title: Reload the current page 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js reload.js 11 | const reload = () => location.reload(); 12 | 13 | // Or 14 | const reload = () => (location.href = location.href); 15 | ``` 16 | 17 | **TypeScript version** 18 | 19 | ```ts reload.ts 20 | const reload = (): void => location.reload(); 21 | 22 | // Or 23 | const reload = (): string => (location.href = location.href); 24 | ``` 25 | -------------------------------------------------------------------------------- /contents/get-the-number-of-days-in-given-month.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Date Time 3 | created: '2020-04-19' 4 | title: Get the number of days in given month 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js daysInMonth.js 11 | // `month` is zero-based index 12 | const daysInMonth = (month, year) => new Date(year, month, 0).getDate(); 13 | ``` 14 | 15 | **TypeScript version** 16 | 17 | ```ts daysInMonth.ts 18 | const daysInMonth = (month: number, year: number): number => new Date(year, month, 0).getDate(); 19 | ``` 20 | -------------------------------------------------------------------------------- /contents/check-if-a-date-is-today.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2020-05-05' 4 | title: Check if a date is today 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isToday.js 11 | // `date` is a Date object 12 | const isToday = (date) => date.toISOString().slice(0, 10) === new Date().toISOString().slice(0, 10); 13 | ``` 14 | 15 | **TypeScript version** 16 | 17 | ```ts isToday.ts 18 | const isToday = (date: Date): boolean => date.toISOString().slice(0, 10) === new Date().toISOString().slice(0, 10); 19 | ``` 20 | -------------------------------------------------------------------------------- /contents/check-if-the-code-is-running-in-node-js.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Misc 3 | created: '2020-05-02' 4 | title: Check if the code is running in NodeJS 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isNode.js 11 | const isNode = typeof process !== 'undefined' && process.versions != null && process.versions.node != null; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts isNode.ts 17 | const isNode: boolean = typeof process !== 'undefined' && process.versions != null && process.versions.node != null; 18 | ``` 19 | -------------------------------------------------------------------------------- /contents/get-the-position-of-an-element-relative-to-the-document.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: DOM 3 | created: '2021-04-21' 4 | title: Get the position of an element relative to the document 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js getPosition.js 11 | const getPosition = (ele) => ( 12 | (r = ele.getBoundingClientRect()), { left: r.left + window.scrollX, top: r.top + window.scrollY } 13 | ); 14 | ``` 15 | 16 | **Example** 17 | 18 | ```js example.js 19 | getPosition(document.body); // { left: 0, top: 0 } 20 | ``` 21 | -------------------------------------------------------------------------------- /contents/get-unique-arr-obj.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Object 3 | contributors: 4 | - gpbuavv 5 | created: '2023-02-17' 6 | title: Returns an object with unique values by key 7 | --- 8 | 9 | **JavaScript version** 10 | 11 | ```js 12 | export const getUniqueArrObj = (arrObj, keyUnique) => [...new Map(arrObj.map((item) => [item[keyUnique], item])).values()]; 13 | ``` 14 | 15 | **Example** 16 | 17 | ```js example.js 18 | // Example 19 | getUniqueArrObj([{ k: 1, e: 1 }, { k: 1, e: 1 }, { k: 3, e: 1 }], 'k'); // [{ k: 1, e: 1 }, { k: 3, e: 1 }] 20 | ``` 21 | -------------------------------------------------------------------------------- /contents/get-all-siblings-of-an-element.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: DOM 3 | created: '2020-04-19' 4 | title: Get all siblings of an element 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js siblings.js 11 | const siblings = (ele) => [].slice.call(ele.parentNode.children).filter((child) => child !== ele); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts siblings.ts 17 | const siblings = (ele: Node): Node[] => 18 | ele.parentNode ? [].slice.call(ele.parentNode.children).filter((child) => child !== ele) : []; 19 | ``` 20 | -------------------------------------------------------------------------------- /contents/remove-spaces-from-a-string.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2020-05-03' 4 | title: Remove spaces from a string 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js removeSpaces.js 11 | const removeSpaces = (str) => str.replace(/\s/g, ''); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts removeSpaces.ts 17 | const removeSpaces = (str: string): string => str.replace(/\s/g, ''); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | removeSpaces('hel lo wor ld'); // 'helloworld' 24 | ``` 25 | -------------------------------------------------------------------------------- /contents/truncate-a-number-at-decimal.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Number 3 | contributors: 4 | - onelifemedia 5 | created: '2020-08-05' 6 | title: Truncate a number at decimal 7 | updated: '2021-10-13' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js truncate.js 13 | const truncate = (n) => ~~n; 14 | ``` 15 | 16 | **TypeScript version** 17 | 18 | ```ts truncate.ts 19 | const truncate = (n: number): number => ~~n; 20 | ``` 21 | 22 | **Examples** 23 | 24 | ```js examples.js 25 | truncate(25.198726354); // 25 26 | truncate(-25.198726354); // -25 27 | ``` 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Favorite single line of code 2 | 3 | What's your favorite JavaScript single LOC (line of code)? Let me know! 4 | 5 | ## Contributing 6 | 7 | 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. 8 | 9 | ## About 10 | 11 | This project is developed by _Nguyen Huu Phuoc_. I love building products and sharing knowledge. 12 | 13 | Be my friend on 14 | 15 | - [Twitter](https://twitter.com/_phuocng) 16 | - [Github](https://github.com/phuocng) 17 | -------------------------------------------------------------------------------- /contents/get-the-timezone-string.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Date Time 3 | created: '2021-02-25' 4 | title: Get the timezone string 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js getTimezone.js 11 | const getTimezone = () => Intl.DateTimeFormat().resolvedOptions().timeZone; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts getTimezone.ts 17 | const getTimezone = (): string => Intl.DateTimeFormat().resolvedOptions().timeZone; 18 | ``` 19 | 20 | **Example** 21 | 22 | ```js example.js 23 | getTimezone(); // 'Asia/Saigon' 24 | ``` 25 | -------------------------------------------------------------------------------- /contents/calculate-the-division-of-arguments.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Number 3 | created: '2020-05-05' 4 | title: Calculate the division of arguments 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js division.js 11 | const division = (...args) => args.reduce((a, b) => a / b); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts division.ts 17 | const division = (...args: number): number => args.reduce((a, b) => a / b); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | division(1, 2, 3, 4); // 0.04166666666666666 24 | ``` 25 | -------------------------------------------------------------------------------- /contents/check-if-a-date-occurs-in-the-current-year.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2021-04-13' 4 | title: Check if a date occurs in the current year 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isCurrentYear.js 11 | // `date` is a Date object 12 | const isCurrentYear = (date) => date.getUTCFullYear() === new Date().getUTCFullYear(); 13 | ``` 14 | 15 | **TypeScript version** 16 | 17 | ```ts isCurrentYear.ts 18 | const isCurrentYear = (date: Date): boolean => date.getUTCFullYear() === new Date().getUTCFullYear(); 19 | ``` 20 | -------------------------------------------------------------------------------- /contents/compute-the-greatest-common-divisor-between-two-numbers.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Number 3 | created: '2020-04-23' 4 | title: Compute the greatest common divisor between two numbers 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js gcd.js 11 | const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b)); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts gcd.ts 17 | const gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b)); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | gcd(10, 15); // 5 24 | ``` 25 | -------------------------------------------------------------------------------- /contents/check-if-a-number-is-a-power-of-2.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2020-04-19' 4 | title: Check if a number is a power of 2 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isPowerOfTwo.js 11 | const isPowerOfTwo = (n) => (n & (n - 1)) === 0; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts isPowerOfTwo.ts 17 | const isPowerOfTwo = (n: number): boolean => (n & (n - 1)) === 0; 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | isPowerOfTwo(256); // true 24 | isPowerOfTwo(129); // false 25 | ``` 26 | -------------------------------------------------------------------------------- /contents/curry-a-function.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Function 3 | created: '2020-05-15' 4 | title: Curry a function 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js curry.js 10 | const curry = (fn, ...args) => (fn.length <= args.length ? fn(...args) : curry.bind(null, fn, ...args)); 11 | ``` 12 | 13 | **Examples** 14 | 15 | ```js examples.js 16 | const sum = (a, b, c) => a + b + c; 17 | curry(sum)(1)(2)(3); // 6 18 | curry(sum)(1, 2, 3); // 6 19 | curry(sum, 1)(2, 3); // 6 20 | curry(sum, 1)(2)(3); // 6 21 | curry(sum, 1, 2)(3); // 6 22 | curry(sum, 1, 2, 3); // 6 23 | ``` 24 | -------------------------------------------------------------------------------- /contents/emulate-a-dice-throw.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Misc 3 | contributors: 4 | - codepo8 5 | created: '2020-05-01' 6 | title: Emulate a dice throw 7 | updated: '2021-10-13' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js throwdice.js 13 | const throwdice = () => ~~(Math.random() * 6) + 1; 14 | ``` 15 | 16 | **TypeScript version** 17 | 18 | ```ts throwdice.ts 19 | const throwdice = (): number => ~~(Math.random() * 6) + 1; 20 | ``` 21 | 22 | **Examples** 23 | 24 | ```js examples.js 25 | throwdice(); // 4 26 | throwdice(); // 1 27 | throwdice(); // 6 28 | ``` 29 | -------------------------------------------------------------------------------- /contents/calculate-the-average-of-arguments.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Number 3 | created: '2020-05-05' 4 | title: Calculate the average of arguments 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js average.js 11 | const average = (...args) => args.reduce((a, b) => a + b) / args.length; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts average.ts 17 | const average = (...args: number[]): number => args.reduce((a, b) => a + b) / args.length; 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | average(1, 2, 3, 4); // 2.5 24 | ``` 25 | -------------------------------------------------------------------------------- /contents/calculate-the-remainder-of-division-of-arguments.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Number 3 | created: '2020-05-05' 4 | title: Calculate the remainder of division of arguments 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js remainder.js 11 | const remainder = (...args) => args.reduce((a, b) => a % b); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts remainder.ts 17 | const remainder = (...args: number[]): number => args.reduce((a, b) => a % b); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | remainder(1, 2, 3, 4); // 1 24 | ``` 25 | -------------------------------------------------------------------------------- /contents/compare-two-dates.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Date Time 3 | created: '2020-04-19' 4 | title: Compare two dates 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js compare.js 11 | // `a` and `b` are `Date` instances 12 | const compare = (a, b) => a.getTime() > b.getTime(); 13 | ``` 14 | 15 | **TypeScript version** 16 | 17 | ```ts compare.ts 18 | const compare = (a: Date, b: Date): boolean => a.getTime() > b.getTime(); 19 | ``` 20 | 21 | **Example** 22 | 23 | ```js example.js 24 | compare(new Date('2020-03-30'), new Date('2020-01-01')); // true 25 | ``` 26 | -------------------------------------------------------------------------------- /contents/cast-a-value-as-an-array.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | title: Cast a value as an array 4 | created: '2021-04-04' 5 | updated: '2021-10-22' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js castArray.js 11 | const castArray = (value) => (Array.isArray(value) ? value : [value]); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts castArray.ts 17 | const castArray = (value: T | T[]): T[] => (Array.isArray(value) ? value : [value]); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | castArray(1); // [1] 24 | castArray([1, 2, 3]); // [1, 2, 3] 25 | ``` 26 | -------------------------------------------------------------------------------- /contents/check-if-a-number-is-positive.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | contributors: 4 | - tugsanunlu 5 | created: '2020-05-07' 6 | title: Check if a number is positive 7 | updated: '2021-10-13' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js isPositive.js 13 | const isPositive = (n) => Math.sign(n) === 1; 14 | ``` 15 | 16 | **TypeScript version** 17 | 18 | ```ts isPositive.ts 19 | const isPositive = (n: number): boolean => Math.sign(n) === 1; 20 | ``` 21 | 22 | **Examples** 23 | 24 | ```js examples.js 25 | isPositive(3); // true 26 | isPositive(-8); // false 27 | ``` 28 | -------------------------------------------------------------------------------- /contents/compare-two-dom-rects-for-size-and-position-match.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: DOM 3 | created: '2023-12-10' 4 | openGraphCover: /og/1-loc/compare-two-dom-rects-size-position-match.png 5 | title: Compare two DOMRects for size and position match 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js compare.js 11 | const compare = (a, b) => ['top', 'left', 'width', 'height'].every(key => a[key] === b[key]); 12 | ``` 13 | 14 | **Example** 15 | 16 | ```js example.js 17 | const a = new DOMRect(0, 0, 100, 200); 18 | const b = new DOMRect(0, 0, 100, 200); 19 | compare(a, b); // true 20 | ``` 21 | -------------------------------------------------------------------------------- /contents/calculate-the-mod-of-collection-index.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Number 3 | contributors: 4 | - marcobiedermann 5 | created: '2020-05-08' 6 | title: Calculate the mod of collection index 7 | updated: '2021-10-13' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js mod.js 13 | const mod = (a, b) => ((a % b) + b) % b; 14 | ``` 15 | 16 | **TypeScript version** 17 | 18 | ```ts mod.ts 19 | const mod = (a: number, b: number): number => ((a % b) + b) % b; 20 | ``` 21 | 22 | **Examples** 23 | 24 | ```js examples.js 25 | mod(-1, 5); // 4 26 | mod(3, 5); // 3 27 | mod(6, 5); // 1 28 | ``` 29 | -------------------------------------------------------------------------------- /contents/extract-values-of-a-property-from-an-array-of-objects.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Object 3 | created: '2020-06-02' 4 | title: Extract values of a property from an array of objects 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js pluck.js 10 | const pluck = (objs, property) => objs.map((obj) => obj[property]); 11 | ``` 12 | 13 | **Examples** 14 | 15 | ```js examples.js 16 | pluck( 17 | [ 18 | { name: 'John', age: 20 }, 19 | { name: 'Smith', age: 25 }, 20 | { name: 'Peter', age: 30 }, 21 | ], 22 | 'name' 23 | ); // ['John', 'Smith', 'Peter'] 24 | ``` 25 | -------------------------------------------------------------------------------- /contents/immutably-rename-object-keys.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Object 3 | contributors: 4 | - imyangyong 5 | created: '2021-01-11' 6 | title: Immutably rename object keys 7 | --- 8 | 9 | **JavaScript version** 10 | 11 | ```js renameKeys.js 12 | const renameKeys = (keysMap, obj) => 13 | Object.keys(obj).reduce((acc, key) => ({ ...acc, ...{ [keysMap[key] || key]: obj[key] } }), {}); 14 | ``` 15 | 16 | **Examples** 17 | 18 | ```js examples.js 19 | const obj = { a: 1, b: 2, c: 3 }; 20 | const keysMap = { a: 'd', b: 'e', c: 'f' }; 21 | renameKeys(keysMap, obj); // { d: 1, e: 2, f: 3 } 22 | ``` 23 | -------------------------------------------------------------------------------- /contents/check-if-a-value-is-a-function.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Function 3 | created: '2020-05-15' 4 | title: Check if a value is a function 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js isFunction.js 10 | const isFunction = (v) => 11 | ['[object Function]', '[object GeneratorFunction]', '[object AsyncFunction]', '[object Promise]'].includes( 12 | Object.prototype.toString.call(v) 13 | ); 14 | ``` 15 | 16 | **Examples** 17 | 18 | ```js examples.js 19 | isFunction(function () {}); // true 20 | isFunction(function* () {}); // true 21 | isFunction(async function () {}); // true 22 | ``` 23 | -------------------------------------------------------------------------------- /contents/check-if-a-value-is-base64-encoded.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2021-04-10' 4 | title: Check if a value is base64 encoded 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isBase64.js 11 | const isBase64 = (value) => 12 | /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/.test(value); 13 | ``` 14 | 15 | **TypeScript version** 16 | 17 | ```ts isBase64.ts 18 | const isBase64 = (value: string): boolean => 19 | /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/.test(value); 20 | ``` 21 | -------------------------------------------------------------------------------- /contents/get-the-file-name-from-a-url.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2020-04-19' 4 | title: Get the file name from a URL 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js fileName.js 11 | const fileName = (url: string): string => url.substring(url.lastIndexOf('/') + 1); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts fileName.ts 17 | const fileName = (url: string): string => url.substring(url.lastIndexOf('/') + 1); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | fileName('http://domain.com/path/to/document.pdf'); // 'document.pdf' 24 | ``` 25 | -------------------------------------------------------------------------------- /contents/calculate-the-distance-between-two-points.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Math 3 | created: '2021-04-05' 4 | title: Calculate the distance between two points 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js distance.js 11 | const distance = (p1, p2) => Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2)); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```js distance.ts 17 | interface Point { 18 | x: number; 19 | y: number; 20 | } 21 | 22 | const distance = (p1: Point, p2: Point): number => Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2)); 23 | ``` 24 | -------------------------------------------------------------------------------- /contents/check-if-user-scrolls-to-the-bottom-of-the-page.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: DOM 3 | created: '2021-04-10' 4 | title: Check if user scrolls to the bottom of the page 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isAtBottom.js 11 | const isAtBottom = () => 12 | document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight; 13 | ``` 14 | 15 | **TypeScript version** 16 | 17 | ```ts isAtBottom.ts 18 | const isAtBottom = (): boolean => 19 | document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight; 20 | ``` 21 | -------------------------------------------------------------------------------- /contents/create-an-object-from-the-pairs-of-key-and-value.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Object 3 | contributors: 4 | - robinpokorny 5 | created: '2020-05-18' 6 | title: Create an object from the pairs of key and value 7 | updated: '2020-05-20' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js toObj.js 13 | const toObj = (arr) => Object.fromEntries(arr); 14 | 15 | // Or 16 | const toObj = (arr) => arr.reduce((a, c) => ((a[c[0]] = c[1]), a), {}); 17 | ``` 18 | 19 | **Examples** 20 | 21 | ```js examples.js 22 | toObj([ 23 | ['a', 1], 24 | ['b', 2], 25 | ['c', 3], 26 | ]); // { a: 1, b: 2, c: 3 } 27 | ``` 28 | -------------------------------------------------------------------------------- /contents/convert-fahrenheit-to-celsius.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Misc 3 | created: '2021-04-08' 4 | title: Convert Fahrenheit to Celsius 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js fahrenheitToCelsius.js 11 | const fahrenheitToCelsius = (fahrenheit) => ((fahrenheit - 32) * 5) / 9; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts fahrenheitToCelsius.ts 17 | const fahrenheitToCelsius = (fahrenheit: number): number => ((fahrenheit - 32) * 5) / 9; 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | fahrenheitToCelsius(59); // 15 24 | fahrenheitToCelsius(32); // 0 25 | ``` 26 | -------------------------------------------------------------------------------- /contents/get-the-weekday-of-a-date.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Date Time 3 | created: '2020-05-05' 4 | title: Get the weekday of a date 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js getWeekday.js 11 | // `date` is a Date object 12 | const getWeekday = (date) => 13 | ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][date.getDay()]; 14 | ``` 15 | 16 | **TypeScript version** 17 | 18 | ```ts getWeekday.ts 19 | const getWeekday = (date: Date): string => 20 | ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][date.getDay()]; 21 | ``` 22 | -------------------------------------------------------------------------------- /contents/check-if-a-date-is-between-two-dates.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2020-04-19' 4 | title: Check if a date is between two dates 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isBetween.js 11 | // `min`, `max` and `date` are `Date` instances 12 | const isBetween = (date, min, max) => date.getTime() >= min.getTime() && date.getTime() <= max.getTime(); 13 | ``` 14 | 15 | **TypeScript version** 16 | 17 | ```ts isBetween.ts 18 | const isBetween = (date: Date, min: Date, max: Date): boolean => 19 | date.getTime() >= min.getTime() && date.getTime() <= max.getTime(); 20 | ``` 21 | -------------------------------------------------------------------------------- /contents/check-if-a-string-contains-whitespace.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2020-04-19' 4 | title: Check if a string contains whitespace 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js containsWhitespace.js 11 | const containsWhitespace = (str) => (str) => /\s/.test(str); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts containsWhitespace.ts 17 | const containsWhitespace = 18 | (str: string): boolean => 19 | (str) => 20 | /\s/.test(str); 21 | ``` 22 | 23 | **Examples** 24 | 25 | ```js examples.js 26 | containsWhitespace('hello world'); // true 27 | ``` 28 | -------------------------------------------------------------------------------- /contents/logical-xor-operator.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Function 3 | created: '2020-05-13' 4 | title: Logical xor operator 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js 10 | // returns `true` if one of the arguments is truthy and the other is falsy 11 | 12 | const xor = (a, b) => (a && !b) || (!a && b); 13 | 14 | // Or 15 | const xor = (a, b) => !(!a && !b) && !(a && b); 16 | 17 | // Or 18 | const xor = (a, b) => Boolean(!a ^ !b); 19 | ``` 20 | 21 | **Examples** 22 | 23 | ```js examples.js 24 | xor(true, true); // false 25 | xor(false, false); // false 26 | xor(true, false); // true 27 | xor(false, true); // true 28 | ``` 29 | -------------------------------------------------------------------------------- /contents/invert-keys-and-values-of-an-object.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Object 3 | contributors: 4 | - johandalabacka 5 | created: '2020-05-15' 6 | title: Invert keys and values of an object 7 | updated: '2020-12-27' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js invert.js 13 | const invert = (obj) => Object.keys(obj).reduce((res, k) => Object.assign(res, { [obj[k]]: k }), {}); 14 | 15 | // Or 16 | const invert = (obj) => Object.fromEntries(Object.entries(obj).map(([k, v]) => [v, k])); 17 | ``` 18 | 19 | **Examples** 20 | 21 | ```js examples.js 22 | invert({ a: '1', b: '2', c: '3' }); // { 1: 'a', 2: 'b', 3: 'c' } 23 | ``` 24 | -------------------------------------------------------------------------------- /contents/check-if-a-value-is-an-object.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2020-05-13' 4 | title: Check if a value is an object 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isObject.js 11 | const isObject = (v) => v !== null && typeof v === 'object'; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts isObject.ts 17 | const isObject = (v: any): boolean => v !== null && typeof v === 'object'; 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | isObject(null); // false 24 | isObject('hello world'); // false 25 | 26 | isObject({}); // true 27 | isObject([]); // true 28 | ``` 29 | -------------------------------------------------------------------------------- /contents/convert-decimal-to-binary-recursively.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Number 3 | contributors: 4 | - philosophercode 5 | created: '2020-12-11' 6 | title: Convert decimal to binary recursively 7 | updated: '2021-10-13' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js decToBi.js 13 | const decToBi = (num) => (num === 0 ? 0 : (num % 2) + 10 * decToBi(~~(num / 2))); 14 | ``` 15 | 16 | **TypeScript version** 17 | 18 | ```ts decToBi.ts 19 | const decToBi = (num: number): number => (num === 0 ? 0 : (num % 2) + 10 * decToBi(~~(num / 2))); 20 | ``` 21 | 22 | **Examples** 23 | 24 | ```js examples.js 25 | decToBi(10); //1010 26 | ``` 27 | -------------------------------------------------------------------------------- /contents/create-cartesian-product.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | contributors: 4 | - robinpokorny 5 | created: '2020-12-02' 6 | title: Create cartesian product 7 | updated: '2021-10-13' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js cartesian.js 13 | const cartesian = (...sets) => sets.reduce((acc, set) => acc.flatMap((x) => set.map((y) => [...x, y])), [[]]); 14 | ``` 15 | 16 | **Example** 17 | 18 | ```js example.js 19 | cartesian([1, 2], [3, 4]); // [ [1, 3], [1, 4], [2, 3], [2, 4] ] 20 | 21 | /* 22 | 3 4 23 | --------------- 24 | 1 | [1, 3] [1, 4] 25 | | 26 | 2 | [2, 3] [2, 4] 27 | 28 | */ 29 | ``` 30 | -------------------------------------------------------------------------------- /contents/normalize-file-path-slashes.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2020-05-15' 4 | title: Normalize file path slashes 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js normalizePath.js 11 | const normalizePath = (path) => path.replace(/[\\/]+/g, '/'); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts normalizePath.ts 17 | const normalizePath = (path: string): string => path.replace(/[\\/]+/g, '/'); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | normalizePath('\\foo\\bar\\baz\\'); // /foo/bar/baz/ 24 | normalizePath('.//foo//bar///////baz/'); // ./foo/bar/baz/ 25 | ``` 26 | -------------------------------------------------------------------------------- /contents/zip-multiple-arrays.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | created: '2020-05-13' 4 | title: Zip multiple arrays 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js zip.js 11 | const zip = (...arr) => Array.from({ length: Math.max(...arr.map((a) => a.length)) }, (_, i) => arr.map((a) => a[i])); 12 | ``` 13 | 14 | **Example** 15 | 16 | ```js example.js 17 | zip(['a', 'b', 'c', 'd', 'e'], [1, 2, 3, 4, 5]); // [['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5]] 18 | 19 | /* 20 | Does it look like a zipper? 21 | a 1 22 | b 2 23 | c 3 24 | d 4 25 | e 5 26 | */ 27 | ``` 28 | -------------------------------------------------------------------------------- /contents/check-if-an-object-is-a-promise.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | contributors: 4 | - quantumsheep 5 | created: '2020-05-06' 6 | title: Check if an object is a Promise 7 | updated: '2021-10-13' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js isPromise.js 13 | const isPromise = (obj) => 14 | !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'; 15 | ``` 16 | 17 | **TypeScript version** 18 | 19 | ```ts isPromise.ts 20 | const isPromise = (obj: any): boolean => 21 | !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'; 22 | ``` 23 | -------------------------------------------------------------------------------- /contents/check-if-the-touch-events-are-supported.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: DOM 3 | created: '2020-04-25' 4 | title: Check if the touch events are supported 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js touchSupported.js 11 | const touchSupported = () => 12 | 'ontouchstart' in window || (window.DocumentTouch && document instanceof window.DocumentTouch); 13 | ``` 14 | 15 | **TypeScript version** 16 | 17 | ```ts touchSupported.ts 18 | const touchSupported = (): boolean => ( 19 | 'ontouchstart' in window || (window as any)['DocumentTouch'] && document instanceof (window as any)['DocumentTouch'] 20 | ); 21 | ``` 22 | -------------------------------------------------------------------------------- /contents/convert-a-date-to-yyyy-mm-dd-format.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Date Time 3 | contributors: 4 | - ValchanOficial 5 | created: '2020-04-19' 6 | title: 'Convert a date to YYYY-MM-DD format' 7 | updated: '2021-10-13' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js formatYmd.js 13 | // `date` is a `Date` object 14 | const formatYmd = (date) => date.toISOString().slice(0, 10); 15 | ``` 16 | 17 | **TypeScript version** 18 | 19 | ```ts formatYmd.ts 20 | const formatYmd = (date: Date): string => date.toISOString().slice(0, 10); 21 | ``` 22 | 23 | **Example** 24 | 25 | ```js example.js 26 | formatYmd(new Date()); // 2020-05-06 27 | ``` 28 | -------------------------------------------------------------------------------- /contents/count-the-number-of-words-in-a-string.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2021-05-26' 4 | title: Count the number of words in a string 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js countWords.js 11 | const countWords = (str) => str.trim().split(/\s+/).length; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts countWords.ts 17 | const countWords = (str: string): number => str.trim().split(/\s+/).length; 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | countWords('Hello World'); // 2 24 | countWords('Hello World'); // 2 25 | countWords(' Hello World '); // 2 26 | ``` 27 | -------------------------------------------------------------------------------- /contents/make-the-first-character-of-a-string-lowercase.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2020-05-03' 4 | title: Make the first character of a string lowercase 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js lowercaseFirst.js 11 | const lowercaseFirst = (str) => `${str.charAt(0).toLowerCase()}${str.slice(1)}`; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts lowercaseFirst.ts 17 | const lowercaseFirst = (str: string): string => `${str.charAt(0).toLowerCase()}${str.slice(1)}`; 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | lowercaseFirst('Hello World'); // 'hello World' 24 | ``` 25 | -------------------------------------------------------------------------------- /contents/calculate-the-factorial-of-a-number.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Number 3 | created: '2020-05-19' 4 | title: Calculate the factorial of a number 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js factorial.js 11 | const factorial = (n) => (n <= 1 ? 1 : n * factorial(n - 1)); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts factorial.ts 17 | const factorial = (n: number): number => (n <= 1 ? 1 : n * factorial(n - 1)); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | factorial(2); // 2 24 | factorial(3); // 6 25 | factorial(4); // 24 26 | factorial(5); // 120 27 | factorial(6); // 720 28 | ``` 29 | -------------------------------------------------------------------------------- /contents/calculate-the-midpoint-of-a-given-range.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Math 3 | created: '2023-12-08' 4 | openGraphCover: /og/1-loc/calculate-midpoint-given-range.png 5 | title: Calculate the midpoint of a given range 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js midpoint.js 11 | const midpoint = ([from, to]) => (from + to) / 2; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts midpoint.ts 17 | const midpoint = ([from, to]: [number, number]): number => (from + to) / 2; 18 | ``` 19 | 20 | ## See also 21 | 22 | - [Calculate the midpoint between two points](https://phuoc.ng/collection/1-loc/calculate-the-midpoint-between-two-points/) 23 | -------------------------------------------------------------------------------- /contents/check-if-a-string-contains-only-letters.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2020-06-07' 4 | title: Check if a string contains only letters 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isAlpha.js 11 | const isAlpha = (str) => /^[A-Z]+$/i.test(str); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts isAlpha.ts 17 | const isAlpha = (str: string): boolean => /^[A-Z]+$/i.test(str); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | isAlpha('helloworld'); // true 24 | isAlpha('HelloWorld'); // true 25 | isAlpha('hello world'); // false 26 | isAlpha('0123456789'); // false 27 | ``` 28 | -------------------------------------------------------------------------------- /contents/check-if-an-array-is-empty.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | contributors: 4 | - inoyakaigor 5 | - elkarouani 6 | created: '2020-06-23' 7 | title: Check if an array is empty 8 | updated: '2021-12-21' 9 | --- 10 | 11 | **JavaScript version** 12 | 13 | ```js isEmpty.js 14 | // `arr` is an array 15 | const isEmpty = (arr) => Array.isArray(arr) && !arr.length; 16 | ``` 17 | 18 | **TypeScript version** 19 | 20 | ```ts isEmpty.ts 21 | const isEmpty = (arr: T[]): boolean => Array.isArray(arr) && !arr.length; 22 | ``` 23 | 24 | **Examples** 25 | 26 | ```js examples.js 27 | isEmpty([]); // true 28 | isEmpty([1, 2, 3]); // false 29 | ``` 30 | -------------------------------------------------------------------------------- /contents/convert-a-letter-to-associate-emoji.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2020-08-02' 4 | title: Convert a letter to associate emoji 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js letterToEmoji.js 11 | const letterToEmoji = (c) => String.fromCodePoint(c.toLowerCase().charCodeAt(0) + 127365); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts letterToEmoji.ts 17 | const letterToEmoji = (c: string): string => String.fromCodePoint(c.toLowerCase().charCodeAt(0) + 127365); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | letterToEmoji('a'); // 🇦 24 | letterToEmoji('b'); // 🇧 25 | ``` 26 | -------------------------------------------------------------------------------- /contents/convert-snake-case-to-camel-case.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2020-05-12' 4 | title: 'Convert snake_case to camelCase' 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js snakeToCamel.js 11 | const snakeToCamel = (str) => str.toLowerCase().replace(/(_\w)/g, (m) => m.toUpperCase().substr(1)); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts snakeToCamel.ts 17 | const snakeToCamel = (str: string): string => str.toLowerCase().replace(/(_\w)/g, (m) => m.toUpperCase().substr(1)); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | snakeToCamel('HELLO_world'); // 'helloWorld' 24 | ``` 25 | -------------------------------------------------------------------------------- /contents/get-the-value-of-a-param-from-a-url.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Misc 3 | created: '2020-04-23' 4 | title: Get the value of a param from a URL 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js getParam.js 11 | const getParam = (url, param) => new URLSearchParams(new URL(url).search).get(param); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts getParam.ts 17 | const getParam = (url: string, param: string): string | null => new URLSearchParams(new URL(url).search).get(param); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | getParam('http://domain.com?message=hello', 'message'); // 'hello' 24 | ``` 25 | -------------------------------------------------------------------------------- /contents/check-if-a-string-is-a-palindrome.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | contributors: 4 | - marcobiedermann 5 | created: '2020-05-18' 6 | title: Check if a string is a palindrome 7 | updated: '2021-10-13' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js isPalindrome.js 13 | const isPalindrome = (str) => str === str.split('').reverse().join(''); 14 | ``` 15 | 16 | **TypeScript version** 17 | 18 | ```ts isPalindrome.ts 19 | const isPalindrome = (str: string): boolean => str === str.split('').reverse().join(''); 20 | ``` 21 | 22 | **Examples** 23 | 24 | ```js examples.js 25 | isPalindrome('abc'); // false 26 | isPalindrom('abcba'); // true 27 | ``` 28 | -------------------------------------------------------------------------------- /contents/replace-all-line-breaks-with-br-elements.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2020-04-19' 4 | title: Replace all line breaks with br elements 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js nl2br.js 11 | const nl2br = (str) => str.replace(new RegExp('\r?\n', 'g'), '
'); 12 | 13 | // In React 14 | str.split('\n').map((item, index) => ( 15 | 16 | {item} 17 |
18 |
19 | )); 20 | ``` 21 | 22 | **TypeScript version** 23 | 24 | ```ts nl2br.ts 25 | const nl2br = (str: string): string => str.replace(new RegExp('\r?\n', 'g'), '
'); 26 | ``` 27 | -------------------------------------------------------------------------------- /contents/validate-a-gregorian-date.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2020-05-03' 4 | title: Validate a Gregorian date 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js 11 | // `m`: the month (zero-based index) 12 | // `d`: the day 13 | // `y`: the year 14 | const isValidDate = (m, d, y) => 0 <= m && m <= 11 && 0 < y && y < 32768 && 0 < d && d <= new Date(y, m, 0).getDate(); 15 | ``` 16 | 17 | **TypeScript version** 18 | 19 | ```ts isValidDate.ts 20 | const isValidDate = (m: number, d: number, y: number): boolean => 21 | 0 <= m && m <= 11 && 0 < y && y < 32768 && 0 < d && d <= new Date(y, m, 0).getDate(); 22 | ``` 23 | -------------------------------------------------------------------------------- /contents/check-if-a-string-contains-lower-case-characters.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2020-05-16' 4 | title: Check if a string contains lower case characters 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js containsLowerCase.js 11 | const containsLowerCase = (str) => str !== str.toUpperCase(); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts containsLowerCase.ts 17 | const containsLowerCase = (str: string): boolean => str !== str.toUpperCase(); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | containsLowerCase('Hello World'); // true 24 | containsLowerCase('HELLO WORLD'); // false 25 | ``` 26 | -------------------------------------------------------------------------------- /contents/check-if-a-string-contains-upper-case-characters.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2020-05-16' 4 | title: Check if a string contains upper case characters 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js containsUpperCase.js 11 | const containsUpperCase = (str) => str !== str.toLowerCase(); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts containsUpperCase.ts 17 | const containsUpperCase = (str: string): boolean => str !== str.toLowerCase(); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | containsUpperCase('Hello World'); // true 24 | containsUpperCase('hello world'); // false 25 | ``` 26 | -------------------------------------------------------------------------------- /contents/remove-falsy-values-from-array.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | contributors: 4 | - vreymond 5 | created: '2020-05-09' 6 | title: Remove falsy values from array 7 | updated: '2021-10-22' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js removeFalsy.js 13 | const removeFalsy = (arr) => arr.filter(Boolean); 14 | ``` 15 | 16 | **TypeScript version** 17 | 18 | ```ts removeFalsy.ts 19 | const removeFalsy = (arr: T[]): T[] => arr.filter(Boolean); 20 | ``` 21 | 22 | **Example** 23 | 24 | ```js example.js 25 | removeFalsy([0, 'a string', '', NaN, true, 5, undefined, 'another string', false]); 26 | // ['a string', true, 5, 'another string'] 27 | ``` 28 | -------------------------------------------------------------------------------- /contents/reverse-the-order-of-lines-of-a-text.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2021-05-30' 4 | title: Reverse the order of lines of a text 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js reverseLines.js 11 | const reverseLines = (str) => str.split(/\r?\n/).reverse().join('\n'); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts reverseLines.ts 17 | const reverseLines = (str: string): string => str.split(/\r?\n/).reverse().join('\n'); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | reverseLines(`one 24 | two 25 | three`); 26 | 27 | /* Output */ 28 | /* 29 | three 30 | two 31 | one 32 | */ 33 | ``` 34 | -------------------------------------------------------------------------------- /contents/get-the-center-point-of-a-dom-rect.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: DOM 3 | created: '2023-12-09' 4 | openGraphCover: /og/1-loc/get-center-point-dom-rect.png 5 | title: Get the center point of a DOMRect 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js getCenter.js 11 | const getCenter = rect => [rect.left + rect.width / 2, rect.top + rect.height / 2]; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts getCenter.ts 17 | const getCenter = (rect: DOMRect): [number, number] => [rect.left + rect.width / 2, rect.top + rect.height / 2]; 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js example.js 23 | getCenter(new DOMRect(0, 0, 200, 400)); // [100, 200] 24 | ``` 25 | -------------------------------------------------------------------------------- /contents/round-a-number-to-a-given-number-of-digits.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Number 3 | created: '2020-05-16' 4 | title: Round a number to a given number of digits 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js round.js 11 | const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts round.ts 17 | const round = (n: number, decimals: number = 0): number => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | round(1.234567, 3); // 1.235 24 | round(1.234567, 4); // 1.2346 25 | ``` 26 | -------------------------------------------------------------------------------- /contents/uncurry-a-function.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Function 3 | created: '2020-05-15' 4 | title: Uncurry a function 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js 10 | // `fn` is a curried function 11 | // `n` is the depth of parameters 12 | const uncurry = 13 | (fn, n = 1) => 14 | (...args) => 15 | ( 16 | (acc) => (args) => 17 | args.reduce((x, y) => x(y), acc) 18 | )(fn)(args.slice(0, n)); 19 | ``` 20 | 21 | **Examples** 22 | 23 | ```js examples.js 24 | const sum = (a) => (b) => (c) => a + b + c; 25 | uncurry(sum, 1)(1)(2)(3); // 6 26 | uncurry(sum, 2)(1, 2)(3); // 6 27 | uncurry(sum, 3)(1, 2, 3); // 6 28 | ``` 29 | -------------------------------------------------------------------------------- /contents/flip-the-arguments-of-a-function.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Function 3 | created: '2020-05-12' 4 | title: Flip the arguments of a function 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js flip.js 10 | // Reverse the order of arguments 11 | const flip = 12 | (fn) => 13 | (...args) => 14 | fn(...args.reverse()); 15 | 16 | // For binary functions 17 | const flip = (fn) => (b, a) => fn(a, b); 18 | 19 | // Or for curried functions 20 | const flip = (fn) => (b) => (a) => fn(a)(b); 21 | ``` 22 | 23 | **Examples** 24 | 25 | ```js examples.js 26 | const isParent = (parent, child) => parent.children.includes(child); 27 | const isChild = flip(isParent); 28 | ``` 29 | -------------------------------------------------------------------------------- /contents/get-a-random-item-and-remove-it-from-an-array.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Random 3 | created: '2021-01-16' 4 | title: Get a random item and remove it from an array 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js randomItem.js 11 | const randomItem = (arr) => arr.splice((Math.random() * arr.length) | 0, 1); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts randomItem.ts 17 | const randomItem = (arr: T[]): T => arr.splice((Math.random() * arr.length) | 0, 1) as unknown as T; 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | const arr = [1, 3, 5, 7, 9]; 24 | randomItem(arr); // 7 25 | // arr = [1, 3, 5, 9] 26 | ``` 27 | -------------------------------------------------------------------------------- /contents/check-if-a-path-is-relative.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2020-05-15' 4 | title: Check if a path is relative 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isRelative.js 11 | const isRelative = (path) => !/^([a-z]+:)?[\\/]/i.test(path); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts isRelative.ts 17 | const isRelative = (path: string): boolean => !/^([a-z]+:)?[\\/]/i.test(path); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | isRelative('/foo/bar/baz'); // false 24 | isRelative('C:\\foo\\bar\\baz'); // false 25 | isRelative('foo/bar/baz.txt'); // true 26 | isRelative('foo.md'); // true 27 | ``` 28 | -------------------------------------------------------------------------------- /contents/check-if-a-value-is-a-string.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2020-06-05' 4 | title: Check if a value is a string 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isString.js 11 | const isString = (value) => Object.prototype.toString.call(value) === '[object String]'; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts isString.ts 17 | const isString = (value: any): boolean => Object.prototype.toString.call(value) === '[object String]'; 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | isString('hello world'); // true 24 | isString(new String('hello world')); // true 25 | isString(10); // false 26 | ``` 27 | -------------------------------------------------------------------------------- /contents/determine-one-year-from-now.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Date Time 3 | created: '2022-08-21' 4 | title: Determine one year from now 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js plusOneYear.js 10 | const plusOneYear = ((d) => new Date(d.setFullYear(d.getFullYear() + 1)))(new Date()); 11 | ``` 12 | 13 | **TypeScript version** 14 | 15 | ```ts plusOneYear.ts 16 | const plusOneYear: Date = ((d) => new Date(d.setFullYear(d.getFullYear() + 1)))(new Date()); 17 | ``` 18 | 19 | ## See also 20 | 21 | - [Get the tomorrow date](https://phuoc.ng/collection/1-loc/get-the-tomorrow-date/) 22 | - [Get the yesterday date](https://phuoc.ng/collection/1-loc/get-the-yesterday-date/) 23 | -------------------------------------------------------------------------------- /contents/check-if-an-array-is-not-empty.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | contributors: 4 | - fenilgandhi 5 | - marcobiedermann 6 | created: '2020-05-06' 7 | title: Check if an array is not empty 8 | updated: '2021-10-13' 9 | --- 10 | 11 | **JavaScript version** 12 | 13 | ```js isNotEmpty.js 14 | const isNotEmpty = (arr) => Array.isArray(arr) && Object.keys(arr).length > 0; 15 | ``` 16 | 17 | **TypeScript version** 18 | 19 | ```ts isNotEmpty.ts 20 | const isNotEmpty = (arr: any): boolean => Array.isArray(arr) && Object.keys(arr).length > 0; 21 | ``` 22 | 23 | **Examples** 24 | 25 | ```js examples.js 26 | isNotEmpty([]); // false 27 | isNotEmpty([1, 2, 3]); // true 28 | ``` 29 | -------------------------------------------------------------------------------- /contents/convert-celsius-to-fahrenheit.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Misc 3 | contributors: 4 | - mizanmahi 5 | created: '2020-05-09' 6 | title: Convert Celsius to Fahrenheit 7 | updated: '2021-10-13' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js celsiusToFahrenheit.js 13 | const celsiusToFahrenheit = (celsius) => (celsius * 9) / 5 + 32; 14 | ``` 15 | 16 | **TypeScript version** 17 | 18 | ```ts celsiusToFahrenheit.ts 19 | const celsiusToFahrenheit = (celsius: number): number => (celsius * 9) / 5 + 32; 20 | ``` 21 | 22 | **Examples** 23 | 24 | ```js examples.js 25 | celsiusToFahrenheit(15); // 59 26 | celsiusToFahrenheit(0); // 32 27 | celsiusToFahrenheit(-20); // -4 28 | ``` 29 | -------------------------------------------------------------------------------- /contents/format-a-date-for-the-given-locale.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Date Time 3 | created: '2020-05-06' 4 | title: Format a date for the given locale 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js 11 | // `date` is a `Date` object 12 | // `locale` is a locale (en-US, pt-BR, for example) 13 | const format = (date, locale) => new Intl.DateTimeFormat(locale).format(date); 14 | ``` 15 | 16 | **TypeScript version** 17 | 18 | ```ts format.ts 19 | const format = (date: Date, locale: string): string => new Intl.DateTimeFormat(locale).format(date); 20 | ``` 21 | 22 | **Example** 23 | 24 | ```js example.js 25 | format(new Date(), 'pt-BR'); // 06/05/2020 26 | ``` 27 | -------------------------------------------------------------------------------- /contents/get-all-nth-items-of-an-array.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | created: '2021-02-20' 4 | title: 'Get all n-th items of an array' 5 | updated: '2021-10-22' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js getNthItems.js 11 | const getNthItems = (arr, nth) => arr.filter((_, i) => i % nth === nth - 1); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts getNthItems.ts 17 | const getNthItems = (arr: T[], nth: number): T[] => arr.filter((_, i) => i % nth === nth - 1); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | getNthItems([1, 2, 3, 4, 5, 6, 7, 8, 9], 2); // [2, 4, 6, 8] 24 | getNthItems([1, 2, 3, 4, 5, 6, 7, 8, 9], 3); // [3, 6, 9] 25 | ``` 26 | -------------------------------------------------------------------------------- /contents/repeat-a-string.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | contributors: 4 | - chety 5 | created: '2020-04-19' 6 | title: Repeat a string 7 | updated: '2021-10-13' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js repeat.js 13 | const repeat = (str, numberOfTimes) => str.repeat(numberOfTimes); 14 | 15 | // Or 16 | const repeat = (str, numberOfTimes) => Array(numberOfTimes + 1).join(str); 17 | ``` 18 | 19 | **TypeScript version** 20 | 21 | ```ts repeat.ts 22 | const repeat = (str: string, numberOfTimes: number): string => str.repeat(numberOfTimes); 23 | 24 | // Or 25 | const repeat = (str: string, numberOfTimes: number): string => Array(numberOfTimes + 1).join(str); 26 | ``` 27 | -------------------------------------------------------------------------------- /contents/trim-some-character.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | contributors: 4 | - mahdiyar 5 | created: '2020-06-04' 6 | title: Trim some character 7 | updated: '2021-10-13' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js trim.js 13 | const trim = (str, char) => str.split(char).filter(Boolean).join(); 14 | ``` 15 | 16 | **TypeScript version** 17 | 18 | ```ts trim.ts 19 | const trim = (str: string, char: string): string => str.split(char).filter(Boolean).join(); 20 | ``` 21 | 22 | **Examples** 23 | 24 | ```js examples.js 25 | trim('/hello world//', '/'); // hello world 26 | trim('"hello world"', '"'); // hello world 27 | trim(' hello world ', ' '); // hello world 28 | ``` 29 | -------------------------------------------------------------------------------- /contents/convert-a-base64-encoded-string-to-an-uint8-array.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2021-11-11' 4 | title: Convert a base64 encoded string to an uint8 array 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js base64ToUint8.js 10 | const base64ToUint8 = (str) => Uint8Array.from(atob(str), (c) => c.charCodeAt(0)); 11 | ``` 12 | 13 | **TypeScript version** 14 | 15 | ```ts base64ToUint8.ts 16 | const base64ToUint8 = (str: string): Uint8Array => Uint8Array.from(atob(str), (c) => c.charCodeAt(0)); 17 | ``` 18 | 19 | ## See also 20 | 21 | - [Convert an uint8 array to a base64 encoded string](https://phuoc.ng/collection/1-loc/convert-an-uint8-array-to-a-base64-encoded-string/) 22 | -------------------------------------------------------------------------------- /contents/find-the-index-of-the-maximum-item-of-an-array.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | created: '2021-04-20' 4 | title: Find the index of the maximum item of an array 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js indexOfMax.js 11 | const indexOfMax = (arr) => arr.reduce((prev, curr, i, a) => (curr > a[prev] ? i : prev), 0); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts indexOfMax.ts 17 | const indexOfMax = (arr: number[]): number => arr.reduce((prev, curr, i, a) => (curr > a[prev] ? i : prev), 0); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | indexOfMax([1, 3, 9, 7, 5]); // 2 24 | indexOfMax([1, 3, 7, 7, 5]); // 2 25 | ``` 26 | -------------------------------------------------------------------------------- /contents/find-the-index-of-the-minimum-item-of-an-array.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | created: '2021-04-20' 4 | title: Find the index of the minimum item of an array 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js indexOfMin.js 11 | const indexOfMin = (arr) => arr.reduce((prev, curr, i, a) => (curr < a[prev] ? i : prev), 0); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts indexOfMin.ts 17 | const indexOfMin = (arr: number[]): number => arr.reduce((prev, curr, i, a) => (curr < a[prev] ? i : prev), 0); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | indexOfMin([6, 4, 8, 2, 10]); // 3 24 | indexOfMin([6, 4, 2, 2, 10]); // 2 25 | ``` 26 | -------------------------------------------------------------------------------- /contents/generate-a-random-string-with-given-length.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Random 3 | created: '2020-04-23' 4 | title: Generate a random string with given length 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js generateString.js 11 | const generateString = (length) => 12 | Array(length) 13 | .fill('') 14 | .map((v) => Math.random().toString(36).charAt(2)) 15 | .join(''); 16 | ``` 17 | 18 | **TypeScript version** 19 | 20 | ```ts generateString.ts 21 | const generateString = (length: number): string => 22 | Array(length) 23 | .fill('') 24 | .map((v) => Math.random().toString(36).charAt(2)) 25 | .join(''); 26 | ``` 27 | -------------------------------------------------------------------------------- /contents/remove-duplicate-values-in-an-array.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | created: '2021-03-07' 4 | title: Remove duplicate values in an array 5 | updated: '2021-10-22' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js removeDuplicate.js 11 | const removeDuplicate = (arr) => arr.filter((i) => arr.indexOf(i) === arr.lastIndexOf(i)); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts removeDuplicate.ts 17 | const removeDuplicate = (arr: T[]): T[] => arr.filter((i) => arr.indexOf(i) === arr.lastIndexOf(i)); 18 | ``` 19 | 20 | **Example** 21 | 22 | ```js example.js 23 | removeDuplicate(['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']); //  ['h', 'e', 'w', 'r', 'd'] 24 | ``` 25 | -------------------------------------------------------------------------------- /contents/convert-a-windows-file-path-to-unix-path.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2020-05-15' 4 | title: Convert a Windows file path to Unix path 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js toUnixPath.js 11 | const toUnixPath = (path) => path.replace(/[\\/]+/g, '/').replace(/^([a-zA-Z]+:|\.\/)/, ''); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts toUnixPath.ts 17 | const toUnixPath = (path: string): string => path.replace(/[\\/]+/g, '/').replace(/^([a-zA-Z]+:|\.\/)/, ''); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | toUnixPath('./foo/bar/baz'); // foo/bar/baz 24 | toUnixPath('C:\\foo\\bar\\baz'); // /foo/bar/baz 25 | ``` 26 | -------------------------------------------------------------------------------- /contents/delay-the-evaluation-of-a-function.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Function 3 | created: '2020-05-12' 4 | title: Delay the evaluation of a function 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js thunkfy.js 10 | // returns a new version of `fn` that returns values as lazy evaluable 11 | const thunkfy = 12 | (fn) => 13 | (...args) => 14 | () => 15 | fn(...args); 16 | ``` 17 | 18 | **Examples** 19 | 20 | ```js examples.js 21 | const heavyComputation = (x) => doStuff(x); 22 | const unnecessarySlow = manyThings.map(heavyComputation).find((result) => result.criteria); 23 | const probablyFaster = manyThings.map(thunkfy(heavyComputation)).find((thunk) => thunk().criteria); 24 | ``` 25 | -------------------------------------------------------------------------------- /contents/toggle-an-element.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: DOM 3 | contributors: 4 | - islamozbek 5 | created: '2020-04-19' 6 | title: Toggle an element 7 | updated: '2021-10-13' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js toggle.js 13 | const toggle = (ele) => (ele.style.display = ele.style.display === 'none' ? 'block' : 'none'); 14 | 15 | // Or 16 | const toggle = (ele) => (ele.hidden = !ele.hidden); 17 | ``` 18 | 19 | **TypeScript version** 20 | 21 | ```ts toggle.ts 22 | const toggle = (ele: HTMLElement): string => (ele.style.display = ele.style.display === 'none' ? 'block' : 'none'); 23 | 24 | // Or 25 | const toggle = (ele: HTMLElement): boolean => (ele.hidden = !ele.hidden); 26 | ``` 27 | -------------------------------------------------------------------------------- /contents/find-the-length-of-the-longest-string-in-an-array.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | contributors: 4 | - codepo8 5 | created: '2020-04-30' 6 | title: Find the length of the longest string in an array 7 | updated: '2021-10-13' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js findLongest.js 13 | const findLongest = (words) => Math.max(...words.map((el) => el.length)); 14 | ``` 15 | 16 | **TypeScript version** 17 | 18 | ```ts findLongest.ts 19 | const findLongest = (words: string[]): number => Math.max(...words.map((el) => el.length)); 20 | ``` 21 | 22 | **Example** 23 | 24 | ```js example.js 25 | findLongest(['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']); // 6 26 | ``` 27 | -------------------------------------------------------------------------------- /contents/get-the-rank-of-an-array-of-numbers.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | created: '2020-04-19' 4 | title: Get the rank of an array of numbers 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js ranking.js 11 | const ranking = (arr) => arr.map((x, y, z) => z.filter((w) => w > x).length + 1); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts ranking.ts 17 | const ranking = (arr: number[]): number[] => arr.map((x, y, z) => z.filter((w) => w > x).length + 1); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | ranking([80, 65, 90, 50]); // [2, 3, 1, 4] 24 | ranking([80, 80, 70, 50]); // [1, 1, 3, 4] 25 | ranking([80, 80, 80, 50]); // [1, 1, 1, 4] 26 | ``` 27 | -------------------------------------------------------------------------------- /contents/pick-random-lines-from-a-text-document.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Random 3 | created: '2021-06-01' 4 | title: Pick random lines from a text document 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js randomLines.js 10 | const randomLines = (str, count) => 11 | str 12 | .split(/\r?\n/) 13 | .reduce( 14 | (p, _, __, arr) => 15 | p[0] < count ? [p[0] + 1, p[1].concat(arr.splice((Math.random() * arr.length) | 0, 1))] : p, 16 | [0, []] 17 | )[1]; 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | randomLines( 24 | `one 25 | two 26 | three 27 | four 28 | five`, 29 | 2 30 | ); 31 | 32 | // ['one', 'four'] 33 | ``` 34 | -------------------------------------------------------------------------------- /contents/replace-the-first-given-number-of-characters-of-a-string-with-another-character.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2020-06-15' 4 | title: Replace the first given number of characters of a string with another character 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js mask.js 11 | const mask = (str, num, mask) => `${str}`.slice(num).padStart(`${str}`.length, mask); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts mask.ts 17 | const mask = (str: string, num: number, mask: string): string => `${str}`.slice(num).padStart(`${str}`.length, mask); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | mask(1234567890, 3, '*'); // ***4567890 24 | ``` 25 | -------------------------------------------------------------------------------- /contents/check-if-a-url-is-absolute.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2020-05-15' 4 | title: Check if a URL is absolute 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isAbsoluteUrl.js 11 | const isAbsoluteUrl = (url) => /^[a-z][a-z0-9+.-]*:/.test(url); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts isAbsoluteUrl.ts 17 | const isAbsoluteUrl = (url: string): boolean => /^[a-z][a-z0-9+.-]*:/.test(url); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | isAbsoluteUrl('https://phuoc.ng'); // true 24 | isAbsoluteUrl('https://phuoc.ng/collection/1-loc'); // true 25 | isAbsoluteUrl('phuoc.ng'); // false 26 | isAbsoluteUrl('//phuoc.ng'); // false 27 | ``` 28 | -------------------------------------------------------------------------------- /contents/memoize-a-function.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Function 3 | contributors: 4 | - Kikobeats 5 | created: '2020-05-16' 6 | title: Memoize a function 7 | updated: '2021-10-06' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js memoize.js 13 | const memoize = (fn) => 14 | ( 15 | (cache = Object.create(null)) => 16 | (arg) => 17 | cache[arg] || (cache[arg] = fn(arg)) 18 | )(); 19 | ``` 20 | 21 | **Examples** 22 | 23 | ```js examples.js 24 | // Calculate Fibonacci numbers 25 | const fibo = memoize((n) => (n <= 2 ? 1 : fibo(n - 1) + fibo(n - 2))); 26 | 27 | fibo(1); // 1 28 | fibo(2); // 1 29 | fibo(3); // 2 30 | fibo(4); // 3 31 | fibo(5); // 5 32 | fibo(6); // 8 33 | ``` 34 | -------------------------------------------------------------------------------- /contents/round-a-number-to-the-nearest-multiple-of-a-given-value.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Math 3 | created: '2021-05-11' 4 | title: Round a number to the nearest multiple of a given value 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js roundNearest.js 11 | const roundNearest = (value, nearest) => Math.round(value / nearest) * nearest; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts roundNearest.ts 17 | const roundNearest = (value: number, nearest: number): number => Math.round(value / nearest) * nearest; 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | roundNearest(100, 30); // 90 24 | roundNearest(200, 30); // 210 25 | roundNearest(200, 40); // 200 26 | ``` 27 | -------------------------------------------------------------------------------- /contents/check-if-a-given-integer-is-a-prime-number.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2020-04-19' 4 | title: Check if a given integer is a prime number 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isPrime.js 11 | const isPrime = (n) => 12 | n > 1 && 13 | Array(Math.floor(Math.sqrt(n)) - 1) 14 | .fill(0) 15 | .map((_, i) => i + 2) 16 | .every((i) => n % i !== 0); 17 | ``` 18 | 19 | **TypeScript version** 20 | 21 | ```ts isPrime.ts 22 | const isPrime = (n: number): boolean => 23 | n > 1 && 24 | Array(Math.floor(Math.sqrt(n)) - 1) 25 | .fill(0) 26 | .map((_, i) => i + 2) 27 | .every((i) => n % i !== 0); 28 | ``` 29 | -------------------------------------------------------------------------------- /contents/get-hours-and-minutes-from-decimal-time.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Date Time 3 | contributors: 4 | - ognjenst 5 | created: '2022-12-27' 6 | title: Get the hours and minutes from the decimal time 7 | --- 8 | 9 | **JavaScript version** 10 | 11 | ```js getHoursAndMinutes.js 12 | const getHoursAndMinutes = (value) => [Math.floor(value), Math.floor((value * 60) % 60)]; 13 | ``` 14 | 15 | **TypeScript version** 16 | 17 | ```ts getHoursAndMinutes.ts 18 | const getHoursAndMinutes = (value: number): [number, number] => [Math.floor(value), Math.floor((value * 60) % 60)]; 19 | ``` 20 | 21 | **Examples** 22 | 23 | ```js examples.js 24 | getHoursAndMinutes(4.5); //[4, 30] 25 | getHoursAndMinutes(7.89); // [7, 53] 26 | ``` 27 | -------------------------------------------------------------------------------- /contents/get-random-items-of-an-array.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Random 3 | created: '2021-01-16' 4 | title: Get random items of an array 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js randomItems.js 10 | const randomItems = (arr, count) => 11 | arr 12 | .concat() 13 | .reduce( 14 | (p, _, __, arr) => 15 | p[0] < count ? [p[0] + 1, p[1].concat(arr.splice((Math.random() * arr.length) | 0, 1))] : p, 16 | [0, []] 17 | )[1]; 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | randomItems([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3); // [4, 8, 5] 24 | randomItems(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'], 4); // ['e', 'c', 'h', 'j'] 25 | ``` 26 | -------------------------------------------------------------------------------- /contents/sort-an-array-of-dates.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Date Time 3 | created: '2020-04-19' 4 | title: Sort an array of dates 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js sortDescending.js 11 | // `arr` is an array of `Date` items 12 | const sortDescending = (arr) => arr.sort((a, b) => a.getTime() > b.getTime()); 13 | 14 | const sortAscending = (arr) => arr.sort((a, b) => a.getTime() < b.getTime()); 15 | ``` 16 | 17 | **TypeScript version** 18 | 19 | ```ts sortDescending.ts 20 | const sortDescending = (arr: Date[]): Date[] => arr.sort((a, b) => a.getTime() - b.getTime()); 21 | 22 | const sortAscending = (arr: Date[]): Date[] => arr.sort((a, b) => b.getTime() - a.getTime()); 23 | ``` 24 | -------------------------------------------------------------------------------- /contents/wait-for-an-amount-of-time.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Misc 3 | contributors: 4 | - furkankose 5 | created: '2020-05-06' 6 | openGraphCover: /og/1-loc/wait-amount-time.png 7 | title: Wait for an amount of time 8 | updated: '2021-10-13' 9 | --- 10 | 11 | **JavaScript version** 12 | 13 | ```js wait.js 14 | const wait = async (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)); 15 | ``` 16 | 17 | **TypeScript version** 18 | 19 | ```ts wait.ts 20 | const wait = async (milliseconds: number) => new Promise((resolve) => setTimeout(resolve, milliseconds)); 21 | ``` 22 | 23 | ## See also 24 | 25 | - [Wait for the next event loop](https://phuoc.ng/collection/1-loc/wait-for-the-next-event-loop/) 26 | -------------------------------------------------------------------------------- /contents/get-the-day-of-the-year-from-a-date.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Date Time 3 | created: '2020-05-16' 4 | title: Get the day of the year from a date 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js dayOfYear.js 11 | // `date` is a Date object 12 | const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24)); 13 | ``` 14 | 15 | **TypeScript version** 16 | 17 | ```ts dayOfYear.ts 18 | const dayOfYear = (date: Date): number => 19 | Math.floor((date.valueOf() - new Date(date.getFullYear(), 0, 0).valueOf()) / (1000 * 60 * 60 * 24)); 20 | ``` 21 | 22 | **Example** 23 | 24 | ```js example.js 25 | dayOfYear(new Date(2020, 04, 16)); // 137 26 | ``` 27 | -------------------------------------------------------------------------------- /contents/check-if-a-number-is-negative.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | contributors: 4 | - sadirde 5 | - tugsanunlu 6 | created: '2020-05-07' 7 | title: Check if a number is negative 8 | updated: '2021-10-13' 9 | --- 10 | 11 | **JavaScript version** 12 | 13 | ```js isNegative.js 14 | const isNegative = (n) => Math.sign(n) === -1; 15 | 16 | // Or 17 | const isNegative = (n) => n < 0; 18 | ``` 19 | 20 | **TypeScript version** 21 | 22 | ```ts isNegative.ts 23 | const isNegative = (n: number): boolean => Math.sign(n) === -1; 24 | 25 | // Or 26 | const isNegative = (n: number): boolean => n < 0; 27 | ``` 28 | 29 | **Examples** 30 | 31 | ```js examples.js 32 | isNegative(-3); // true 33 | isNegative(8); // false 34 | ``` 35 | -------------------------------------------------------------------------------- /contents/calculate-fibonacci-numbers.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Number 3 | created: '2020-05-16' 4 | title: Calculate Fibonacci numbers 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js fibo.js 11 | const fibo = (n, memo = {}) => memo[n] || (n <= 2 ? 1 : (memo[n] = fibo(n - 1, memo) + fibo(n - 2, memo))); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts fibo.ts 17 | const fibo = (n: number, memo: Record = {}): number => 18 | memo[n] || (n <= 2 ? 1 : (memo[n] = fibo(n - 1, memo) + fibo(n - 2, memo))); 19 | ``` 20 | 21 | **Examples** 22 | 23 | ```js examples.js 24 | fibo(1); // 1 25 | fibo(2); // 1 26 | fibo(3); // 2 27 | fibo(4); // 3 28 | fibo(5); // 5 29 | fibo(6); // 8 30 | ``` 31 | -------------------------------------------------------------------------------- /contents/convert-an-array-of-strings-to-numbers.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | contributors: 4 | - jonrandy 5 | created: '2020-04-23' 6 | title: Convert an array of strings to numbers 7 | updated: '2021-10-13' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js toNumbers.js 13 | const toNumbers = (arr) => arr.map(Number); 14 | 15 | // Or 16 | const toNumbers = (arr) => arr.map((x) => +x); 17 | ``` 18 | 19 | **TypeScript version** 20 | 21 | ```ts toNumbers.ts 22 | const toNumbers = (arr: string[]): number[] => arr.map(Number); 23 | 24 | // Or 25 | const toNumbers = (arr: string[]): number[] => arr.map((x) => +x); 26 | ``` 27 | 28 | **Example** 29 | 30 | ```js example.js 31 | toNumbers(['2', '3', '4']); // [2, 3, 4] 32 | ``` 33 | -------------------------------------------------------------------------------- /contents/sort-an-object-by-its-properties.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Object 3 | created: '2021-04-20' 4 | title: Sort an object by its properties 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js sort.js 10 | const sort = (obj) => 11 | Object.keys(obj) 12 | .sort() 13 | .reduce((p, c) => ((p[c] = obj[c]), p), {}); 14 | ``` 15 | 16 | **Examples** 17 | 18 | ```js examples.js 19 | const colors = { 20 | white: '#ffffff', 21 | black: '#000000', 22 | red: '#ff0000', 23 | green: '#008000', 24 | blue: '#0000ff', 25 | }; 26 | sort(colors); 27 | /* 28 | { 29 | black: '#000000', 30 | blue: '#0000ff', 31 | green: '#008000', 32 | red: '#ff0000', 33 | white: '#ffffff', 34 | } 35 | */ 36 | ``` 37 | -------------------------------------------------------------------------------- /contents/sort-the-characters-of-a-string-in-the-alphabetical-order.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2020-05-16' 4 | title: Sort the characters of a string in the alphabetical order 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js sort.js 11 | const sort = (str) => 12 | str 13 | .split('') 14 | .sort((a, b) => a.localeCompare(b)) 15 | .join(''); 16 | ``` 17 | 18 | **TypeScript version** 19 | 20 | ```ts sort.ts 21 | const sort = (str: string): string => 22 | str 23 | .split('') 24 | .sort((a, b) => a.localeCompare(b)) 25 | .join(''); 26 | ``` 27 | 28 | **Examples** 29 | 30 | ```js examples.js 31 | sort('hello world'); // dehllloorw 32 | ``` 33 | -------------------------------------------------------------------------------- /contents/swap-two-array-items.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | created: '2021-03-13' 4 | title: Swap two array items 5 | updated: '2021-10-22' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js swapItems.js 11 | // `i` must be less than `j` 12 | const swapItems = (a, i, j) => 13 | (a[i] && a[j] && [...a.slice(0, i), a[j], ...a.slice(i + 1, j), a[i], ...a.slice(j + 1)]) || a; 14 | ``` 15 | 16 | **TypeScript version** 17 | 18 | ```ts swapItems.ts 19 | 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; 20 | ``` 21 | 22 | **Example** 23 | 24 | ```js example.js 25 | swapItems([1, 2, 3, 4, 5], 1, 4); // [1, 5, 3, 4, 2] 26 | ``` 27 | -------------------------------------------------------------------------------- /contents/check-if-a-string-contains-only-digits.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2020-05-09' 4 | title: Check if a string contains only digits 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isNumeric.js 11 | const isNumeric = (str) => !/[^0-9]/.test(str); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts isNumeric.ts 17 | const isNumeric = (str: string): boolean => !/[^0-9]/.test(str); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | isNumeric(2); // true 24 | isNumeric('23'); // true 25 | isNumeric('00123'); // true 26 | 27 | isNumeric('1.23'); // false 28 | isNumeric('-Infinity'); // false 29 | isNumeric('Infinity'); // false 30 | isNumeric('NaN'); // false 31 | ``` 32 | -------------------------------------------------------------------------------- /contents/check-if-an-object-is-empty.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | contributors: 4 | - robinpokorny 5 | created: '2020-04-19' 6 | title: Check if an object is empty 7 | updated: '2021-10-13' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js isEmpty.js 13 | const isEmpty = (obj) => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object; 14 | 15 | // Or for enumerable property names only 16 | const isEmpty = (obj) => JSON.stringify(obj) === '{}'; 17 | ``` 18 | 19 | **TypeScript version** 20 | 21 | ```ts isEmpty.ts 22 | const isEmpty = (obj: object): boolean => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object; 23 | 24 | const isEmpty = (obj: object): boolean => JSON.stringify(obj) === '{}'; 25 | ``` 26 | -------------------------------------------------------------------------------- /contents/generate-a-random-hex-color.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Random 3 | contributors: 4 | - robinpokorny 5 | created: '2020-04-19' 6 | title: Generate a random hex color 7 | updated: '2021-10-13' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js randomColor.js 13 | const randomColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`; 14 | 15 | // Or 16 | const randomColor = () => `#${(~~(Math.random() * (1 << 24))).toString(16)}`; 17 | ``` 18 | 19 | **TypeScript version** 20 | 21 | ```ts randomColor.ts 22 | const randomColor = (): string => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`; 23 | 24 | // Or 25 | const randomColor = (): string => `#${(~~(Math.random() * (1 << 24))).toString(16)}`; 26 | ``` 27 | -------------------------------------------------------------------------------- /contents/check-if-a-year-is-leap-year.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2020-04-19' 4 | title: Check if a year is leap year 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isLeapYear.js 11 | const isLeapYear = (year) => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; 12 | 13 | // Or 14 | // Get the number of days in February 15 | const isLeapYear = (year) => new Date(year, 1, 29).getDate() === 29; 16 | ``` 17 | 18 | **TypeScript version** 19 | 20 | ```ts isLeapYear.ts 21 | const isLeapYear = (year: number): boolean => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; 22 | 23 | // Or 24 | const isLeapYear = (year: number): boolean => new Date(year, 1, 29).getDate() === 29; 25 | ``` 26 | -------------------------------------------------------------------------------- /contents/convert-a-string-to-url-slug.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2020-05-04' 4 | title: Convert a string to URL slug 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js slugify.js 11 | const slugify = (str) => 12 | str 13 | .toLowerCase() 14 | .replace(/\s+/g, '-') 15 | .replace(/[^\w-]+/g, ''); 16 | ``` 17 | 18 | **TypeScript version** 19 | 20 | ```ts slugify.ts 21 | const slugify = (str: string): string => 22 | str 23 | .toLowerCase() 24 | .replace(/\s+/g, '-') 25 | .replace(/[^\w-]+/g, ''); 26 | ``` 27 | 28 | **Examples** 29 | 30 | ```js examples.js 31 | slugify('Chapter One: Once upon a time...'); // 'chapter-one-once-upon-a-time' 32 | ``` 33 | -------------------------------------------------------------------------------- /contents/add-am-pm-suffix-to-an-hour.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Date Time 3 | created: '2021-02-20' 4 | title: Add AM PM suffix to an hour 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js suffixAmPm.js 11 | // `h` is an hour number between 0 and 23 12 | const suffixAmPm = (h) => `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? 'am' : 'pm'}`; 13 | ``` 14 | 15 | **TypeScript version** 16 | 17 | ```ts suffixAmPm.ts 18 | const suffixAmPm = (h: number): string => `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? 'am' : 'pm'}`; 19 | ``` 20 | 21 | **Examples** 22 | 23 | ```js examples.js 24 | suffixAmPm(0); // '12am' 25 | suffixAmPm(5); // '5am' 26 | suffixAmPm(12); // '12pm' 27 | suffixAmPm(15); // '3pm' 28 | suffixAmPm(23); // '11pm' 29 | ``` 30 | -------------------------------------------------------------------------------- /contents/calculate-the-number-of-difference-days-between-two-dates.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Date Time 3 | created: '2020-04-19' 4 | title: Calculate the number of difference days between two dates 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js diffDays.js 11 | const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24)); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts diffDays.ts 17 | const diffDays = (date: Date, otherDate: Date): number => 18 | Math.ceil(Math.abs(date.valueOf() - otherDate.valueOf()) / (1000 * 60 * 60 * 24)); 19 | ``` 20 | 21 | **Examples** 22 | 23 | ```js examples.js 24 | diffDays(new Date('2014-12-19'), new Date('2020-01-01')); // 1839 25 | ``` 26 | -------------------------------------------------------------------------------- /contents/check-if-a-rectangle-contains-other-one.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Math 3 | created: '2021-04-08' 4 | title: Check if a rectangle contains other one 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js contains.js 11 | // Returns true if `a` contains `b` 12 | // (x1, y1) and (x2, y2) are top-left and bottom-right corners 13 | const contains = (a, b) => a.x1 <= b.x1 && a.y1 <= b.y1 && a.x2 >= b.x2 && a.y2 >= b.y2; 14 | ``` 15 | 16 | **TypeScript version** 17 | 18 | ```ts contains.ts 19 | interface Rect { 20 | x1: number; 21 | x2: number; 22 | y1: number; 23 | y2: number; 24 | } 25 | 26 | const contains = (a: Rect, b: Rect): boolean => a.x1 <= b.x1 && a.y1 <= b.y1 && a.x2 >= b.x2 && a.y2 >= b.y2; 27 | ``` 28 | -------------------------------------------------------------------------------- /contents/check-if-a-rectangle-overlaps-other-one.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Math 3 | created: '2021-04-08' 4 | title: Check if a rectangle overlaps other one 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js overlaps.js 11 | // Returns true if `a` overlaps `b` 12 | // (x1, y1) and (x2, y2) are top-left and bottom-right corners 13 | const overlaps = (a, b) => (a.x1 < b.x2 && b.x1 < a.x2) || (a.y1 < b.y2 && b.y1 < a.y2); 14 | ``` 15 | 16 | **TypeScript version** 17 | 18 | ```ts overlaps.ts 19 | interface Rect { 20 | x1: number; 21 | x2: number; 22 | y1: number; 23 | y2: number; 24 | } 25 | 26 | const overlaps = (a: Rect, b: Rect): boolean => (a.x1 < b.x2 && b.x1 < a.x2) || (a.y1 < b.y2 && b.y1 < a.y2); 27 | ``` 28 | -------------------------------------------------------------------------------- /contents/check-if-a-string-is-a-hexadecimal-color.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2020-06-09' 4 | title: Check if a string is a hexadecimal color 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isHexColor.js 11 | const isHexColor = (color) => /^#([0-9A-F]{3}|[0-9A-F]{4}|[0-9A-F]{6}|[0-9A-F]{8})$/i.test(color); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts isHexColor.ts 17 | const isHexColor = (color: string): boolean => /^#([0-9A-F]{3}|[0-9A-F]{4}|[0-9A-F]{6}|[0-9A-F]{8})$/i.test(color); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | isHexColor('#012'); // true 24 | isHexColor('#A1B2C3'); // true 25 | isHexColor('012'); // false 26 | isHexColor('#GHIJKL'); // false 27 | ``` 28 | -------------------------------------------------------------------------------- /contents/unzip-an-array-of-arrays.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | created: '2020-05-15' 4 | title: Unzip an array of arrays 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js unzip.js 11 | const unzip = (arr) => 12 | arr.reduce( 13 | (acc, c) => (c.forEach((v, i) => acc[i].push(v)), acc), 14 | Array.from({ length: Math.max(...arr.map((a) => a.length)) }, (_) => []) 15 | ); 16 | ``` 17 | 18 | **Example** 19 | 20 | ```js example.js 21 | unzip([ 22 | ['a', 1], 23 | ['b', 2], 24 | ['c', 3], 25 | ['d', 4], 26 | ['e', 5], 27 | ]); // [['a', 'b', 'c', 'd', 'e'], [1, 2, 3, 4, 5]] 28 | 29 | /* 30 | a 1 31 | b 2 32 | c 3 33 | d 4 34 | e 5 35 | */ 36 | ``` 37 | -------------------------------------------------------------------------------- /contents/partition-an-array-based-on-a-condition.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | contributors: 4 | - TangSY 5 | created: '2020-05-13' 6 | title: Partition an array based on a condition 7 | updated: '2021-10-22' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js partition.js 13 | const partition = (arr, criteria) => arr.reduce((acc, i) => (acc[criteria(i) ? 0 : 1].push(i), acc), [[], []]); 14 | ``` 15 | 16 | **TypeScript version** 17 | 18 | ```ts partition.ts 19 | const partition = (arr: T[], criteria: (a: T) => boolean): T[][] => arr.reduce((acc, i) => (acc[criteria(i) ? 0 : 1].push(i), acc), [[], []]); 20 | ``` 21 | 22 | **Example** 23 | 24 | ```js example.js 25 | partition([1, 2, 3, 4, 5], (n) => n % 2); // [[1, 3, 5], [2, 4]] 26 | ``` 27 | -------------------------------------------------------------------------------- /contents/flatten-an-array.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | contributors: 4 | - nico2che 5 | created: '2020-05-01' 6 | title: Flatten an array 7 | updated: '2021-10-13' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js flat.js 13 | const flat = (arr) => 14 | [].concat.apply( 15 | [], 16 | arr.map((a) => (Array.isArray(a) ? flat(a) : a)) 17 | ); 18 | 19 | // Or 20 | const flat = (arr) => arr.reduce((a, b) => (Array.isArray(b) ? [...a, ...flat(b)] : [...a, b]), []); 21 | 22 | // Or 23 | // See the browser compatibility at https://caniuse.com/#feat=array-flat 24 | const flat = (arr) => arr.flat(); 25 | ``` 26 | 27 | **Example** 28 | 29 | ```js example.js 30 | flat(['cat', ['lion', 'tiger']]); // ['cat', 'lion', 'tiger'] 31 | ``` 32 | -------------------------------------------------------------------------------- /contents/get-all-subsets-of-an-array.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | created: '2021-02-25' 4 | title: Get all subsets of an array 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js getSubsets.js 11 | const getSubsets = (arr) => arr.reduce((prev, curr) => prev.concat(prev.map((k) => k.concat(curr))), [[]]); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts getSubsets.ts 17 | const getSubsets = (arr: T[]): T[][] => ( 18 | arr.reduce((prev, curr) => prev.concat(prev.map((k) => k.concat(curr))), [[]] as T[][]) 19 | ); 20 | ``` 21 | 22 | **Examples** 23 | 24 | ```js examples.js 25 | getSubsets([1, 2]); // [[], [1], [2], [1, 2]] 26 | getSubsets([1, 2, 3]); // [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] 27 | ``` 28 | -------------------------------------------------------------------------------- /contents/compose-functions.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Function 3 | created: '2020-05-07' 4 | title: Compose functions 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js compose.js 10 | // Compose functions from right to left 11 | const compose = 12 | (...fns) => 13 | (x) => 14 | fns.reduceRight((y, f) => f(y), x); 15 | ``` 16 | 17 | **Examples** 18 | 19 | ```js examples.js 20 | const lowercase = (str) => str.toLowerCase(); 21 | const capitalize = (str) => `${str.charAt(0).toUpperCase()}${str.slice(1)}`; 22 | const reverse = (str) => str.split('').reverse().join(''); 23 | 24 | const fn = compose(reverse, capitalize, lowercase); 25 | 26 | // We will execute `lowercase`, `capitalize` and `reverse` in order 27 | fn('Hello World') === 'dlrow olleH'; 28 | ``` 29 | -------------------------------------------------------------------------------- /contents/get-the-arrays-of-digits-from-a-number.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Number 3 | created: '2020-05-16' 4 | title: Get the arrays of digits from a number 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js digitize.js 11 | const digitize = (n) => `${n}`.split('').map((v) => parseInt(v, 10)); 12 | 13 | // Or 14 | const digitize = (n) => [...`${n}`].map((v) => parseInt(v, 10)); 15 | ``` 16 | 17 | **TypeScript version** 18 | 19 | ```ts digitize.ts 20 | const digitize = (n: number): number[] => `${n}`.split('').map((v) => parseInt(v, 10)); 21 | 22 | // Or 23 | const digitize = (n: number): number[] => [...`${n}`].map((v) => parseInt(v, 10)); 24 | ``` 25 | 26 | **Examples** 27 | 28 | ```js examples.js 29 | digitize(123); // [1, 2, 3] 30 | ``` 31 | -------------------------------------------------------------------------------- /contents/check-if-a-string-contains-only-letters-and-numbers.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2020-06-08' 4 | title: Check if a string contains only letters and numbers 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isAlphanumeric.js 11 | const isAlphanumeric = (str) => /^[0-9A-Z]+$/i.test(str); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts isAlphanumeric.ts 17 | const isAlphanumeric = (str: string): boolean => /^[0-9A-Z]+$/i.test(str); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | isAlphanumeric('helloworld'); // true 24 | isAlphanumeric('HelloWorld'); // true 25 | isAlphanumeric('hello world'); // false 26 | isAlphanumeric('hello123'); // true 27 | isAlphanumeric('hello 123'); // false 28 | ``` 29 | -------------------------------------------------------------------------------- /contents/check-if-multiple-objects-are-equal.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Object 3 | contributors: 4 | - tugsanunlu 5 | created: '2020-05-20' 6 | title: Check if multiple objects are equal 7 | updated: '2021-10-13' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js isEqual.js 13 | const isEqual = (...objects) => objects.every((obj) => JSON.stringify(obj) === JSON.stringify(objects[0])); 14 | ``` 15 | 16 | **TypeScript version** 17 | 18 | ```ts isEqual.ts 19 | const isEqual = (...objects: object[]): boolean => 20 | objects.every((obj) => JSON.stringify(obj) === JSON.stringify(objects[0])); 21 | ``` 22 | 23 | **Examples** 24 | 25 | ```js examples.js 26 | isEqual({ foo: 'bar' }, { foo: 'bar' }); // true 27 | isEqual({ foo: 'bar' }, { bar: 'foo' }); // false 28 | ``` 29 | -------------------------------------------------------------------------------- /contents/remove-duplicate-lines-of-a-text-document.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2021-05-31' 4 | title: Remove duplicate lines of a text document 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js removeDuplicateLines.js 11 | const removeDuplicateLines = (str) => Array.from(new Set(str.split(/\r?\n/))).join('\n'); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts removeDuplicateLines.ts 17 | const removeDuplicateLines = (str: string): string => Array.from(new Set(str.split(/\r?\n/))).join('\n'); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | removeDuplicateLines(`one 24 | three 25 | two 26 | three 27 | one 28 | four`); 29 | 30 | /* Output */ 31 | /* 32 | one 33 | three 34 | two 35 | four 36 | */ 37 | ``` 38 | -------------------------------------------------------------------------------- /contents/trim-the-file-extension-from-a-file-name.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2020-05-30' 4 | title: Trim the file extension from a file name 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js trimExt.js 11 | const trimExt = (fileName) => (fileName.indexOf('.') === -1 ? fileName : fileName.split('.').slice(0, -1).join('.')); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts trimExt.ts 17 | const trimExt = (fileName: string): string => 18 | fileName.indexOf('.') === -1 ? fileName : fileName.split('.').slice(0, -1).join('.'); 19 | ``` 20 | 21 | **Examples** 22 | 23 | ```js examples.js 24 | trimExt('document'); // document 25 | trimExt('document.pdf'); // document 26 | trimExt('document.2020.pdf'); // document.2020 27 | ``` 28 | -------------------------------------------------------------------------------- /contents/unescape-html-special-characters.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2020-05-29' 4 | title: Unescape HTML special characters 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js unescape.js 11 | const unescape = (str) => 12 | str 13 | .replace(/&/g, '&') 14 | .replace(/</g, '<') 15 | .replace(/>/g, '>') 16 | .replace(/�*39;/g, "'") 17 | .replace(/"/g, '"'); 18 | ``` 19 | 20 | **TypeScript version** 21 | 22 | ```ts unescape.ts 23 | const unescape = (str: string): string => 24 | str 25 | .replace(/&/g, '&') 26 | .replace(/</g, '<') 27 | .replace(/>/g, '>') 28 | .replace(/�*39;/g, "'") 29 | .replace(/"/g, '"'); 30 | ``` 31 | -------------------------------------------------------------------------------- /contents/run-promises-in-sequence.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Misc 3 | created: '2020-05-02' 4 | title: Run Promises in sequence 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js run.js 11 | // `promises` is an array of `Promise` 12 | const run = (promises) => promises.reduce((p, c) => p.then((rp) => c.then((rc) => [...rp, rc])), Promise.resolve([])); 13 | ``` 14 | 15 | **TypeScript version** 16 | 17 | ```ts run.ts 18 | const run = (promises: Promise[]): Promise => 19 | promises.reduce((p, c) => p.then((rp) => c.then((rc) => [...rp, rc])), Promise.resolve([])); 20 | ``` 21 | 22 | **Examples** 23 | 24 | ```js examples.js 25 | run(promises).then((results) => { 26 | // `results` is an array of promise results in the same order 27 | }); 28 | ``` 29 | -------------------------------------------------------------------------------- /contents/calculate-the-midpoint-between-two-points.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Math 3 | created: '2021-04-10' 4 | openGraphCover: /og/1-loc/calculate-midpoint-two-points.png 5 | title: Calculate the midpoint between two points 6 | updated: '2021-10-13' 7 | --- 8 | 9 | **JavaScript version** 10 | 11 | ```js midpoint.js 12 | const midpoint = (p1, p2) => [(p1.x + p2.x) / 2, (p1.y + p2.y) / 2]; 13 | ``` 14 | 15 | **TypeScript version** 16 | 17 | ```ts midpoint.ts 18 | interface Point { 19 | x: number; 20 | y: number; 21 | } 22 | 23 | const midpoint = (p1: Point, p2: Point): number[] => [(p1.x + p2.x) / 2, (p1.y + p2.y) / 2]; 24 | ``` 25 | 26 | ## See also 27 | 28 | - [Calculate the midpoint of a given range](https://phuoc.ng/collection/1-loc/calculate-the-midpoint-of-a-given-range/) 29 | -------------------------------------------------------------------------------- /contents/extract-year-month-day-hour-minute-second-and-millisecond-from-a-date.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Date Time 3 | created: '2020-04-19' 4 | title: 'Extract year, month, day, hour, minute, second and millisecond from a date' 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js extract.js 11 | // `date` is a `Date` object 12 | const extract = (date) => 13 | date 14 | .toISOString() 15 | .split(/[^0-9]/) 16 | .slice(0, -1); 17 | 18 | // `extract` is an array of [year, month, day, hour, minute, second, millisecond] 19 | ``` 20 | 21 | **TypeScript version** 22 | 23 | ```ts extract.ts 24 | const extract = (date: Date): string[] => 25 | date 26 | .toISOString() 27 | .split(/[^0-9]/) 28 | .slice(0, -1); 29 | ``` 30 | -------------------------------------------------------------------------------- /contents/get-the-total-number-of-days-in-a-year.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Date Time 3 | created: '2021-04-10' 4 | title: Get the total number of days in a year 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js numberOfDays.js 11 | const numberOfDays = (year) => ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 366 : 365); 12 | 13 | // Or 14 | const numberOfDays = (year) => (new Date(year, 1, 29).getDate() === 29 ? 366 : 365); 15 | ``` 16 | 17 | **TypeScript version** 18 | 19 | ```ts numberOfDays.ts 20 | const numberOfDays = (year: number): number => ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 366 : 365); 21 | 22 | // Or 23 | const numberOfDays = (year: number): number => (new Date(year, 1, 29).getDate() === 29 ? 366 : 365); 24 | ``` 25 | -------------------------------------------------------------------------------- /contents/intersperse-element-between-elements.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | contributors: 4 | - iamandrewluca 5 | created: '2021-12-24' 6 | title: Intersperse element between elements 7 | --- 8 | 9 | **JavaScript version** 10 | 11 | ```js intersperse.js 12 | const intersperse = (a, s) => [...Array(2 * a.length - 1)].map((_, i) => (i % 2 ? s : a[i / 2])); 13 | ``` 14 | 15 | **TypeScript version** 16 | 17 | ```ts 18 | const intersperse = (a: T[], s: T): T[] => [...Array(2 * a.length - 1)].map((_, i) => (i % 2 ? s : a[i / 2])); 19 | ``` 20 | 21 | **Examples** 22 | 23 | ```tsx 24 | intersperse(['A', 'B', 'C'], '/'); // ['A', '/', 'B', '/', 'C'] 25 | intersperse([
  • A
  • ,
  • B
  • ,
  • C
  • ],
  • /
  • ); // [
  • A
  • ,
  • /
  • ,
  • B
  • ,
  • /
  • ,
  • C
  • ] 26 | ``` 27 | -------------------------------------------------------------------------------- /contents/swap-case-of-characters-in-a-string.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2021-02-20' 4 | title: Swap case of characters in a string 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js swapCase.js 11 | const swapCase = (str) => 12 | str 13 | .split('') 14 | .map((c) => (c === c.toLowerCase() ? c.toUpperCase() : c.toLowerCase())) 15 | .join(''); 16 | ``` 17 | 18 | **TypeScript version** 19 | 20 | ```ts swapCase.ts 21 | const swapCase = (str: string): string => 22 | str 23 | .split('') 24 | .map((c) => (c === c.toLowerCase() ? c.toUpperCase() : c.toLowerCase())) 25 | .join(''); 26 | ``` 27 | 28 | **Examples** 29 | 30 | ```js examples.js 31 | swapCase('Hello World'); // 'hELLO wORLD' 32 | ``` 33 | -------------------------------------------------------------------------------- /contents/compose-functions-from-left-to-right.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Function 3 | created: '2020-05-12' 4 | title: Compose functions from left to right 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js pipe.js 10 | // Compose functions from left to right 11 | const pipe = 12 | (...fns) => 13 | (x) => 14 | fns.reduce((y, f) => f(y), x); 15 | ``` 16 | 17 | **Examples** 18 | 19 | ```js examples.js 20 | const lowercase = (str) => str.toLowerCase(); 21 | const capitalize = (str) => `${str.charAt(0).toUpperCase()}${str.slice(1)}`; 22 | const reverse = (str) => str.split('').reverse().join(''); 23 | 24 | const fn = pipe(lowercase, capitalize, reverse); 25 | 26 | // We will execute `lowercase`, `capitalize` and `reverse` in order 27 | fn('Hello World') === 'dlrow olleH'; 28 | ``` 29 | -------------------------------------------------------------------------------- /contents/get-the-intersection-of-arrays.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | contributors: 4 | - vreymond 5 | - robinpokorny 6 | created: '2020-05-09' 7 | title: Get the intersection of arrays 8 | updated: '2021-10-22' 9 | --- 10 | 11 | **JavaScript version** 12 | 13 | ```js getIntersection.js 14 | const getIntersection = (a, ...arr) => [...new Set(a)].filter((v) => arr.every((b) => b.includes(v))); 15 | ``` 16 | 17 | **TypeScript version** 18 | 19 | ```ts getIntersection.ts 20 | const getIntersection = (a: T[], ...arr: T[][]): T[] => [...new Set(a)].filter((v) => arr.every((b) => b.includes(v))); 21 | ``` 22 | 23 | **Examples** 24 | 25 | ```js examples.js 26 | getIntersection([1, 2, 3], [2, 3, 4, 5]); // [2, 3] 27 | getIntersection([1, 2, 3], [2, 3, 4, 5], [1, 3, 5]); // [3] 28 | ``` 29 | -------------------------------------------------------------------------------- /contents/calculate-the-linear-interpolation-between-two-numbers.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Math 3 | created: '2021-05-24' 4 | title: Calculate the linear interpolation between two numbers 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js lerp.js 11 | const lerp = (a, b, amount) => (1 - amount) * a + amount * b; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts lerp.ts 17 | const lerp = (a: number, b: number, amount: number): number => (1 - amount) * a + amount * b; 18 | ``` 19 | 20 | ## See also 21 | 22 | - [Linear scale of a number between two ranges](https://phuoc.ng/collection/1-loc/linear-scale-of-a-number-between-two-ranges/) 23 | - [Normalize the ratio of a number in a range](https://phuoc.ng/collection/1-loc/normalize-the-ratio-of-a-number-in-a-range/) 24 | -------------------------------------------------------------------------------- /contents/truncate-a-string-at-full-words.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2020-05-29' 4 | title: Truncate a string at full words 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js truncate.js 11 | const truncate = (str, max, suffix) => 12 | str.length < max ? str : `${str.substr(0, str.substr(0, max - suffix.length).lastIndexOf(' '))}${suffix}`; 13 | ``` 14 | 15 | **TypeScript version** 16 | 17 | ```ts truncate.ts 18 | const truncate = (str: string, max: number, suffix: string = '...'): string => 19 | str.length < max ? str : `${str.substr(0, str.substr(0, max - suffix.length).lastIndexOf(' '))}${suffix}`; 20 | ``` 21 | 22 | **Examples** 23 | 24 | ```js examples.js 25 | truncate('This is a long message', 20, '...'); // 'This is a long...' 26 | ``` 27 | -------------------------------------------------------------------------------- /contents/check-if-a-number-is-in-a-given-range.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2020-06-04' 4 | title: Check if a number is in a given range 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js inRange.js 11 | const inRange = (num, a, b, threshold = 0) => Math.min(a, b) - threshold <= num && num <= Math.max(a, b) + threshold; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts inRange.ts 17 | const inRange = (num: number, a: number, b: number, threshold: number = 0): boolean => 18 | Math.min(a, b) - threshold <= num && num <= Math.max(a, b) + threshold; 19 | ``` 20 | 21 | **Examples** 22 | 23 | ```js examples.js 24 | inRange(10, 5, 15); // true 25 | inRange(10, 5, 6); // false 26 | inRange(10, 15, 5); // true 27 | inRange(-10, -5, -15); // true 28 | ``` 29 | -------------------------------------------------------------------------------- /contents/convert-an-lch-color-to-a-lab-color.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Misc 3 | created: '2023-11-10' 4 | openGraphCover: /og/1-loc/convert-lch-color-lab-color.png 5 | title: Convert an LCH color to a LAB color 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js lchToLab.js 11 | const lchToLab = (l, c, h) => [ 12 | l, 13 | Math.cos(h * Math.PI / 180) * c, 14 | Math.sin(h * Math.PI / 180) * c, 15 | ]; 16 | ``` 17 | 18 | **TypeScript version** 19 | 20 | ```ts lchToLab.ts 21 | const lchToLab = (l: number, c: number, h: number): number[] => [ 22 | l, 23 | Math.cos(h * Math.PI / 180) * c, 24 | Math.sin(h * Math.PI / 180) * c, 25 | ]; 26 | ``` 27 | 28 | ## See also 29 | 30 | - [Convert a LAB color to an LCH color](https://phuoc.ng/collection/1-loc/convert-a-lab-color-to-an-lch-color/) 31 | -------------------------------------------------------------------------------- /contents/add-an-ordinal-suffix-to-a-number.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Number 3 | created: '2020-05-16' 4 | title: Add an ordinal suffix to a number 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js addOrdinal.js 11 | // `n` is a position number 12 | const addOrdinal = (n) => `${n}${['st', 'nd', 'rd'][((((n + 90) % 100) - 10) % 10) - 1] || 'th'}`; 13 | ``` 14 | 15 | **TypeScript version** 16 | 17 | ```ts addOrdinal.ts 18 | const addOrdinal = (n: number): string => `${n}${['st', 'nd', 'rd'][((((n + 90) % 100) - 10) % 10) - 1] || 'th'}`; 19 | ``` 20 | 21 | **Examples** 22 | 23 | ```js examples.js 24 | addOrdinal(1); // '1st' 25 | addOrdinal(2); // '2nd' 26 | addOrdinal(3); // '3rd' 27 | addOrdinal(11); // '11th' 28 | addOrdinal(12); // '13th' 29 | addOrdinal(13); // '13th' 30 | ``` 31 | -------------------------------------------------------------------------------- /contents/check-if-a-string-is-a-mongo-db-object-id.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2021-04-10' 4 | title: Check if a string is a MongoDB ObjectId 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isMongoId.js 11 | const isMongoId = (str) => str.length === 24 && /^[A-F0-9]+$/i.test(str); 12 | 13 | // Or 14 | const isMongoId = (str) => str.length === 24 && str.split('').every((c) => '0123456789ABCDEFabcdef'.indexOf(c) !== -1); 15 | ``` 16 | 17 | **TypeScript version** 18 | 19 | ```ts isMongoId.ts 20 | const isMongoId = (str: string): boolean => str.length === 24 && /^[A-F0-9]+$/i.test(str); 21 | 22 | // Or 23 | const isMongoId = (str: string): boolean => 24 | str.length === 24 && str.split('').every((c) => '0123456789ABCDEFabcdef'.indexOf(c) !== -1); 25 | ``` 26 | -------------------------------------------------------------------------------- /contents/generate-a-random-ip-address.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Random 3 | contributors: 4 | - PiyushSuthar 5 | - Comet32 6 | created: '2020-08-10' 7 | title: Generate a random IP address 8 | updated: '2023-08-09' 9 | --- 10 | 11 | **JavaScript version** 12 | 13 | ```js randomIp.js 14 | const randomIp = () => 15 | Array(4) 16 | .fill(0) 17 | .map((_, i) => Math.floor(Math.random() * 255) + (i === 0 ? 1 : 0)) 18 | .join('.'); 19 | ``` 20 | 21 | **TypeScript version** 22 | 23 | ```ts randomIp.ts 24 | const randomIp = (): string => 25 | Array(4) 26 | .fill(0) 27 | .map((_, i) => Math.floor(Math.random() * 255) + (i === 0 ? 1 : 0)) 28 | .join('.'); 29 | ``` 30 | 31 | **Examples** 32 | 33 | ```js examples.js 34 | randomIp(); // 175.89.174.131 35 | ``` 36 | -------------------------------------------------------------------------------- /contents/split-an-array-into-chunks.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | created: '2020-05-13' 4 | title: Split an array into chunks 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js chunk.js 11 | const chunk = (arr, size) => 12 | arr.reduce((acc, e, i) => (i % size ? acc[acc.length - 1].push(e) : acc.push([e]), acc), []); 13 | ``` 14 | 15 | **TypeScript version** 16 | 17 | ```ts chunk.ts 18 | const chunk = (arr: T[], size: number): T[][] => ( 19 | arr.reduce((acc, e, i) => (i % size ? acc[acc.length - 1].push(e) : acc.push([e]), acc), [] as T[][]) 20 | ); 21 | ``` 22 | 23 | **Examples** 24 | 25 | ```js examples.js 26 | chunk([1, 2, 3, 4, 5, 6, 7, 8], 3); // [[1, 2, 3], [4, 5, 6], [7, 8]] 27 | chunk([1, 2, 3, 4, 5, 6, 7, 8], 4); // [[1, 2, 3, 4], [5, 6, 7, 8]] 28 | ``` 29 | -------------------------------------------------------------------------------- /contents/decapitalize-a-string.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2021-02-21' 4 | title: Decapitalize a string 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js decapitalize.js 11 | const decapitalize = (str) => `${str.charAt(0).toLowerCase()}${str.slice(1)}`; 12 | 13 | // Or 14 | const decapitalize = ([first, ...rest]) => `${first.toLowerCase()}${rest.join('')}`; 15 | ``` 16 | 17 | **TypeScript version** 18 | 19 | ```ts decapitalize.ts 20 | const decapitalize = (str: string): string => `${str.charAt(0).toLowerCase()}${str.slice(1)}`; 21 | 22 | // Or 23 | const decapitalize = ([first, ...rest]: string): string => `${first.toLowerCase()}${rest.join('')}`; 24 | ``` 25 | 26 | **Examples** 27 | 28 | ```js examples.js 29 | decapitalize('Hello world'); // 'hello world' 30 | ``` 31 | -------------------------------------------------------------------------------- /contents/trim-slashes-at-the-beginning-and-the-end-of-a-string.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2020-06-01' 4 | title: Trim slashes at the beginning and the end of a string 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js trimSlashes.js 11 | const trimSlashes = (str) => str.replace(/^\/+|\/+$/g, ''); 12 | 13 | // Or 14 | const trimSlashes = (str) => str.split('/').filter(Boolean).join('/'); 15 | ``` 16 | 17 | **TypeScript version** 18 | 19 | ```ts trimSlashes.ts 20 | const trimSlashes = (str: string): string => str.replace(/^\/+|\/+$/g, ''); 21 | 22 | // Or 23 | const trimSlashes = (str: string): string => str.split('/').filter(Boolean).join('/'); 24 | ``` 25 | 26 | **Examples** 27 | 28 | ```js examples.js 29 | trimSlashes('//hello/world///'); // hello/world 30 | ``` 31 | -------------------------------------------------------------------------------- /contents/check-if-a-point-is-inside-a-rectangle.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Math 3 | created: '2021-04-05' 4 | title: Check if a point is inside a rectangle 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isInside.js 11 | const isInside = (point, rect) => 12 | point.x > rect.left && point.x < rect.right && point.y > rect.top && point.y < rect.bottom; 13 | ``` 14 | 15 | **TypeScript version** 16 | 17 | ```ts isInside.ts 18 | interface Point { 19 | x: number; 20 | y: number; 21 | } 22 | 23 | interface Rect { 24 | bottom: number; 25 | left: number; 26 | top: number; 27 | right: number; 28 | } 29 | 30 | const isInside = (point: Point, rect: Rect): boolean => 31 | point.x > rect.left && point.x < rect.right && point.y > rect.top && point.y < rect.bottom; 32 | ``` 33 | -------------------------------------------------------------------------------- /contents/convert-a-string-to-camel-case.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2020-05-16' 4 | title: Convert a string to camelCase 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js toCamelCase.js 11 | const toCamelCase = (str) => str.trim().replace(/[-_\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : '')); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts toCamelCase.ts 17 | const toCamelCase = (str: string): string => str.trim().replace(/[-_\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : '')); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | toCamelCase('background-color'); // backgroundColor 24 | toCamelCase('-webkit-scrollbar-thumb'); // WebkitScrollbarThumb 25 | toCamelCase('_hello_world'); // HelloWorld 26 | toCamelCase('hello_world'); // helloWorld 27 | ``` 28 | -------------------------------------------------------------------------------- /contents/convert-a-string-to-pascal-case.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2020-05-15' 4 | title: Convert a string to PascalCase 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js toPascalCase.js 11 | const toPascalCase = (str) => 12 | (str.match(/[a-zA-Z0-9]+/g) || []).map((w) => `${w.charAt(0).toUpperCase()}${w.slice(1)}`).join(''); 13 | ``` 14 | 15 | **TypeScript version** 16 | 17 | ```ts toPascalCase.ts 18 | const toPascalCase = (str: string): string => 19 | (str.match(/[a-zA-Z0-9]+/g) || []).map((w) => `${w.charAt(0).toUpperCase()}${w.slice(1)}`).join(''); 20 | ``` 21 | 22 | **Examples** 23 | 24 | ```js examples.js 25 | toPascalCase('hello world'); // 'HelloWorld' 26 | toPascalCase('hello.world'); // 'HelloWorld' 27 | toPascalCase('foo_bar-baz'); // FooBarBaz 28 | ``` 29 | -------------------------------------------------------------------------------- /contents/generate-an-array-of-random-integers-in-a-given-range.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Random 3 | created: '2020-05-16' 4 | title: Generate an array of random integers in a given range 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js randomArrayInRange.js 11 | const randomArrayInRange = (min, max, n) => 12 | Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min); 13 | ``` 14 | 15 | **TypeScript version** 16 | 17 | ```ts randomArrayInRange.ts 18 | const randomArrayInRange = (min: number, max: number, n: number): number[] => 19 | Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min); 20 | ``` 21 | 22 | **Examples** 23 | 24 | ```js examples.js 25 | randomArrayInRange(1, 100, 10); // [11, 82, 41, 35, 76, 83, 43, 15, 60, 54] 26 | ``` 27 | -------------------------------------------------------------------------------- /contents/convert-a-lab-color-to-an-lch-color.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Misc 3 | created: '2023-11-10' 4 | openGraphCover: /og/1-loc/convert-lab-color-lch-color.png 5 | title: Convert a LAB color to an LCH color 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js labToLch.js 11 | const labToLch = (l, a, b) => [ 12 | l, 13 | Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2)), 14 | Math.atan2(b, a) * 180 / Math.PI, 15 | ]; 16 | ``` 17 | 18 | **TypeScript version** 19 | 20 | ```ts labToLch.ts 21 | const labToLch = (l: number, a: number, b: number): number[] => [ 22 | l, 23 | Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2)), 24 | Math.atan2(b, a) * 180 / Math.PI, 25 | ]; 26 | ``` 27 | 28 | ## See also 29 | 30 | - [Convert an LCH color to a LAB color](https://phuoc.ng/collection/1-loc/convert-an-lch-color-to-a-lab-color/) 31 | -------------------------------------------------------------------------------- /contents/generate-a-random-floating-point-number-in-given-range.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Random 3 | created: '2020-05-05' 4 | title: Generate a random floating point number in given range 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js randomFloat.js 11 | const randomFloat = (min, max) => Math.random() * (max - min) + min; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts randomFloat.ts 17 | const randomFloat = (min: number, max: number): number => Math.random() * (max - min) + min; 18 | ``` 19 | 20 | ## See also 21 | 22 | - [Generate a random integer in given range](https://phuoc.ng/collection/1-loc/generate-a-random-integer-in-given-range/) 23 | - [Generate a weighted random number in given range](https://phuoc.ng/collection/1-loc/generate-a-weighted-random-number-in-given-range/) 24 | -------------------------------------------------------------------------------- /contents/get-the-intersection-range-between-two-ranges.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Number 3 | created: '2023-12-07' 4 | openGraphCover: /og/1-loc/get-intersection-range-between-two-ranges.png 5 | title: Get the intersection range between two ranges 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js intersection.js 11 | const intersection = (a, b) => (a[0] > b[1] || a[1] < b[0]) ? [] : [Math.max(a[0], b[0]), Math.min(a[1], b[1])]; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts intersection.ts 17 | 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])]; 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | intersection([0, 20], [15, 35]); // [15, 20] 24 | intersection([0, 20], [40, 50]); // [] 25 | ``` 26 | -------------------------------------------------------------------------------- /contents/insert-an-element-before-other-one.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: DOM 3 | created: '2020-04-19' 4 | title: Insert an element before other one 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js insertBefore.js 11 | const insertBefore = (ele, anotherEle) => anotherEle.parentNode.insertBefore(ele, anotherEle); 12 | 13 | // Or 14 | const insertBefore = (ele, anotherEle) => anotherEle.insertAdjacentElement('beforebegin', ele); 15 | ``` 16 | 17 | **TypeScript version** 18 | 19 | ```ts insertBefore.ts 20 | const insertBefore = (ele: Element, anotherEle: Element): Element | null => 21 | anotherEle.parentNode ? anotherEle.parentNode.insertBefore(ele, anotherEle) : null; 22 | 23 | // Or 24 | const insertBefore = (ele: Element, anotherEle: Element) => anotherEle.insertAdjacentElement('beforebegin', ele); 25 | ``` 26 | -------------------------------------------------------------------------------- /contents/normalize-the-ratio-of-a-number-in-a-range.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Math 3 | created: '2021-05-24' 4 | title: Normalize the ratio of a number in a range 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js normalizeRatio.js 11 | const normalizeRatio = (value, min, max) => (value - min) / (max - min); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts normalizeRatio.ts 17 | const normalizeRatio = (value: number, min: number, max: number): number => (value - min) / (max - min); 18 | ``` 19 | 20 | ## See also 21 | 22 | - [Calculate the linear interpolation between two numbers](https://phuoc.ng/collection/1-loc/calculate-the-linear-interpolation-between-two-numbers/) 23 | - [Linear scale of a number between two ranges](https://phuoc.ng/collection/1-loc/linear-scale-of-a-number-between-two-ranges/) 24 | -------------------------------------------------------------------------------- /contents/shuffle-an-array.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | contributors: 4 | - elkarouani 5 | created: '2020-05-20' 6 | title: Shuffle an array 7 | updated: '2021-12-22' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js shuffle.js 13 | const shuffle = (arr) => 14 | arr 15 | .map((a) => ({ sort: Math.random(), value: a })) 16 | .sort((a, b) => a.sort - b.sort) 17 | .map((a) => a.value); 18 | ``` 19 | 20 | **TypeScript version** 21 | 22 | ```ts shuffle.ts 23 | const shuffle = (arr: T[]): T[] => 24 | arr 25 | .map((a) => ({ sort: Math.random(), value: a })) 26 | .sort((a, b) => a.sort - b.sort) 27 | .map((a) => a.value); 28 | ``` 29 | 30 | **Example** 31 | 32 | ```js example.js 33 | shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); // [9, 1, 10, 6, 8, 5, 2, 3, 7, 4] 34 | ``` 35 | -------------------------------------------------------------------------------- /contents/format-a-string.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | contributors: 4 | - david-luna 5 | created: '2021-11-10' 6 | title: Format a string 7 | --- 8 | 9 | **JavaScript version** 10 | 11 | ```js format.js 12 | const format = (str, ...vals) => vals.reduce((s, v, i) => s.replace(new RegExp('\\{' + i + '\\}', 'g'), v), str); 13 | ``` 14 | 15 | **TypeScript version** 16 | 17 | ```ts 18 | const format = (str: string, ...vals: unknown[]): string => 19 | vals.reduce((s, v, i) => s.replace(new RegExp('\\{' + i + '\\}', 'g'), v), str); 20 | ``` 21 | 22 | **Examples** 23 | 24 | ```js examples.js 25 | const template = 'My name is {0} and I am {1} years old'; 26 | 27 | format(template, 'John', 30)); 28 | // My name is John and I am 30 years old 29 | 30 | format(template, 'Jane', 20); 31 | // My name is Jane and I am 20 years old 32 | ``` 33 | -------------------------------------------------------------------------------- /contents/check-if-a-number-is-odd.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | contributors: 4 | - ietienam 5 | - Namysh 6 | - marcobiedermann 7 | created: '2020-05-06' 8 | title: Check if a number is odd 9 | updated: '2021-10-13' 10 | --- 11 | 12 | **JavaScript version** 13 | 14 | ```js isOdd.js 15 | const isOdd = (n) => n % 2 !== 0; 16 | 17 | // Or 18 | const isOdd = (n) => !!(n & 1); 19 | 20 | // Or 21 | const isOdd = (n) => !Number.isInteger(n / 2); 22 | ``` 23 | 24 | **TypeScript version** 25 | 26 | ```ts isOdd.ts 27 | const isOdd = (n: number): boolean => n % 2 !== 0; 28 | 29 | // Or 30 | const isOdd = (n: number): boolean => !!(n & 1); 31 | 32 | // Or 33 | const isOdd = (n: number): boolean => !Number.isInteger(n / 2); 34 | ``` 35 | 36 | **Examples** 37 | 38 | ```js examples.js 39 | isOdd(1); // true 40 | isOdd(2); // false 41 | ``` 42 | -------------------------------------------------------------------------------- /contents/check-if-a-string-consists-of-a-repeated-character-sequence.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2021-04-21' 4 | title: Check if a string consists of a repeated character sequence 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js consistsRepeatedSubstring.js 11 | const consistsRepeatedSubstring = (str) => `${str}${str}`.indexOf(str, 1) !== str.length; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts consistsRepeatedSubstring.ts 17 | const consistsRepeatedSubstring = (str: string): boolean => `${str}${str}`.indexOf(str, 1) !== str.length; 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | consistsRepeatedSubstring('aa'); // true 24 | consistsRepeatedSubstring('aaa'); // true 25 | consistsRepeatedSubstring('ababab'); // true 26 | consistsRepeatedSubstring('abc'); // false 27 | ``` 28 | -------------------------------------------------------------------------------- /contents/hide-an-element.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: DOM 3 | contributors: 4 | - iamdileepkumar 5 | - islamozbek 6 | created: '2020-04-19' 7 | title: Hide an element 8 | updated: '2021-10-13' 9 | --- 10 | 11 | **JavaScript version** 12 | 13 | ```js hide.js 14 | // Pick the method that is suitable for your use case 15 | const hide = (ele) => (ele.style.display = 'none'); 16 | 17 | // Or 18 | const hide = (ele) => (ele.style.visibility = 'hidden'); 19 | 20 | // Or 21 | const hide = (ele) => (ele.hidden = true); 22 | ``` 23 | 24 | **TypeScript version** 25 | 26 | ```ts hide.ts 27 | const hide = (ele: HTMLElement): string => (ele.style.display = 'none'); 28 | 29 | // Or 30 | const hide = (ele: HTMLElement): string => (ele.style.visibility = 'hidden'); 31 | 32 | // Or 33 | const hide = (ele: HTMLElement): boolean => (ele.hidden = true); 34 | ``` 35 | -------------------------------------------------------------------------------- /contents/strip-ansi-codes-from-a-string.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2020-06-07' 4 | title: Strip ANSI codes from a string 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js stripAnsiCodes.js 11 | const stripAnsiCodes = (str) => 12 | str.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, ''); 13 | ``` 14 | 15 | **TypeScript version** 16 | 17 | ```ts stripAnsiCodes.ts 18 | const stripAnsiCodes = (str: string): string => 19 | str.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, ''); 20 | ``` 21 | 22 | **Examples** 23 | 24 | ```js examples.js 25 | stripAnsiCodes('\u001B[4mcake\u001B[0m'); // 'cake' 26 | stripAnsiCodes('\u001B[0m\u001B[4m\u001B[42m\u001B[31mfoo\u001B[39m\u001B[49m\u001B[24mfoo\u001B[0m'); // 'foofoo' 27 | ``` 28 | -------------------------------------------------------------------------------- /contents/calculate-the-angle-of-a-line-defined-by-two-points.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Math 3 | created: '2021-04-08' 4 | title: Calculate the angle of a line defined by two points 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js radiansAngle.js 11 | // In radians 12 | const radiansAngle = (p1, p2) => Math.atan2(p2.y - p1.y, p2.x - p1.x); 13 | 14 | // In degrees 15 | const degreesAngle = (p1, p2) => (Math.atan2(p2.y - p1.y, p2.x - p1.x) * 180) / Math.PI; 16 | ``` 17 | 18 | **TypeScript version** 19 | 20 | ```ts radiansAngle.ts 21 | interface Point { 22 | x: number; 23 | y: number; 24 | } 25 | 26 | const radiansAngle = (p1: Point, p2: Point): number => Math.atan2(p2.y - p1.y, p2.x - p1.x); 27 | 28 | const degreesAngle = (p1: Point, p2: Point): number => (Math.atan2(p2.y - p1.y, p2.x - p1.x) * 180) / Math.PI; 29 | ``` 30 | -------------------------------------------------------------------------------- /contents/check-if-two-strings-are-anagram.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | contributors: 4 | - mahdiyar 5 | created: '2020-05-07' 6 | title: Check if two strings are anagram 7 | updated: '2021-10-13' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js areAnagram.js 13 | const areAnagram = (str1, str2) => 14 | str1.toLowerCase().split('').sort().join('') === str2.toLowerCase().split('').sort().join(''); 15 | ``` 16 | 17 | **TypeScript version** 18 | 19 | ```ts areAnagram.ts 20 | const areAnagram = (str1: string, str2: string): boolean => 21 | str1.toLowerCase().split('').sort().join('') === str2.toLowerCase().split('').sort().join(''); 22 | ``` 23 | 24 | **Examples** 25 | 26 | ```js examples.js 27 | areAnagram('listen', 'silent'); // true 28 | areAnagram('they see', 'the eyes'); // true 29 | areAnagram('node', 'deno'); // true 30 | ``` 31 | -------------------------------------------------------------------------------- /contents/clamp-a-number-between-two-values.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Number 3 | contributors: 4 | - r-i-c-h 5 | created: '2020-05-05' 6 | title: Clamp a number between two values 7 | updated: '2021-10-13' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js clamp.js 13 | const clamp = (val, min = 0, max = 1) => Math.max(min, Math.min(max, val)); 14 | ``` 15 | 16 | **TypeScript version** 17 | 18 | ```ts clamp.ts 19 | const clamp = (val: number, min: number = 0, max: number = 1): number => Math.max(min, Math.min(max, val)); 20 | ``` 21 | 22 | **Examples** 23 | 24 | ```js examples.js 25 | clamp(199, 10, 25); // 25 26 | ``` 27 | 28 | ## See also 29 | 30 | - [Build a spin input](https://phuoc.ng/collection/html-dom/build-a-spin-input/) 31 | - [Wrap a number between two values](https://phuoc.ng/collection/1-loc/wrap-a-number-between-two-values/) 32 | -------------------------------------------------------------------------------- /contents/compare-two-arrays.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | created: '2020-05-05' 4 | title: Compare two arrays 5 | updated: '2021-10-22' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isEqual.js 11 | // `a` and `b` are arrays 12 | const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b); 13 | 14 | // Or 15 | const isEqual = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]); 16 | ``` 17 | 18 | **TypeScript version** 19 | 20 | ```ts isEqual.ts 21 | const isEqual = (a: T[], b: T[]): boolean => JSON.stringify(a) === JSON.stringify(b); 22 | 23 | // Or 24 | const isEqual = (a: T[], b: T[]): boolean => a.length === b.length && a.every((v, i) => v === b[i]); 25 | ``` 26 | 27 | **Examples** 28 | 29 | ```js examples.js 30 | isEqual([1, 2, 3], [1, 2, 3]); // true 31 | isEqual([1, 2, 3], [1, '2', 3]); // false 32 | ``` 33 | -------------------------------------------------------------------------------- /contents/replace-multiple-spaces-with-a-single-space.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2020-05-09' 4 | title: Replace multiple spaces with a single space 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js replaceSpaces.js 11 | // Replace spaces, tabs and new line characters 12 | const replaceSpaces = (str) => str.replace(/\s\s+/g, ' '); 13 | 14 | // Only replace spaces 15 | const replaceOnlySpaces = (str) => str.replace(/ +/g, ' '); 16 | ``` 17 | 18 | **TypeScript version** 19 | 20 | ```ts replaceSpaces.ts 21 | const replaceSpaces = (str: string): string => str.replace(/\s\s+/g, ' '); 22 | 23 | const replaceOnlySpaces = (str: string): string => str.replace(/ +/g, ' '); 24 | ``` 25 | 26 | **Examples** 27 | 28 | ```js examples.js 29 | replaceSpaces('this\n is \ta \rmessage'); // 'this is a message' 30 | ``` 31 | -------------------------------------------------------------------------------- /contents/calculate-the-number-of-months-between-two-dates.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Date Time 3 | contributors: 4 | - kwaimind 5 | created: '2020-07-27' 6 | title: Calculate the number of months between two dates 7 | updated: '2021-10-13' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js monthDiff.js 13 | const monthDiff = (startDate, endDate) => 14 | Math.max(0, (endDate.getFullYear() - startDate.getFullYear()) * 12 - startDate.getMonth() + endDate.getMonth()); 15 | ``` 16 | 17 | **TypeScript version** 18 | 19 | ```ts monthDiff.ts 20 | const monthDiff = (startDate: Date, endDate: Date): number => 21 | Math.max(0, (endDate.getFullYear() - startDate.getFullYear()) * 12 - startDate.getMonth() + endDate.getMonth()); 22 | ``` 23 | 24 | **Example** 25 | 26 | ```js example.js 27 | monthDiff(new Date('2020-01-01'), new Date('2021-01-01')); // 12 28 | ``` 29 | -------------------------------------------------------------------------------- /contents/find-the-minimum-item-of-an-array-by-given-key.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | created: '2021-01-13' 4 | title: Find the minimum item of an array by given key 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js minBy.js 11 | const minBy = (arr, key) => arr.reduce((a, b) => (a[key] < b[key] ? a : b), {}); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts minBy.ts 17 | const minBy = , K extends keyof T>(arr: T[], key: K): T => ( 18 | arr.reduce((a, b) => (a[key] < b[key] ? a : b), {} as T) 19 | ); 20 | ``` 21 | 22 | **Example** 23 | 24 | ```js example.js 25 | const people = [ 26 | { name: 'Bar', age: 24 }, 27 | { name: 'Baz', age: 32 }, 28 | { name: 'Foo', age: 42 }, 29 | { name: 'Fuzz', age: 36 }, 30 | ]; 31 | minBy(people, 'age'); // { name: 'Bar', age: 24 } 32 | ``` 33 | -------------------------------------------------------------------------------- /contents/count-the-occurrences-of-array-elements.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | created: '2020-06-11' 4 | title: Count the occurrences of array elements 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js countOccurrences.js 11 | const countOccurrences = (arr) => arr.reduce((prev, curr) => ((prev[curr] = ++prev[curr] || 1), prev), {}); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts countOccurrences.ts 17 | const countOccurrences = (arr: T[]): Record => ( 18 | arr.reduce((prev, curr) => ((prev[curr] = ++prev[curr] || 1), prev), {}as Record) 19 | ); 20 | ``` 21 | 22 | **Examples** 23 | 24 | ```js examples.js 25 | countOccurrences([2, 1, 3, 3, 2, 3]); // { '1': 1, '2': 2, '3': 3 } 26 | countOccurrences(['a', 'b', 'a', 'c', 'a', 'b']); // { 'a': 3, 'b': 2, 'c': 1 } 27 | ``` 28 | -------------------------------------------------------------------------------- /contents/find-the-maximum-item-of-an-array-by-given-key.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | created: '2021-01-13' 4 | title: Find the maximum item of an array by given key 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js maxBy.js 11 | const maxBy = (arr, key) => arr.reduce((a, b) => (a[key] >= b[key] ? a : b), {}); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts maxBy.ts 17 | const maxBy = , K extends keyof T>(arr: T[], key: K): T => ( 18 | arr.reduce((a, b) => (a[key] >= b[key] ? a : b), {} as T) 19 | ); 20 | ``` 21 | 22 | **Example** 23 | 24 | ```js example.js 25 | const people = [ 26 | { name: 'Bar', age: 24 }, 27 | { name: 'Baz', age: 32 }, 28 | { name: 'Foo', age: 42 }, 29 | { name: 'Fuzz', age: 36 }, 30 | ]; 31 | maxBy(people, 'age'); // { name: 'Foo', age: 42 } 32 | ``` 33 | -------------------------------------------------------------------------------- /contents/generate-a-random-integer-in-given-range.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Random 3 | created: '2020-05-05' 4 | title: Generate a random integer in given range 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js randomInteger.js 11 | const randomInteger = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts randomInteger.ts 17 | const randomInteger = (min: number, max: number): number => Math.floor(Math.random() * (max - min + 1)) + min; 18 | ``` 19 | 20 | ## See also 21 | 22 | - [Generate a random floating point number in given range](https://phuoc.ng/collection/1-loc/generate-a-random-floating-point-number-in-given-range/) 23 | - [Generate a weighted random number in given range](https://phuoc.ng/collection/1-loc/generate-a-weighted-random-number-in-given-range/) 24 | -------------------------------------------------------------------------------- /contents/get-the-tomorrow-date.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Date Time 3 | created: '2020-05-21' 4 | title: Get the tomorrow date 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js tomorrow.js 11 | const tomorrow = ((d) => new Date(d.setDate(d.getDate() + 1)))(new Date()); 12 | 13 | // Or 14 | const tomorrow = new Date(new Date().valueOf() + 1000 * 60 * 60 * 24); 15 | ``` 16 | 17 | **TypeScript version** 18 | 19 | ```ts tomorrow.ts 20 | const tomorrow: Date = ((d) => new Date(d.setDate(d.getDate() + 1)))(new Date()); 21 | 22 | // Or 23 | const tomorrow: Date = new Date(new Date().valueOf() + 1000 * 60 * 60 * 24); 24 | ``` 25 | 26 | ## See also 27 | 28 | - [Determine one year from now](https://phuoc.ng/collection/1-loc/determine-one-year-from-now/) 29 | - [Get the yesterday date](https://phuoc.ng/collection/1-loc/get-the-yesterday-date/) 30 | -------------------------------------------------------------------------------- /contents/convert-a-number-to-equivalent-characters.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Number 3 | created: '2020-05-27' 4 | title: Convert a number to equivalent characters 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js toChars.js 11 | const toChars = (n) => `${n >= 26 ? toChars(Math.floor(n / 26) - 1) : ''}${'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[n % 26]}`; 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts toChars.ts 17 | const toChars = (n: number): string => 18 | `${n >= 26 ? toChars(Math.floor(n / 26) - 1) : ''}${'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[n % 26]}`; 19 | ``` 20 | 21 | **Examples** 22 | 23 | ```js examples.js 24 | toChars(0); // A 25 | toChars(1); // B 26 | toChars(25); // Z 27 | 28 | toChars(26); // AA 29 | toChars(27); // AB 30 | toChars(51); // AZ 31 | 32 | toChars(701); // ZZ 33 | toChars(702); // AAA 34 | toChars(703); // AAB 35 | ``` 36 | -------------------------------------------------------------------------------- /contents/get-the-yesterday-date.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Date Time 3 | created: '2020-05-21' 4 | title: Get the yesterday date 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js yesterday.js 11 | const yesterday = ((d) => new Date(d.setDate(d.getDate() - 1)))(new Date()); 12 | 13 | // Or 14 | const yesterday = new Date(new Date().valueOf() - 1000 * 60 * 60 * 24); 15 | ``` 16 | 17 | **TypeScript version** 18 | 19 | ```ts yesterday.ts 20 | const yesterday: Date = ((d) => new Date(d.setDate(d.getDate() - 1)))(new Date()); 21 | 22 | // Or 23 | const yesterday: Date = new Date(new Date().valueOf() - 1000 * 60 * 60 * 24); 24 | ``` 25 | 26 | ## See also 27 | 28 | - [Determine one year from now](https://phuoc.ng/collection/1-loc/determine-one-year-from-now/) 29 | - [Get the tomorrow date](https://phuoc.ng/collection/1-loc/get-the-tomorrow-date/) 30 | -------------------------------------------------------------------------------- /contents/insert-an-element-after-other-one.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: DOM 3 | created: '2020-04-19' 4 | title: Insert an element after other one 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js insertAfter.js 11 | const insertAfter = (ele, anotherEle) => anotherEle.parentNode.insertBefore(ele, anotherEle.nextSibling); 12 | 13 | // Or 14 | const insertAfter = (ele, anotherEle) => anotherEle.insertAdjacentElement('afterend', ele); 15 | ``` 16 | 17 | **TypeScript version** 18 | 19 | ```ts insertAfter.ts 20 | const insertAfter = (ele: Element, anotherEle: Element): Element | null => 21 | anotherEle.parentNode ? anotherEle.parentNode.insertBefore(ele, anotherEle.nextSibling) : null; 22 | 23 | // Or 24 | const insertAfter = (ele: Element, anotherEle: Element): Element | null => 25 | anotherEle.insertAdjacentElement('afterend', ele); 26 | ``` 27 | -------------------------------------------------------------------------------- /contents/redirect-the-page-to-https-if-it-is-in-http.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Misc 3 | created: '2020-05-31' 4 | title: Redirect the page to HTTPS if it is in HTTP 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js redirectHttps.js 11 | const redirectHttps = () => 12 | location.protocol === 'https:' ? {} : location.replace(`https://${location.href.split('//')[1]}`); 13 | 14 | // Or 15 | const redirectHttps = () => (location.protocol === 'https:' ? {} : (location.protocol = 'https:')); 16 | ``` 17 | 18 | **TypeScript version** 19 | 20 | ```ts redirectHttps.ts 21 | const redirectHttps = (): void => 22 | location.protocol === 'https:' ? void 0 : location.replace(`https://${location.href.split('//')[1]}`); 23 | 24 | // Or 25 | const redirectHttps = (): string => (location.protocol === 'https:' ? '' : (location.protocol = 'https:')); 26 | ``` 27 | -------------------------------------------------------------------------------- /contents/get-the-first-defined-and-non-null-argument.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Misc 3 | created: '2020-06-12' 4 | title: Get the first defined and non null argument 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js coalesce.js 11 | const coalesce = (...args) => args.find((item) => item !== undefined && item !== null); 12 | 13 | // Or 14 | const coalesce = (...args) => args.find((item) => ![undefined, null].includes(item)); 15 | ``` 16 | 17 | **TypeScript version** 18 | 19 | ```ts coalesce.ts 20 | const coalesce = (...args: any[]): any[] => args.find((item) => item !== undefined && item !== null); 21 | 22 | // Or 23 | const coalesce = (...args: any[]): any[] => args.find((item) => ![undefined, null].includes(item)); 24 | ``` 25 | 26 | **Examples** 27 | 28 | ```js examples.js 29 | coalesce(undefined, null, 'helloworld', NaN); // 'helloworld' 30 | ``` 31 | -------------------------------------------------------------------------------- /contents/remove-empty-lines-of-a-text-document.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2021-05-28' 4 | title: Remove empty lines of a text document 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js removeEmptyLines.js 11 | const removeEmptyLines = (str) => 12 | str 13 | .split(/\r?\n/) 14 | .filter((line) => line.trim() !== '') 15 | .join('\n'); 16 | ``` 17 | 18 | **TypeScript version** 19 | 20 | ```ts removeEmptyLines.ts 21 | const removeEmptyLines = (str: string): string => 22 | str 23 | .split(/\r?\n/) 24 | .filter((line) => line.trim() !== '') 25 | .join('\n'); 26 | ``` 27 | 28 | **Examples** 29 | 30 | ```js examples.js 31 | removeEmptyLines(`red 32 | 33 | green 34 | blue 35 | 36 | yellow`); 37 | 38 | /* Output */ 39 | /* 40 | red 41 | green 42 | blue 43 | yellow 44 | */ 45 | ``` 46 | -------------------------------------------------------------------------------- /contents/check-if-all-items-in-an-array-are-equal.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | contributors: 4 | - manu2504 5 | - glennfaison 6 | created: '2020-04-19' 7 | title: Check if all items in an array are equal 8 | updated: '2021-10-22' 9 | --- 10 | 11 | **JavaScript version** 12 | 13 | ```js areEqual.js 14 | const areEqual = (arr) => arr.length > 0 && arr.every((item) => item === arr[0]); 15 | 16 | // Or 17 | const areEqual = (arr) => new Set(arr).size === 1; 18 | ``` 19 | 20 | **TypeScript version** 21 | 22 | ```ts areEqual.ts 23 | const areEqual = (arr: T[]): boolean => arr.length > 0 && arr.every((item) => item === arr[0]); 24 | 25 | // Or 26 | const areEqual = (arr: T[]): boolean => new Set(arr).size === 1; 27 | ``` 28 | 29 | **Examples** 30 | 31 | ```js examples.js 32 | areEqual([1, 2, 3, 4]); // false 33 | areEqual(['hello', 'hello', 'hello']); // true 34 | ``` 35 | -------------------------------------------------------------------------------- /contents/generate-a-random-string-from-given-characters.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Random 3 | created: '2020-04-23' 4 | title: Generate a random string from given characters 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js generateString.js 11 | const generateString = (length, chars) => 12 | Array(length) 13 | .fill('') 14 | .map((v) => chars[Math.floor(Math.random() * chars.length)]) 15 | .join(''); 16 | ``` 17 | 18 | **TypeScript version** 19 | 20 | ```ts generateString.ts 21 | const generateString = (length: number, chars: string) => 22 | Array(length) 23 | .fill('') 24 | .map((v) => chars[Math.floor(Math.random() * chars.length)]) 25 | .join(''); 26 | ``` 27 | 28 | **Examples** 29 | 30 | ```js examples.js 31 | generateString(10, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'); 32 | ``` 33 | -------------------------------------------------------------------------------- /contents/convert-the-name-of-an-excel-column-to-number.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2020-05-25' 4 | title: Convert the name of an Excel column to number 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js getIndex.js 11 | const getIndex = (col) => col.split('').reduce((prev, next) => prev * 26 + parseInt(next, 36) - 9, 0); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts getIndex.ts 17 | const getIndex = (col: string): number => col.split('').reduce((prev, next) => prev * 26 + parseInt(next, 36) - 9, 0); 18 | ``` 19 | 20 | **Examples** 21 | 22 | ```js examples.js 23 | getIndex('A'); // 1 24 | getIndex('B'); // 2 25 | getIndex('C'); // 3 26 | getIndex('Z'); // 26 27 | 28 | getIndex('AA'); // 27 29 | getIndex('AB'); // 28 30 | getIndex('AC'); // 29 31 | getIndex('AZ'); // 52 32 | 33 | getIndex('AAA'); // 703 34 | getIndex('AAB'); // 704 35 | ``` 36 | -------------------------------------------------------------------------------- /contents/compare-two-arrays-regardless-of-order.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | contributors: 4 | - Rupesh Jaiswal 5 | - robinpokorny 6 | - dauom 7 | - elkarouani 8 | created: '2020-05-11' 9 | title: Compare two arrays regardless of order 10 | updated: '2021-12-23' 11 | --- 12 | 13 | **JavaScript version** 14 | 15 | ```js isEqual.js 16 | // `a` and `b` are arrays 17 | const isEqual = (a, b) => JSON.stringify([...new Set(a)].sort()) === JSON.stringify([...new Set(b)].sort()); 18 | ``` 19 | 20 | **TypeScript version** 21 | 22 | ```ts isEqual.ts 23 | const isEqual = (a: T[], b: T[]): boolean => JSON.stringify([...(new Set(a))].sort()) === JSON.stringify([...(new Set(b))].sort()); 24 | ``` 25 | 26 | **Examples** 27 | 28 | ```js examples.js 29 | isEqual([1, 2, 3], [1, 2, 3]); // true 30 | isEqual([1, 2, 3], [1, 3, 2]); // true 31 | isEqual([1, 2, 3], [1, '2', 3]); // false 32 | ``` 33 | -------------------------------------------------------------------------------- /contents/convert-3-digits-color-to-6-digits-color.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Misc 3 | created: '2021-02-20' 4 | title: Convert 3 digits color to 6 digits color 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js toFullHexColor.js 11 | const toFullHexColor = (color) => 12 | `#${(color.startsWith('#') ? color.slice(1) : color) 13 | .split('') 14 | .map((c) => `${c}${c}`) 15 | .join('')}`; 16 | ``` 17 | 18 | **TypeScript version** 19 | 20 | ```ts toFullHexColor.ts 21 | const toFullHexColor = (color: string): string => 22 | `#${(color.startsWith('#') ? color.slice(1) : color) 23 | .split('') 24 | .map((c) => `${c}${c}`) 25 | .join('')}`; 26 | ``` 27 | 28 | **Examples** 29 | 30 | ```js examples.js 31 | toFullHexColor('123'); // '#112233' 32 | toFullHexColor('#123'); // '#112233' 33 | toFullHexColor('#abc'); // '#aabbcc' 34 | ``` 35 | -------------------------------------------------------------------------------- /contents/check-if-a-string-is-a-hexadecimal-number.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2020-06-10' 4 | title: Check if a string is a hexadecimal number 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isHexadecimal.js 11 | const isHexadecimal = (str) => /^[A-F0-9]+$/i.test(str); 12 | 13 | // Or 14 | const isHexadecimal = (str) => str.split('').every((c) => '0123456789ABCDEFabcdef'.indexOf(c) !== -1); 15 | ``` 16 | 17 | **TypeScript version** 18 | 19 | ```ts isHexadecimal.ts 20 | const isHexadecimal = (str: string): boolean => /^[A-F0-9]+$/i.test(str); 21 | 22 | // Or 23 | const isHexadecimal = (str: string): boolean => str.split('').every((c) => '0123456789ABCDEFabcdef'.indexOf(c) !== -1); 24 | ``` 25 | 26 | **Examples** 27 | 28 | ```js examples.js 29 | isHexadecimal('123'); // true 30 | isHexadecimal('A1B2C3'); // true 31 | isHexadecimal('#123'); // false 32 | ``` 33 | -------------------------------------------------------------------------------- /contents/convert-camel-case-to-kebab-case-and-vice-versa.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2020-05-12' 4 | title: 'Convert camelCase to kebab-case and vice versa' 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js kebabToCamel.js 11 | const kebabToCamel = (str) => str.replace(/-./g, (m) => m.toUpperCase()[1]); 12 | 13 | const camelToKebab = (str) => str.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase(); 14 | ``` 15 | 16 | **TypeScript version** 17 | 18 | ```ts kebabToCamel.ts 19 | const kebabToCamel = (str: string): string => str.replace(/-./g, (m) => m.toUpperCase()[1]); 20 | 21 | const camelToKebab = (str: string): string => str.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase(); 22 | ``` 23 | 24 | **Examples** 25 | 26 | ```js examples.js 27 | kebabToCamel('background-color'); // 'backgroundColor' 28 | camelToKebab('backgroundColor'); // 'background-color' 29 | ``` 30 | -------------------------------------------------------------------------------- /contents/get-all-arrays-of-consecutive-elements.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | created: '2021-04-10' 4 | title: Get all arrays of consecutive elements 5 | updated: '2021-10-22' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js getConsecutiveArrays.js 11 | const getConsecutiveArrays = (arr, size) => 12 | size > arr.length ? [] : arr.slice(size - 1).map((_, i) => arr.slice(i, size + i)); 13 | ``` 14 | 15 | **TypeScript version** 16 | 17 | ```ts getConsecutiveArrays.ts 18 | const getConsecutiveArrays = (arr: T[], size: number): T[][] => (size > arr.length ? [] : arr.slice(size - 1).map((_, i) => arr.slice(i, size + i))); 19 | ``` 20 | 21 | **Examples** 22 | 23 | ```js examples.js 24 | getConsecutiveArrays([1, 2, 3, 4, 5], 2); // [[1, 2], [2, 3], [3, 4], [4, 5]] 25 | getConsecutiveArrays([1, 2, 3, 4, 5], 3); // [[1, 2, 3], [2, 3, 4], [3, 4, 5]] 26 | getConsecutiveArrays([1, 2, 3, 4, 5], 6); // [] 27 | ``` 28 | -------------------------------------------------------------------------------- /contents/get-the-unique-values-of-an-array.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | contributors: 4 | - vreymond 5 | created: '2020-04-19' 6 | title: Get the unique values of an array 7 | updated: '2021-10-13' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js unique.js 13 | const unique = (arr) => [...new Set(arr)]; 14 | 15 | // Or 16 | const unique = (arr) => arr.filter((el, i, array) => array.indexOf(el) === i); 17 | 18 | // Or 19 | const unique = (arr) => arr.reduce((acc, el) => (acc.includes(el) ? acc : [...acc, el]), []); 20 | ``` 21 | 22 | **TypeScript version** 23 | 24 | ```ts unique.ts 25 | const unique = (arr: T[]): T[] => [...new Set(arr)]; 26 | 27 | // Or 28 | const unique = (arr: T[]): T[] => arr.filter((el, i, array) => array.indexOf(el) === i); 29 | 30 | // Or 31 | const unique = (arr: T[]): T[] => arr.reduce((acc, el) => (acc.includes(el) ? acc : [...acc, el]), [] as T[]); 32 | ``` 33 | -------------------------------------------------------------------------------- /contents/generate-a-hash-of-a-string.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2021-03-21' 4 | title: Generate a hash of a string 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js hash.js 11 | const hash = (str) => str.split('').reduce((prev, curr) => (Math.imul(31, prev) + curr.charCodeAt(0)) | 0, 0); 12 | 13 | // Or 14 | const hash = (str) => str.split('').reduce((prev, curr) => ((prev << 5) - prev + curr.charCodeAt(0)) | 0, 0); 15 | ``` 16 | 17 | **TypeScript version** 18 | 19 | ```ts hash.ts 20 | const hash = (str: string): number => 21 | str.split('').reduce((prev, curr) => (Math.imul(31, prev) + curr.charCodeAt(0)) | 0, 0); 22 | 23 | // Or 24 | const hash = (str: string): number => 25 | str.split('').reduce((prev, curr) => ((prev << 5) - prev + curr.charCodeAt(0)) | 0, 0); 26 | ``` 27 | 28 | **Examples** 29 | 30 | ```js examples.js 31 | hash('hello'); // 99162322 32 | ``` 33 | -------------------------------------------------------------------------------- /contents/wrap-a-number-between-two-values.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Number 3 | contributors: 4 | - iamandrewluca 5 | created: '2021-12-13' 6 | title: Wrap a number between two values 7 | --- 8 | 9 | **JavaScript version** 10 | 11 | ```js wrap.js 12 | const wrap = (num, min, max) => ((((num - min) % (max - min)) + (max - min)) % (max - min)) + min; 13 | ``` 14 | 15 | **TypeScript version** 16 | 17 | ```ts 18 | const wrap = (num: number, min: number, max: number): number => 19 | ((((num - min) % (max - min)) + (max - min)) % (max - min)) + min; 20 | ``` 21 | 22 | **Examples** 23 | 24 | ```js examples.js 25 | wrap(11, 10, 25); // 11 26 | wrap(10, 10, 25); // 10 27 | wrap(9, 10, 25); // 25 28 | wrap(24, 10, 25); // 24 29 | wrap(25, 10, 25); // 25 30 | wrap(26, 10, 25); // 10 31 | ``` 32 | 33 | ## See also 34 | 35 | - [Clamp a number between two values](https://phuoc.ng/collection/1-loc/clamp-a-number-between-two-values/) 36 | -------------------------------------------------------------------------------- /contents/get-the-number-of-a-character-in-a-string.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2020-08-02' 4 | title: Get the number of a character in a string 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js characterCount.js 11 | const characterCount = (str, char) => str.split(char).length - 1; 12 | 13 | // Or 14 | const characterCount = (str, char) => str.replace(new RegExp(String.raw`[^${char}]`, 'g'), '').length; 15 | ``` 16 | 17 | **TypeScript version** 18 | 19 | ```ts characterCount.ts 20 | const characterCount = (str: string, char: string): number => str.split(char).length - 1; 21 | 22 | // Or 23 | const characterCount = (str: string, char: string): number => 24 | str.replace(new RegExp(String.raw`[^${char}]`, 'g'), '').length; 25 | ``` 26 | 27 | **Examples** 28 | 29 | ```js examples.js 30 | characterCount('192.168.1.1', '.'); // 3 31 | characterCount('star wars', 's'); // 2 32 | ``` 33 | -------------------------------------------------------------------------------- /contents/check-if-a-flat-array-has-duplicate-values.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2021-02-25' 4 | title: Check if a flat array has duplicate values 5 | updated: '2022-01-26' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js hasDuplicateValues.js 11 | const hasDuplicateValues = (arr) => new Set(arr).size !== arr.length; 12 | 13 | // Or 14 | const hasDuplicateValues = (arr) => arr.some((item, index, arr) => arr.indexOf(item) !== index); 15 | ``` 16 | 17 | **TypeScript version** 18 | 19 | ```ts hasDuplicateValues.ts 20 | const hasDuplicateValues = (arr: T[]): boolean => new Set(arr).size !== arr.length; 21 | 22 | // Or 23 | const hasDuplicateValues = (arr: T[]): boolean => arr.some((item, index, arr) => arr.indexOf(item) !== index); 24 | ``` 25 | 26 | **Examples** 27 | 28 | ```js examples.js 29 | hasDuplicateValues(['h', 'e', 'l', 'l', 'o']); // true 30 | hasDuplicateValues(['w', 'o', 'r', 'd']); // false 31 | ``` 32 | -------------------------------------------------------------------------------- /contents/check-if-a-value-is-a-plain-object.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2020-05-13' 4 | title: Check if a value is a plain object 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js isPlainObject.js 11 | const isPlainObject = (v) => !!v && typeof v === 'object' && (v.__proto__ === null || v.__proto__ === Object.prototype); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts isPlainObject.ts 17 | const isPlainObject = (v: any): boolean => 18 | !!v && typeof v === 'object' && (v.__proto__ === null || v.__proto__ === Object.prototype); 19 | ``` 20 | 21 | **Examples** 22 | 23 | ```js examples.js 24 | isPlainObject(null); // false 25 | isPlainObject('hello world'); // false 26 | isPlainObject([]); // false 27 | isPlainObject(Object.create(null)); // false 28 | isPlainObject(function () {}); // false 29 | 30 | isPlainObject({}); // true 31 | isPlainObject({ a: '1', b: '2' }); // true 32 | ``` 33 | -------------------------------------------------------------------------------- /contents/clear-all-cookies.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Misc 3 | contributors: 4 | - iamandrewluca 5 | created: '2021-04-20' 6 | title: Clear all cookies 7 | updated: '2021-10-13' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js clearCookies.js 13 | const clearCookies = () => 14 | document.cookie 15 | .split(';') 16 | .forEach( 17 | (c) => 18 | (document.cookie = c.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`)) 19 | ); 20 | ``` 21 | 22 | **TypeScript version** 23 | 24 | ```ts clearCookies.ts 25 | const clearCookies = (): void => 26 | document.cookie 27 | .split(';') 28 | .forEach( 29 | (c) => 30 | (document.cookie = c.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`)) 31 | ); 32 | ``` 33 | 34 | **Examples** 35 | 36 | ```js examples.js 37 | clearCookies(); 38 | ``` 39 | -------------------------------------------------------------------------------- /contents/encode-a-url.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Misc 3 | created: '2020-05-03' 4 | title: Encode a URL 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js encode.js 11 | // `encodeURIComponent` doesn't encode -_.!~*'() 12 | const encode = (url) => 13 | encodeURIComponent(url) 14 | .replace(/!/g, '%21') 15 | .replace(/~/g, '%7E') 16 | .replace(/\*/g, '%2A') 17 | .replace(/'/g, '%27') 18 | .replace(/\(/g, '%28') 19 | .replace(/\)/g, '%29') 20 | .replace(/%20/g, '+'); 21 | ``` 22 | 23 | **TypeScript version** 24 | 25 | ```ts encode.ts 26 | const encode = (url: string): string => 27 | encodeURIComponent(url) 28 | .replace(/!/g, '%21') 29 | .replace(/~/g, '%7E') 30 | .replace(/\*/g, '%2A') 31 | .replace(/'/g, '%27') 32 | .replace(/\(/g, '%28') 33 | .replace(/\)/g, '%29') 34 | .replace(/%20/g, '+'); 35 | ``` 36 | -------------------------------------------------------------------------------- /contents/prepend-a-line-number-to-each-line-of-a-text-document.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2021-06-07' 4 | title: Prepend a line number to each line of a text document 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js prependNumbers.js 11 | const prependNumbers = (str) => 12 | str 13 | .split(/\r?\n/) 14 | .map((line, i) => `${(i + 1).toString().padStart(2, ' ')} ${line}`) 15 | .join('\n'); 16 | ``` 17 | 18 | **TypeScript version** 19 | 20 | ```ts prependNumbers.ts 21 | const prependNumbers = (str: string): string => 22 | str 23 | .split(/\r?\n/) 24 | .map((line, i) => `${(i + 1).toString().padStart(2, ' ')} ${line}`) 25 | .join('\n'); 26 | ``` 27 | 28 | **Examples** 29 | 30 | ```js examples.js 31 | prependNumbers(`one 32 | two 33 | three 34 | four`); 35 | 36 | /* Output */ 37 | /* 38 | 1 one 39 | 2 two 40 | 3 three 41 | 4 four 42 | */ 43 | ``` 44 | -------------------------------------------------------------------------------- /contents/count-the-occurrences-of-a-value-in-an-array.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | created: '2020-06-11' 4 | title: Count the occurrences of a value in an array 5 | updated: '2021-10-22' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js countOccurrences.js 11 | const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0); 12 | 13 | // Or 14 | const countOccurrences = (arr, val) => arr.filter((item) => item === val).length; 15 | ``` 16 | 17 | **TypeScript version** 18 | 19 | ```ts countOccurrences.ts 20 | const countOccurrences = (arr: T[], val: T): number => arr.reduce((a, v) => (v === val ? a + 1 : a), 0); 21 | 22 | // Or 23 | const countOccurrences = (arr: T[], val: T): number => arr.filter((item) => item === val).length; 24 | ``` 25 | 26 | **Examples** 27 | 28 | ```js examples.js 29 | countOccurrences([2, 1, 3, 3, 2, 3], 2); // 2 30 | countOccurrences(['a', 'b', 'a', 'c', 'a', 'b'], 'a'); // 3 31 | ``` 32 | -------------------------------------------------------------------------------- /contents/merge-two-arrays.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | created: '2020-04-19' 4 | title: Merge two arrays 5 | updated: '2021-10-22' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js merge.js 11 | // Merge but don't remove the duplications 12 | const merge = (a, b) => a.concat(b); 13 | // Or 14 | const merge = (a, b) => [...a, ...b]; 15 | 16 | // Merge and remove the duplications 17 | const merge = (a, b) => [...new Set(a.concat(b))]; 18 | // Or 19 | const merge = (a, b) => [...new Set([...a, ...b])]; 20 | ``` 21 | 22 | **TypeScript version** 23 | 24 | ```ts merge.ts 25 | // Merge but don't remove the duplications 26 | const merge = (a: T[], b: T[]): T[] => a.concat(b); 27 | // Or 28 | const merge = (a: T[], b: T[]): T[] => [...a, ...b]; 29 | 30 | // Merge and remove the duplications 31 | const merge = (a: T[], b: T[]): T[] => [...new Set(a.concat(b))]; 32 | // Or 33 | const merge = (a: T[], b: T[]): T[] => [...new Set([...a, ...b])]; 34 | ``` 35 | -------------------------------------------------------------------------------- /contents/check-if-two-dom-rects-intersect.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: DOM 3 | created: '2023-12-12' 4 | openGraphCover: /og/1-loc/check-two-dom-rects-intersect.png 5 | title: Check if two DOMRects intersect 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js intersect.js 11 | const intersect = (a, b) => (b.right >= a.left && b.left <= a.right && b.top <= a.bottom && b.bottom >= a.top); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts intersect.ts 17 | const intersect = (a: DOMRect, b: DOMRect): boolean => (b.right >= a.left && b.left <= a.right && b.top <= a.bottom && b.bottom >= a.top); 18 | ``` 19 | 20 | **Example** 21 | 22 | ```js example.js 23 | const a = new DOMRect(0, 0, 40, 40); 24 | const b = new DOMRect(10, 10, 20, 20); 25 | intersect(a, b); // true 26 | ``` 27 | 28 | ## See also 29 | 30 | - [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/) 31 | -------------------------------------------------------------------------------- /contents/check-if-an-array-is-subset-of-other-array.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | contributors: 4 | - lupu60 5 | - Rupesh Jaiswal 6 | created: '2020-05-10' 7 | title: Check if an array is subset of other array 8 | updated: '2021-10-22' 9 | --- 10 | 11 | **JavaScript version** 12 | 13 | ```js isSubset.js 14 | // Check if `b` is subset of `a` 15 | const isSubset = (a, b) => new Set(b).size === new Set(b.concat(a)).size; 16 | 17 | // Or 18 | const isSubset = (a, b) => b.join('|').includes(a.join('|')); 19 | ``` 20 | 21 | **TypeScript version** 22 | 23 | ```ts isSubset.ts 24 | const isSubset = (a: T[], b: T[]): boolean => new Set(b).size === new Set(b.concat(a)).size; 25 | 26 | // Or 27 | const isSubset = (a: T[], b: T[]): boolean => b.join('|').includes(a.join('|')); 28 | ``` 29 | 30 | **Examples** 31 | 32 | ```js examples.js 33 | isSubset([1, 2], [1, 2, 3, 4]); // true 34 | isSubset([1, 2, 5], [1, 2, 3, 4]); // false 35 | isSubset([6], [1, 2, 3, 4]); // false 36 | ``` 37 | -------------------------------------------------------------------------------- /contents/find-the-closest-number-from-an-array.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | created: '2020-05-22' 4 | title: Find the closest number from an array 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js closest.js 11 | // Find the number from `arr` which is closest to `n` 12 | const closest = (arr, n) => arr.reduce((prev, curr) => (Math.abs(curr - n) < Math.abs(prev - n) ? curr : prev)); 13 | 14 | // Or 15 | const closest = (arr, n) => arr.sort((a, b) => Math.abs(a - n) - Math.abs(b - n))[0]; 16 | ``` 17 | 18 | **TypeScript version** 19 | 20 | ```ts closest.ts 21 | const closest = (arr: number[], n: number): number => 22 | arr.reduce((prev, curr) => (Math.abs(curr - n) < Math.abs(prev - n) ? curr : prev)); 23 | 24 | // Or 25 | const closest = (arr: number[], n: number): number => arr.sort((a, b) => Math.abs(a - n) - Math.abs(b - n))[0]; 26 | ``` 27 | 28 | **Example** 29 | 30 | ```js example.js 31 | closest([29, 87, 8, 78, 97, 20, 75, 33, 24, 17], 50); // 33 32 | ``` 33 | -------------------------------------------------------------------------------- /contents/get-indices-of-a-value-in-an-array.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | created: '2021-03-07' 4 | title: Get indices of a value in an array 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js indices.js 11 | const indices = (arr, value) => arr.reduce((acc, v, i) => (v === value ? [...acc, i] : acc), []); 12 | 13 | // Or 14 | const indices = (arr, value) => arr.map((v, i) => (v === value ? i : false)).filter(Boolean); 15 | ``` 16 | 17 | **TypeScript version** 18 | 19 | ```ts indices.ts 20 | const indices = (arr: T[], value: T): number[] => ( 21 | arr.reduce((acc, v, i) => (v === value ? [...acc, i] : acc), [] as number[]) 22 | ); 23 | 24 | // Or 25 | const indices = (arr: T[], value: T): number[] => ( 26 | arr.map((v, i) => (v === value ? i : false)).filter(Boolean) as number[] 27 | ); 28 | ``` 29 | 30 | **Examples** 31 | 32 | ```js examples.js 33 | indices(['h', 'e', 'l', 'l', 'o'], 'l'); // [2, 3] 34 | indices(['h', 'e', 'l', 'l', 'o'], 'w'); // [] 35 | ``` 36 | -------------------------------------------------------------------------------- /contents/check-if-a-number-is-even.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | contributors: 4 | - chety 5 | - ietienam 6 | - Vadim-Moshev 7 | - marcobiedermann 8 | created: '2020-05-06' 9 | title: Check if a number is even 10 | updated: '2021-10-13' 11 | --- 12 | 13 | **JavaScript version** 14 | 15 | ```js isEven.js 16 | const isEven = (n) => n % 2 === 0; 17 | 18 | // Or 19 | const isEven = (n) => (n & 1) === 0; 20 | 21 | // Or 22 | const isEven = (n) => !(n & 1); 23 | 24 | // Or 25 | const isEven = (n) => Number.isInteger(n / 2); 26 | ``` 27 | 28 | **TypeScript version** 29 | 30 | ```ts isEven.ts 31 | const isEven = (n: number): boolean => n % 2 === 0; 32 | 33 | // Or 34 | const isEven = (n: number): boolean => (n & 1) === 0; 35 | 36 | // Or 37 | const isEven = (n: number): boolean => !(n & 1); 38 | 39 | // Or 40 | const isEven = (n: number): boolean => Number.isInteger(n / 2); 41 | ``` 42 | 43 | **Examples** 44 | 45 | ```js examples.js 46 | isEven(1); // false 47 | isEven(2); // true 48 | ``` 49 | -------------------------------------------------------------------------------- /contents/check-if-all-array-elements-are-equal-to-a-given-value.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | contributors: 4 | - contributorpw 5 | - tugsanunlu 6 | created: '2020-05-08' 7 | title: Check if all array elements are equal to a given value 8 | updated: '2021-10-22' 9 | --- 10 | 11 | **JavaScript version** 12 | 13 | ```js isEqual.js 14 | const isEqual = (arr, value) => arr.every((item) => item === value); 15 | 16 | // Or 17 | // Ends earlier for false arrays 18 | const isEqual = (arr, value) => !arr.some((item) => item !== value); 19 | ``` 20 | 21 | **TypeScript version** 22 | 23 | ```ts isEqual.ts 24 | const isEqual = (arr: T[], value: T): boolean => arr.every((item) => item === value); 25 | 26 | // Or 27 | const isEqual = (arr: T[], value: T): boolean => !arr.some((item) => item !== value); 28 | ``` 29 | 30 | **Examples** 31 | 32 | ```js examples.js 33 | isEqual(['foo', 'foo'], 'foo'); // true 34 | isEqual(['foo', 'bar'], 'foo'); // false 35 | isEqual(['bar', 'bar'], 'foo'); // false 36 | ``` 37 | -------------------------------------------------------------------------------- /contents/sort-an-array-of-items-by-given-key.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | created: '2021-01-13' 4 | title: Sort an array of items by given key 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js sortBy.js 11 | const sortBy = (arr, k) => arr.concat().sort((a, b) => (a[k] > b[k] ? 1 : a[k] < b[k] ? -1 : 0)); 12 | ``` 13 | 14 | **TypeScript version** 15 | 16 | ```ts sortBy.ts 17 | const sortBy = , K extends keyof T>(arr: T[], k: K): T[] => ( 18 | arr.concat().sort((a, b) => (a[k] > b[k] ? 1 : a[k] < b[k] ? -1 : 0)) 19 | ); 20 | ``` 21 | 22 | **Example** 23 | 24 | ```js example.js 25 | const people = [ 26 | { name: 'Foo', age: 42 }, 27 | { name: 'Bar', age: 24 }, 28 | { name: 'Fuzz', age: 36 }, 29 | { name: 'Baz', age: 32 }, 30 | ]; 31 | sortBy(people, 'age'); 32 | 33 | // [ 34 | // { name: 'Bar', age: 24 }, 35 | // { name: 'Baz', age: 32 }, 36 | // { name: 'Fuzz', age: 36 }, 37 | // { name: 'Foo', age: 42 }, 38 | // ] 39 | ``` 40 | -------------------------------------------------------------------------------- /contents/get-the-month-name-of-a-date.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Date Time 3 | created: '2020-05-05' 4 | title: Get the month name of a date 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js getMonthName.js 11 | // `date` is a Date object 12 | const getMonthName = (date) => 13 | [ 14 | 'January', 15 | 'February', 16 | 'March', 17 | 'April', 18 | 'May', 19 | 'June', 20 | 'July', 21 | 'August', 22 | 'September', 23 | 'October', 24 | ' November', 25 | 'December', 26 | ][date.getMonth()]; 27 | ``` 28 | 29 | **TypeScript version** 30 | 31 | ```ts getMonthName.ts 32 | const getMonthName = (date: Date): string => 33 | [ 34 | 'January', 35 | 'February', 36 | 'March', 37 | 'April', 38 | 'May', 39 | 'June', 40 | 'July', 41 | 'August', 42 | 'September', 43 | 'October', 44 | ' November', 45 | 'December', 46 | ][date.getMonth()]; 47 | ``` 48 | -------------------------------------------------------------------------------- /contents/uppercase-the-first-character-of-each-word-in-a-string.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2020-05-03' 4 | title: Uppercase the first character of each word in a string 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js uppercaseWords.js 11 | const uppercaseWords = (str) => 12 | str 13 | .split(' ') 14 | .map((w) => `${w.charAt(0).toUpperCase()}${w.slice(1)}`) 15 | .join(' '); 16 | 17 | // Or 18 | const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase()); 19 | ``` 20 | 21 | **TypeScript version** 22 | 23 | ```ts uppercaseWords.ts 24 | const uppercaseWords = (str: string): string => 25 | str 26 | .split(' ') 27 | .map((w) => `${w.charAt(0).toUpperCase()}${w.slice(1)}`) 28 | .join(' '); 29 | 30 | // Or 31 | const uppercaseWords = (str: string): string => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase()); 32 | ``` 33 | 34 | **Examples** 35 | 36 | ```js examples.js 37 | uppercaseWords('hello world'); // 'Hello World' 38 | ``` 39 | -------------------------------------------------------------------------------- /contents/check-if-a-character-is-a-digit.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Validator 3 | created: '2021-10-22' 4 | title: Check if a character is a digit 5 | --- 6 | 7 | **JavaScript version** 8 | 9 | ```js isDigit.js 10 | const isDigit = (char) => char < 10; 11 | 12 | // Or 13 | const isDigit = (char) => char.length === 1 && c >= '0' && c <= '9'; 14 | 15 | // Or 16 | const isDigit = (char) => Boolean([true, true, true, true, true, true, true, true, true, true][char]); 17 | ``` 18 | 19 | **TypeScript version** 20 | 21 | ```ts isDigit.ts 22 | const isDigit = (char: string): boolean => char < 10; 23 | 24 | // Or 25 | const isDigit = (char: string): boolean => char.length === 1 && c >= '0' && c <= '9'; 26 | 27 | // Or 28 | const isDigit = (char: string): boolean => Boolean([true, true, true, true, true, true, true, true, true, true][char]); 29 | ``` 30 | 31 | **Examples** 32 | 33 | ```js examples.js 34 | isDigit('a'); // false 35 | isDigit('abc'); // false 36 | isDigit(10); // false 37 | isDigit('10'); // false 38 | 39 | isDigit('2'); // true 40 | isDigit(2); // true 41 | ``` 42 | -------------------------------------------------------------------------------- /contents/find-the-index-of-the-last-matching-item-of-an-array.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Array 3 | created: '2020-12-31' 4 | title: Find the index of the last matching item of an array 5 | updated: '2021-10-22' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js lastIndex.js 11 | const lastIndex = (arr, predicate) => arr.reduce((prev, curr, index) => (predicate(curr) ? index : prev), -1); 12 | 13 | // Or 14 | const lastIndex = (arr, predicate) => arr.map((item) => predicate(item)).lastIndexOf(true); 15 | ``` 16 | 17 | **TypeScript version** 18 | 19 | ```ts lastIndex.ts 20 | const lastIndex = (arr: T[], predicate: (a: T) => boolean): number => arr.reduce((prev, curr, index) => (predicate(curr) ? index : prev), -1); 21 | 22 | // Or 23 | const lastIndex = (arr: T[], predicate: (a: T) => boolean): number => arr.map((item) => predicate(item)).lastIndexOf(true); 24 | ``` 25 | 26 | **Examples** 27 | 28 | ```js examples.js 29 | lastIndex([1, 3, 5, 7, 9, 2, 4, 6, 8], (i) => i % 2 === 1); // 4 30 | lastIndex([1, 3, 5, 7, 9, 8, 6, 4, 2], (i) => i > 6); // 5 31 | ``` 32 | -------------------------------------------------------------------------------- /contents/calculate-the-distance-to-the-bottom-of-a-page.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: DOM 3 | created: '2023-08-23' 4 | description: one-liner function to calculate how far you are from the bottom of the page 5 | openGraphCover: /og/1-loc/distance-to-bottom.png 6 | title: Calculate the distance to the bottom of a page 7 | --- 8 | 9 | The following snippet calculates how far you are from the bottom of the page. 10 | 11 | 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`). 12 | 13 | The result is the distance from your current position to the bottom of the page. 14 | 15 | **JavaScript version** 16 | 17 | ```js distanceToBottom.js 18 | const distanceToBottom = document.body.scrollHeight - window.innerHeight - window.scrollY; 19 | ``` 20 | 21 | **TypeScript version** 22 | 23 | ```js distanceToBottom.ts 24 | const distanceToBottom: number = document.body.scrollHeight - window.innerHeight - window.scrollY; 25 | ``` 26 | -------------------------------------------------------------------------------- /contents/capitalize-a-string.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | contributors: 4 | - Edmon Narmetov 5 | - fahimfaisaal 6 | created: '2023-04-11' 7 | title: Capitalize a string 8 | updated: '2020-04-19' 9 | --- 10 | 11 | **JavaScript version** 12 | 13 | ```js capitalize.js 14 | const capitalize = (str) => `${str.charAt(0).toUpperCase()}${str.slice(1)}`; 15 | 16 | // Or 17 | const capitalize = ([first, ...rest]) => `${first.toUpperCase()}${rest.join('')}`; 18 | 19 | // Or 20 | const capitalize = (str) => str.replace(/^([a-z])/, (first) => first.toUpperCase()); 21 | ``` 22 | 23 | **TypeScript version** 24 | 25 | ```ts capitalize.ts 26 | const capitalize = (str: string): string => `${str.charAt(0).toUpperCase()}${str.slice(1)}`; 27 | 28 | // Or 29 | const capitalize = ([first, ...rest]: string): string => `${first.toUpperCase()}${rest.join('')}`; 30 | 31 | // Or 32 | const capitalize = (str: string): string => str.replace(/^([a-z])/, (first) => first.toUpperCase()); 33 | ``` 34 | 35 | **Examples** 36 | 37 | ```js examples.js 38 | capitalize('hello world'); // 'Hello world' 39 | ``` 40 | -------------------------------------------------------------------------------- /contents/escape-html-special-characters.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: String 3 | created: '2020-05-29' 4 | title: Escape HTML special characters 5 | updated: '2021-10-13' 6 | --- 7 | 8 | **JavaScript version** 9 | 10 | ```js escape.js 11 | const escape = (str) => 12 | str 13 | .replace(/&/g, '&') 14 | .replace(//g, '>') 16 | .replace(/'/g, ''') 17 | .replace(/"/g, '"'); 18 | 19 | // Or 20 | const escape = (str) => 21 | str.replace(/[&<>"']/g, (m) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[m])); 22 | ``` 23 | 24 | **TypeScript version** 25 | 26 | ```ts escape.ts 27 | const escape = (str: string): string => 28 | str 29 | .replace(/&/g, '&') 30 | .replace(//g, '>') 32 | .replace(/'/g, ''') 33 | .replace(/"/g, '"'); 34 | 35 | // Or 36 | const escape = (str: string): string => 37 | str.replace(/[&<>"']/g, (m) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[m])); 38 | ``` 39 | -------------------------------------------------------------------------------- /contents/box-handler.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Function 3 | contributors: 4 | - Valeriy Arbachakov 5 | created: '2020-07-15' 6 | title: Box handler 7 | updated: '2020-08-18' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js boxHandler.js 13 | const boxHandler = (x) => ({ next: (f) => boxHandler(f(x)), done: (f) => f(x) }); 14 | ``` 15 | 16 | **Examples** 17 | 18 | ```js examples.js 19 | // First example 20 | const getPercentNumber = (str) => 21 | boxHandler(str) 22 | .next((str) => str.replace(/\%/, '')) 23 | .next((str) => parseFloat(str)) 24 | .done((res) => res * 0.01); 25 | 26 | getPercentNumber('50%'); // 0.5 27 | 28 | // Second example 29 | const getMoney = (price) => Number.parseFloat(price.replace(/\$/, '')); 30 | const getPercent = (percent) => Number.parseFloat(percent.replace(/\%/)) * 0.01; 31 | 32 | const getDiscountPrice = (price, discount) => 33 | boxHandler(getMoney(price)) 34 | .done((cents) => boxHandler(getPercent(discount)).next((save) => cents - cents * save)) 35 | .done((res) => res); 36 | 37 | getDiscountPrice('$6.00', '20%'); // 4.8 38 | ``` 39 | -------------------------------------------------------------------------------- /contents/prefix-an-integer-with-zeros.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | category: Number 3 | contributors: 4 | - VincentRoth 5 | created: '2020-04-23' 6 | title: Prefix an integer with zeros 7 | updated: '2021-10-13' 8 | --- 9 | 10 | **JavaScript version** 11 | 12 | ```js prefixWithZeros.js 13 | const prefixWithZeros = (n, length) => (n / Math.pow(10, length)).toFixed(length).substr(2); 14 | 15 | // Or 16 | const prefixWithZeros = (n, length) => `${Array(length).join('0')}${n}`.slice(-length); 17 | 18 | // Or 19 | const prefixWithZeros = (n, length) => String(n).padStart(length, '0'); 20 | ``` 21 | 22 | **TypeScript version** 23 | 24 | ```ts prefixWithZeros.ts 25 | const prefixWithZeros = (n: number, length: number): string => (n / Math.pow(10, length)).toFixed(length).substr(2); 26 | 27 | // Or 28 | const prefixWithZeros = (n: number, length: number): string => `${Array(length).join('0')}${n}`.slice(-length); 29 | 30 | // Or 31 | const prefixWithZeros = (n: number, length: number): string => String(n).padStart(length, '0'); 32 | ``` 33 | 34 | **Examples** 35 | 36 | ```js examples.js 37 | prefixWithZeros(42, 5); // '00042' 38 | ``` 39 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 phuoc-ng 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. --------------------------------------------------------------------------------