From 3a24e6d5f83a6508aed4ee7bfd13a49bdd8b7dc5 Mon Sep 17 00:00:00 2001 From: Jeremy Butler Date: Mon, 15 Jan 2024 13:30:38 +1000 Subject: [PATCH] Updates docs --- content/2.functions/actions.md | 44 ++-- content/2.functions/detections.md | 187 ++++++++-------- content/2.functions/formatters.md | 44 ++-- content/2.functions/generators.md | 16 +- content/2.functions/modifiers.md | 356 +++++++++++++++++++++--------- content/2.functions/numbers.md | 115 +++++++--- content/2.functions/validators.md | 310 ++++++++++++++++++-------- docs.ts | 23 +- utils/detections.ts | 62 +++--- 9 files changed, 750 insertions(+), 407 deletions(-) diff --git a/content/2.functions/actions.md b/content/2.functions/actions.md index e67d3c33..d67bba1d 100644 --- a/content/2.functions/actions.md +++ b/content/2.functions/actions.md @@ -1,100 +1,86 @@ # Actions -#### A collection of useful actions +A collection of useful actions -### -Scrolls to the element with the specified ID. @example scrollToAnchor('#my-anchor') +Scrolls to the element with the specified ID. ```js [js] scrollToAnchor('#my-anchor') ``` -### -Smoothly scroll to the top of the page @example scrollToTop() +Smoothly scroll to the top of the page ```js [js] scrollToTop() ``` -### -Smoothly scroll to the bottom of the page @example scrollToBottom() +Smoothly scroll to the bottom of the page ```js [js] scrollToBottom() ``` -### -Toggles the body scroll with the specified class name @example toggleBodyScroll('overflow-hidden') +Toggles the body scroll with the specified class name ```js [js] toggleBodyScroll('overflow-hidden') ``` -### -Toggles the element scroll @example toggleElementScroll(document.querySelector('#my-element')) +Toggles the element scroll ```js [js] toggleElementScroll(document.querySelector('#my-element')) ``` -### -Copies a text to the clipboard @example copyToClipboard() +Copies a text to the clipboard ```js [js] copyToClipboard() ``` -### -Toggles the fullscreen mode @example toggleFullScreen() +Toggles the fullscreen mode ```js [js] toggleFullScreen() ``` -### -Toggles the dark mode @example toggleDarkMode() +Toggles the dark mode ```js [js] toggleDarkMode() ``` -### -Redirects to a new URL @example redirect('https://example.com') +Redirects to a new URL ```js [js] redirect('https://example.com') ``` -### -Resets a form @example resetForm(document.querySelector('form')) +Resets a form ```js [js] resetForm(document.querySelector('form')) ``` -### -Focuses on an element @example focusOn(document.querySelector('#my-element')) +Focuses on an element ```js [js] focusOn(document.querySelector('#my-element')) ``` -### -Focuses on the first element @example focusOnFirst(document.querySelector('#my-element')) +Focuses on the first element ```js [js] focusOnFirst(document.querySelector('#my-element')) ``` -### -Focuses on the last element @example focusOnLast(document.querySelector('#my-element')) +Focuses on the last element ```js [js] focusOnLast(document.querySelector('#my-element')) ``` -### -Sets up a keyboard trap within an HTML element, allowing the focus to cycle between the first and last focusable elements when the Tab key is pressed. @example focusTrap(document.querySelector('#my-element')) +Sets up a keyboard trap within an HTML element, allowing the focus to cycle between the first and last focusable elements when the Tab key is pressed. ```js [js] focusTrap(document.querySelector('#my-element')) diff --git a/content/2.functions/detections.md b/content/2.functions/detections.md index 9b15941f..0a67d783 100644 --- a/content/2.functions/detections.md +++ b/content/2.functions/detections.md @@ -1,291 +1,300 @@ # Detections -#### A collection of detections for common data types +A collection of detections for common data types -### export function detectDevice -Detect the current device type (Mobile or Desktop) @example detectDevice() @returns `Mobile` or `Desktop` +### detectDevice + +Detect the current device type (Mobile or Desktop) ```js [js] detectDevice() ``` -### export function detectOS -Detect the current operating system @example detectOS() @returns `Windows`, `Mac`, `Linux`, `UNIX`, or `Unknown` +**Returns:** `Mobile` or `Desktop` + +### detectOS + +Detect the current operating system ```js [js] detectOS() ``` -### export function detectBrowser -Detects the user's browser based on the user agent string. @example detectBrowser() @returns `Chrome`, `Firefox`, `Safari`, `Opera`, `Edge`, `IE`, or `Unknown` +**Returns:** `Windows`, `Mac`, `Linux`, `UNIX`, or `Unknown` + +### detectBrowser + +Detects the user's browser based on the user agent string. ```js [js] detectBrowser() ``` -### export function detectActiveBrowser -Detect if the browser window is currently active or hidden. @example detectActiveBrowser() +**Returns:** `Chrome`, `Firefox`, `Safari`, `Opera`, `Edge`, `IE`, or `Unknown` + +### detectActiveBrowser + +Detect if the browser window is currently active or hidden. ```js [js] detectActiveBrowser() ``` -### export function detectColorScheme -Detect the current color scheme (Light or Dark) @example detectColorScheme() @returns `Light` or `Dark` +### detectColorScheme + +Detect the current color scheme (Light or Dark) ```js [js] detectColorScheme() ``` -### export function detectBrowserLanguage -Detect the current browser language @example detectBrowserLanguage() +**Returns:** `Light` or `Dark` + +### detectBrowserLanguage + +Detect the current browser language ```js [js] detectBrowserLanguage() ``` -### export function detectGeolocation -Detect the current user's location @example detectUserLocation() @returns `US`, `UK`, `CA`, `AU`, `NZ`, `EU`, `Unknown` +### detectGeolocation + +Detect the current user's location ```js [js] detectUserLocation() ``` -### export function detectUserTimezone -Detect the current user's Timezone @example detectUserTimezone() +**Returns:** `US`, `UK`, `CA`, `AU`, `NZ`, `EU`, `Unknown` + +### detectUserTimezone + +Detect the current user's Timezone ```js [js] detectUserTimezone() ``` -### export function detectDeviceOrientation -Detect the currect device orientation @example detectDeviceOrientation() +### detectDeviceOrientation + +Detect the currect device orientation ```js [js] detectDeviceOrientation() ``` -### export function detectDeviceMotion -Detect the current device motion @example detectDeviceMotion() +### detectDeviceMotion + +Detect the current device motion ```js [js] detectDeviceMotion() ``` -### -Detect the browser's window size @example detectWindowSize() +Detect the browser's window size ```js [js] detectWindowSize() ``` -### -Detect the screen or monitor size @example detectScreenSize() +Detect the screen or monitor size ```js [js] detectScreenSize() ``` -### -Detect the container size via ID @example detectContainerSize('container') +Detect the container size via ID ```js [js] detectContainerSize('container') ``` -### export function detectTailwindBreakpoint -Detect the current breakpoint based on Tailwind CSS breakpoints @example detectTailwindBreakpoint() +### detectTailwindBreakpoint + +Detect the current breakpoint based on Tailwind CSS breakpoints ```js [js] detectTailwindBreakpoint() ``` -### export function detectTailwindContainerBreakpoint -Detect the current container breakpoint based on Tailwind CSS breakpoints @example detectTailwindContainerBreakpoint('container') +### detectTailwindContainerBreakpoint + +Detect the current container breakpoint based on Tailwind CSS breakpoints ```js [js] detectTailwindContainerBreakpoint('container') ``` -### -Detect the current scroll position of the window @example detectScrollPosition() +Detect the current scroll position of the window ```js [js] detectScrollPosition() ``` -### -Detect the current mouse position within the window @example detectMousePosition(event) +Detect the current mouse position within the window ```js [js] detectMousePosition(event) ``` -### -Detect the current mouse position within a container via ID @example detectRelativeMousePosition('container', event) +Detect the current mouse position within a container via ID ```js [js] detectRelativeMousePosition('container', event) ``` -### export function detectNetworkStatus -Detect the current network status of the user (Online or Offline) @example detectNetworkStatus() +### detectNetworkStatus + +Detect the current network status of the user (Online or Offline) ```js [js] detectNetworkStatus() ``` -### -Detect the current memory status of the user (RAM) @example detectMemoryStatus() +Detect the current memory status of the user (RAM) ```js [js] detectMemoryStatus() ``` -### export function detectPerformance -Detect the current performance status of the user (CPU, RAM, etc.) @example detectPerformance() +### detectPerformance + +Detect the current performance status of the user (CPU, RAM, etc.) ```js [js] detectPerformance() ``` -### -Detect the current storage status of the user (Local Storage, Session Storage) @example detectStorage() +// Detect the current storage status of the user (Local Storage, Session Storage) ```js [js] detectStorage() ``` -### -Returns a cookie value by name @example detectCookie('name') +Returns a cookie value by name ```js [js] detectCookie('name') ``` -### -Returns a local storage value by name and parses it into JSON @example detectLocalStorage('name') +### detectLocalStorage + +Returns a local storage value by name and parses it into JSON ```js [js] detectLocalStorage('name') ``` -### -Returns a session storage value by name and parses it into JSON @example detectSessionStorage('name') +Returns a session storage value by name and parses it into JSON ```js [js] detectSessionStorage('name') ``` -### -Returns a value from the URL by name @example detectURLParameters('http://url.com/page?name=Adam&surname=Smith') +Returns a value from the URL by name ```js [js] detectURLParameters('http://url.com/page?name=Adam&surname=Smith') ``` -### -Returns a value from the URL hash by name @example detectURLHashParameters() +Returns a value from the URL hash by name ```js [js] detectURLHashParameters() ``` -### -Retrieves and returns the parameters from the URL search query string @example detectURLSearchParameters() +Retrieves and returns the parameters from the URL search query string ```js [js] detectURLSearchParameters() ``` -### -Returns the current URL @example detectURL() +### detectURL + +Returns the current URL ```js [js] detectURL() ``` -### -Returns the current domain @example detectDomain() +### detectDomain + +Returns the current domain ```js [js] detectDomain() ``` -### -Returns the current IP address @example detectIP() +### detectIP + +Returns the current IP address ```js [js] detectIP() ``` -### -Returns the current port @example detectPort() +### detectPort + +Returns the current port ```js [js] detectPort() ``` -### -Returns the current protocol (HTTP or HTTPS) @example detectProtocol() +Returns the current protocol (HTTP or HTTPS) ```js [js] detectProtocol() ``` -### -Returns the URL of the referring page (the page that linked to the current page) @example detectReferrer() +Returns the URL of the referring page (the page that linked to the current page) ```js [js] detectReferrer() ``` -### export function detectCachedData -Retrieves cached entries and optionally filters the entries based on a provided key @example detectCachedData('abc') +### detectCachedData + +Retrieves cached entries and optionally filters the entries based on a provided key ```js [js] detectCachedData('abc') ``` -### -Detects if the element is currently in the viewport @example isInViewport(element) +Detects if the element is currently in the viewport ```js [js] -isInViewport(element) +detectInViewport(element) ``` -### -Detects if the element is currently in the container via ID @example isInContainer(element, 'container') +Detects if the element is currently in the container via ID ```js [js] -isInContainer(element, 'container') +detectInContainer(element, 'container') ``` -### -Detects if the element is overflowing vertically @example isOverflowingY(element) +Detects if the element is overflowing vertically ```js [js] -isOverflowingY(element) +detectOverflowingY(element) ``` -### -Detects if the element is overflowing horizontally @example isOverflowingX(element) +Detects if the element is overflowing horizontally ```js [js] -isOverflowingX(element) +detectOverflowingX(element) ``` -### -Detects if the element is scrollable (overflowing vertically or horizontally) @example isScrollable(element) +Detects if the element is scrollable (overflowing vertically or horizontally) ```js [js] -isScrollable(element) +detectScrollable(element) ``` -### -Detects if the elements is an HTML element @example isElement(element) +Detects if the elements is an HTML element ```js [js] -isElement(element) +detectElement() ``` diff --git a/content/2.functions/formatters.md b/content/2.functions/formatters.md index 3183edb2..2831dfc7 100644 --- a/content/2.functions/formatters.md +++ b/content/2.functions/formatters.md @@ -1,46 +1,64 @@ # Formatters -#### A collection of formatters for common data types +A collection of formatters for common data types -### export function formatCurrency -Format numbers into local currency @example formatCurrency(1234.56) @returns $1,234.56 +### formatCurrency + +Format numbers into local currency ```js [js] formatCurrency(1234.56) ``` -### export function formatValuation -Format numbers into valuations displayed in thounsands, millions or billions @example formatValuation(1234567890) @returns $1.23B +**Returns:** $1,234.56 + +### formatValuation + +Format numbers into valuations displayed in thounsands, millions or billions ```js [js] formatValuation(1234567890) ``` -### export function formatTime -Format time into hours, minutes, and seconds @example formatTime(3723) @returns 1hr 2min 3s +**Returns:** $1.23B + +### formatTime + +Format time into hours, minutes, and seconds ```js [js] formatTime(3723) ``` -### export function formatDatetime -Format Unix timestamp into a datetime string @example formatDatetime(1619097600) @returns 2021-04-22 00:00:00 +**Returns:** 1hr 2min 3s + +### formatDatetime + +Format Unix timestamp into a datetime string ```js [js] formatDatetime(1619097600) ``` -### export function formatPercentage -Format a number into a percentage @example formatPercentage(0.1234) @returns 12.34% +**Returns:** 2021-04-22 00:00:00 + +### formatPercentage + +Format a number into a percentage ```js [js] formatPercentage(0.1234) ``` -### export function formatList -Create a string of comma-separated values from an array of strings with an optional conjunction. @param items - The array of strings. @param limit - The maximum number of items to include before truncating. @param conjunction - The conjunction before the last item e.g. "and" or "or". @example commaList(['one', 'two', 'three']) @returns one, two and three +**Returns:** 12.34% + +### formatList + +Create a string of comma-separated values from an array of strings with an optional conjunction. ```js [js] commaList(['one', 'two', 'three']) ``` +**Returns:** one, two and three + diff --git a/content/2.functions/generators.md b/content/2.functions/generators.md index d6773e83..1c3bc453 100644 --- a/content/2.functions/generators.md +++ b/content/2.functions/generators.md @@ -1,18 +1,24 @@ # Generators -#### A collection of generators +A collection of generators -### export function generateShortId -Generate a unique short ID based on the current timestamp @example generateShortId(36) @returns 1HR2MIN3S +### generateShortId + +Generate a unique short ID based on the current timestamp ```js [js] generateShortId(36) ``` -### export function generateInitials -Generate initials from any string @example generateInitials('John Doe') @returns JD +**Returns:** 1HR2MIN3S + +### generateInitials + +Generate initials from any string ```js [js] generateInitials('John Doe') ``` +**Returns:** JD + diff --git a/content/2.functions/modifiers.md b/content/2.functions/modifiers.md index 32c6c5c7..5fccd602 100644 --- a/content/2.functions/modifiers.md +++ b/content/2.functions/modifiers.md @@ -1,368 +1,514 @@ # Modifiers -#### Modifiers are a key feature of Mods that allow you to easily modify and enhance your content. They are small pieces of code that can be applied to your JS to add functionality, validation or style. +Modifiers are a key feature of Mods that allow you to easily modify and enhance your content. They are small pieces of code that can be applied to your JS to add functionality, validation or style. -### export function widont -Adds a space between the last two words in a string. @example widont('Cool cool cool') @returns cool cool cool +### widont + +Adds a space between the last two words in a string. ```js [js] widont('Cool cool cool') ``` -### export function stripHtml -Strip HTML tags from a string. @example stripHtml('

Hello World

') @returns Hello World +**Returns:** cool cool cool + +### stripHtml + +Strip HTML tags from a string. ```js [js] stripHtml('

Hello World

') ``` -### export function escapeHtml -Escape HTML entities in a string. @example escapeHtml('

Hello World

') @returns <p>Hello World</p> +**Returns:** Hello World + +### escapeHtml + +Escape HTML entities in a string. ```js [js] escapeHtml('

Hello World

') ``` -### export function unescapeHtml -Unescape HTML entities in a string. @example unescapeHtml('<p>Hello World</p>') @returns

Hello World

+**Returns:** <p>Hello World</p> + +### unescapeHtml + +Unescape HTML entities in a string. ```js [js] unescapeHtml('<p>Hello World</p>') ``` -### export function stripTags -Strip HTML tags from a string. @example stripTags('

Hello World

') @returns Hello World +**Returns:**

Hello World

+ +### stripTags + +Strip HTML tags from a string. ```js [js] stripTags('

Hello World

') ``` -### export function slugify -Converts a string to-a-slug. @example slugify('Hello World') @returns hello-world +**Returns:** Hello World + +### slugify + +Converts a string to-a-slug. ```js [js] slugify('Hello World') ``` -### export function deslugify -Converts a slug to a string. @example deslugify('hello-world') @returns hello world +**Returns:** hello-world + +### deslugify + +Converts a slug to a string. ```js [js] deslugify('hello-world') ``` -### export function truncate -Truncates a string to a specified length of characters. @example truncate('Hello World', 5) @returns Hello... +**Returns:** hello world + +### truncate + +Truncates a string to a specified length of characters. ```js [js] truncate('Hello World', 5) ``` -### export function truncateWords -Truncates a string by a number of words @example truncateWords('Hello World', 1) @returns Hello... +**Returns:** Hello... + +### truncateWords + +Truncates a string by a number of words ```js [js] truncateWords('Hello World', 1) ``` -### export function countWords -Counts the number of words in a string. @example countWords('Hello World') @returns 2 +**Returns:** Hello... + +### countWords + +Counts the number of words in a string. ```js [js] countWords('Hello World') ``` -### export function countCharacters -Counts the number of characters in a string. @example countCharacters('Hello World') @returns 11 +**Returns:** 2 + +### countCharacters + +Counts the number of characters in a string. ```js [js] countCharacters('Hello World') ``` -### export function countLines -Counts the number of lines in a string. @example countLines('Hello World') @returns 1 +**Returns:** 11 + +### countLines + +Counts the number of lines in a string. ```js [js] countLines('Hello World') ``` -### export function stripWhitespace -Strips whitespace from a string. @example stripWhitespace('Hello World') @returns HelloWorld +**Returns:** 1 + +### stripWhitespace + +Strips whitespace from a string. ```js [js] stripWhitespace('Hello World') ``` -### export function stripNumbers -Strips numbers from a string. @example stripNumbers('Hello World 123') @returns Hello World +**Returns:** HelloWorld + +### stripNumbers + +Strips numbers from a string. ```js [js] stripNumbers('Hello World 123') ``` -### export function stripPunctuation -Strips punctuation from a string. @example stripPunctuation('Hello World!') @returns Hello World +**Returns:** Hello World + +### stripPunctuation + +Strips punctuation from a string. ```js [js] stripPunctuation('Hello World!') ``` -### export function stripSymbols -Strips symbols from a string. @example stripSymbols('Hello World!') @returns Hello World +**Returns:** Hello World + +### stripSymbols + +Strips symbols from a string. ```js [js] stripSymbols('Hello World!') ``` -### export function stripEmojis -Strips emojis from a string (requires ES6 Unicode support) 🦊. @example stripEmojis('Hello World! 🦊') @returns Hello World! +**Returns:** Hello World + +### stripEmojis + +Strips emojis from a string (requires ES6 Unicode support) 🦊. ```js [js] stripEmojis('Hello World! 🦊') ``` -### export function readingTime -Returns the reading time of a string in Hours, Minutes, and Seconds. @example readingTime('Once, in a vibrant online forum, lived Mod Max, guardian of digital harmony. Max cherished his old scooter, Swift, a symbol of freedom. Navigating both virtual and real worlds, they became legends. Trolls quivered, posts flourished, and lanes whizzed by. Swift’s wheels spun tales, and Max’s keys kept peace. Together, they discovered uncharted threads and hidden lanes. Their journey, an endless adventure, painted pixels and pavements with stories of unity and exhilaration, leaving a trail for all in the intertwined realms of screens and streets.') @returns 1 minute +**Returns:** Hello World! + +### readingTime + +Returns the reading time of a string in Hours, Minutes, and Seconds. ```js [js] readingTime('Once, in a vibrant online forum, lived Mod Max, guardian of digital harmony. Max cherished his old scooter, Swift, a symbol of freedom. Navigating both virtual and real worlds, they became legends. Trolls quivered, posts flourished, and lanes whizzed by. Swift’s wheels spun tales, and Max’s keys kept peace. Together, they discovered uncharted threads and hidden lanes. Their journey, an endless adventure, painted pixels and pavements with stories of unity and exhilaration, leaving a trail for all in the intertwined realms of screens and streets.') ``` -### export function pluralize -Adds plurals to a string. @example pluralize('scooter', 10) @returns scooters +**Returns:** 1 minute + +### pluralize + +Adds plurals to a string. ```js [js] pluralize('scooter', 10) ``` -### export function singularize -Removes plurals from a string. @example singularize('scooters') @returns scooter +**Returns:** scooters + +### singularize + +Removes plurals from a string. ```js [js] singularize('scooters') ``` -### export function ordinalize -Converts a number to a string with ordinal suffix. @example ordinalize(1) @returns 1st +**Returns:** scooter + +### ordinalize + +Converts a number to a string with ordinal suffix. ```js [js] ordinalize(1) ``` -### export function humanize -Replaces underscores with spaces and capitalizes the first letter of each word. @example humanize('hello_world') @returns Hello World +**Returns:** 1st + +### humanize + +Replaces underscores with spaces and capitalizes the first letter of each word. ```js [js] humanize('hello_world') ``` -### export function camelCase -Removes spaces and capitalizes the first letter of each word except for the first word. @example camelCase('hello world') @returns helloWorld +**Returns:** Hello World + +### camelCase + +Removes spaces and capitalizes the first letter of each word except for the first word. ```js [js] camelCase('hello world') ``` -### export function pascalCase -Removes spaces and capitalizes the first letter of each word. @example pascalCase('hello world') @returns HelloWorld +**Returns:** helloWorld + +### pascalCase + +Removes spaces and capitalizes the first letter of each word. ```js [js] pascalCase('hello world') ``` -### export function snakeCase -Replaces spaces with underscores and converts to lowercase. @example snakeCase('hello world') @returns hello_world +**Returns:** HelloWorld + +### snakeCase + +Replaces spaces with underscores and converts to lowercase. ```js [js] snakeCase('hello world') ``` -### export function kebabCase -Replaces spaces with hyphens and converts to lowercase. @example titleize('Hello World') @returns hello-world +**Returns:** hello_world + +### kebabCase + +Replaces spaces with hyphens and converts to lowercase. ```js [js] titleize('Hello World') ``` -### export function titleCase -Converts to title case by capitalizing the first letter of each word. @example titleCase('hello world') @returns Hello World +**Returns:** hello-world + +### titleCase + +Converts to title case by capitalizing the first letter of each word. ```js [js] titleCase('hello world') ``` -### export function sentenceCase -Converts to sentence case by capitalizing the first letter of the first word. @example sentenceCase('hello world') @returns Hello world +**Returns:** Hello World + +### sentenceCase + +Converts to sentence case by capitalizing the first letter of the first word. ```js [js] sentenceCase('hello world') ``` -### export function startWith -Adds a prefix to a string if it doesn't already start with the prefix. @example startWith('usemods.com', 'https://') @returns https://usemods.com +**Returns:** Hello world + +### startWith + +Adds a prefix to a string if it doesn't already start with the prefix. ```js [js] startWith('usemods.com', 'https://') ``` -### export function startWithout -Removes a prefix from a string if it starts with the prefix. @example startWithout('https://usemods.com', 'https://') @returns usemods.com +**Returns:** https://usemods.com + +### startWithout + +Removes a prefix from a string if it starts with the prefix. ```js [js] startWithout('https://usemods.com', 'https://') ``` -### export function endWith -Adds a suffix to a string if it doesn't already end with the suffix. @example endWith('https://usemods', '.com') @returns https://usemods.com +**Returns:** usemods.com + +### endWith + +Adds a suffix to a string if it doesn't already end with the suffix. ```js [js] endWith('https://usemods', '.com') ``` -### export function endWithout -Removes a suffix from a string if it ends with the suffix. @example endWithout('https://usemods.com.au', '.au') @returns https://usemods.com +**Returns:** https://usemods.com + +### endWithout + +Removes a suffix from a string if it ends with the suffix. ```js [js] endWithout('https://usemods.com.au', '.au') ``` -### export function surround -Adds a prefix and suffix to a string if it doesn't already start and end with them. @param text - The string to surround. @param prefix - The prefix to add. @param suffix - The suffix to add. @example surround('https://', 'usemods', '.com') @returns https://usemods.com +**Returns:** https://usemods.com + +### surround + +Adds a prefix and suffix to a string if it doesn't already start and end with them. ```js [js] surround('https://', 'usemods', '.com') ``` -### export function title -Converts a string to title case following the Chicago Manual of Style rules. @reference https://www.chicagomanualofstyle.org/book/ed17/frontmatter/toc.html @example title('the quick brown fox jumps over the lazy dog') @returns The Quick Brown Fox Jumps over the Lazy Dog +**Returns:** https://usemods.com + +### title + +Converts a string to title case following the Chicago Manual of Style rules. ```js [js] title('the quick brown fox jumps over the lazy dog') ``` -### export function splitByWords -Wraps each word in a string with a span tag. @example splitByWords('Hello World. How are you?') @returns Hello world. How are you? +**Returns:** The Quick Brown Fox Jumps over the Lazy Dog + +### splitByWords + +Wraps each word in a string with a span tag. ```js [js] splitByWords('Hello World. How are you?') ``` -### export function list -Creates an array of list items (`
  • `) from an array of strings. @example list(['one', 'two', 'three']) @returns +**Returns:** Hello world. How are you? + +### list + +Creates an array of list items (`
  • `) from an array of strings. ```js [js] list(['one', 'two', 'three']) ``` -### export function shuffle -Shuffles an array. @example shuffle(['one', 'two', 'three']) @returns ['three', 'one', 'two'] +**Returns:** + +### shuffle + +Shuffles an array. ```js [js] shuffle(['one', 'two', 'three']) ``` -### -Returns unique array values with an optional property to pluck. @param items - The array of items. @param property - The property to pluck (optional). @example unique(['one', 'two', 'three', 'one']) @returns ['one', 'two', 'three'] +**Returns:** ['three', 'one', 'two'] + +Returns unique array values with an optional property to pluck. ```js [js] unique(['one', 'two', 'three', 'one']) ``` -### export function difference -Returns the difference between two arrays. @example difference(['one', 'two', 'three'], ['one', 'two']) @returns ['three'] +**Returns:** ['one', 'two', 'three'] + +### difference + +Returns the difference between two arrays. ```js [js] difference(['one', 'two', 'three'], ['one', 'two']) ``` -### export function first -Returns the first item in an array. @example first(['one', 'two', 'three']) @returns one +**Returns:** ['three'] + +### first + +Returns the first item in an array. ```js [js] first(['one', 'two', 'three']) ``` -### export function last -Returns the last item in an array. @example last(['one', 'two', 'three']) @returns three +**Returns:** one + +### last + +Returns the last item in an array. ```js [js] last(['one', 'two', 'three']) ``` -### export function nth -Returns the nth item in an array. @example nth(['one', 'two', 'three'], 1) @returns two +**Returns:** three + +### nth + +Returns the nth item in an array. ```js [js] nth(['one', 'two', 'three'], 1) ``` -### export function offset -Offset the first item in an array. @example offset(['one', 'two', 'three'], 1) @returns ['two', 'three'] +**Returns:** two + +### offset + +Offset the first item in an array. ```js [js] offset(['one', 'two', 'three'], 1) ``` -### -Groups an array of objects by a property. @example group([{ name: 'one' }, { name: 'two' }, { name: 'one' }], 'name') @returns { one: [{ name: 'one' }, { name: 'one' }], two: [{ name: 'two' }] } +**Returns:** ['two', 'three'] + +Groups an array of objects by a property. ```js [js] group([{ name: 'one' }, { name: 'two' }, { name: 'one' }], 'name') ``` -### export function groupBy -Chunks an array into sections of a specified size. @example chunk(['one', 'two', 'three', 'four', 'five'], 2) @returns [['one', 'two'], ['three', 'four'], ['five']] +**Returns:** { one: [{ name: 'one' }, { name: 'one' }], two: [{ name: 'two' }] } + +### groupBy + +Chunks an array into sections of a specified size. ```js [js] chunk(['one', 'two', 'three', 'four', 'five'], 2) ``` -### export function flatten -Flatten an array of arrays. @example flatten([['one', 'two'], ['three', 'four'], ['five']]) @returns ['one', 'two', 'three', 'four', 'five'] +**Returns:** [['one', 'two'], ['three', 'four'], ['five']] + +### flatten + +Flatten an array of arrays. ```js [js] flatten([['one', 'two'], ['three', 'four'], ['five']]) ``` -### export function without -Returns an array with a filtered out property. @example without([{ name: 'one', food: 'apple' }, { name: 'two', food: 'grape' }, { name: 'one', food: 'pear' }], 'name') @returns [{ food: 'apple' }, { food: 'grape' }, { food: 'pear' }] +**Returns:** ['one', 'two', 'three', 'four', 'five'] + +### without + +Returns an array with a filtered out property. ```js [js] without([{ name: 'one', food: 'apple' }, { name: 'two', food: 'grape' }, { name: 'one', food: 'pear' }], 'name') ``` -### export function combine -Combine two or more arrays @example combine(['one', 'two'], ['three', 'four'], ['five']) @returns ['one', 'two', 'three', 'four', 'five'] +**Returns:** [{ food: 'apple' }, { food: 'grape' }, { food: 'pear' }] + +### combine + +Combine two or more arrays ```js [js] combine(['one', 'two'], ['three', 'four'], ['five']) ``` -### -Combine two or more unique arrays @example combineUnique(['one', 'two'], ['three', 'four', 'two'], ['five', 'one']) @returns ['one', 'two', 'three', 'four', 'five'] +**Returns:** ['one', 'two', 'three', 'four', 'five'] + +Combine two or more unique arrays ```js [js] combineUnique(['one', 'two'], ['three', 'four', 'two'], ['five', 'one']) ``` -### -Combine two or more arrays or objects without a property. @example combineWithout({ id: 1, name: 'A' }, { id: 2, name: 'B' }, { id: 3, name: 'C' }, 'id') @returns [1, 2, 3] +**Returns:** ['one', 'two', 'three', 'four', 'five'] + +Combine two or more arrays or objects without a property. ```js [js] combineWithout({ id: 1, name: 'A' }, { id: 2, name: 'B' }, { id: 3, name: 'C' }, 'id') ``` -### export function reverse -Reverse an array. @example reverse(['one', 'two', 'three']) @returns ['three', 'two', 'one'] +**Returns:** [1, 2, 3] + +### reverse + +Reverse an array. ```js [js] reverse(['one', 'two', 'three']) ``` -### -Sort an array by a property. @example sortBy([{ name: 'John', age: 25 },{ name: 'Jane', age: 30 },{ name: 'Jill', age: 20 }], 'age') @returns [{ name: 'Jill', age: 20 },{ name: 'John', age: 25 },{ name: 'Jane', age: 30 }] +**Returns:** ['three', 'two', 'one'] + +Sort an array by a property. ```js [js] sortBy([{ name: 'John', age: 25 },{ name: 'Jane', age: 30 },{ name: 'Jill', age: 20 }], 'age') ``` +**Returns:** [{ name: 'Jill', age: 20 },{ name: 'John', age: 25 },{ name: 'Jane', age: 30 }] + diff --git a/content/2.functions/numbers.md b/content/2.functions/numbers.md index 4da0dfa0..9dc4a1ab 100644 --- a/content/2.functions/numbers.md +++ b/content/2.functions/numbers.md @@ -1,123 +1,166 @@ -# +This file contains functions that are related to numbers. -#### This file contains functions that are related to numbers. +### random -### export function random -Generates a random integer between the specified minimum and maximum values. @example random(1, 10) @returns 5 +Generates a random integer between the specified minimum and maximum values. ```js [js] random(1, 10) ``` -### export function sum -Calculates the sum of an array of numbers. @example sum([1, 2, 3]) @returns 6 +**Returns:** 5 + +### sum + +Calculates the sum of an array of numbers. ```js [js] sum([1, 2, 3]) ``` -### export function mean -Calculates the mean of an array of numbers. @example average([1, 2, 3]) @returns 2 +**Returns:** 6 + +### mean + +Calculates the mean of an array of numbers. ```js [js] average([1, 2, 3]) ``` -### export function average -Calculates the mean of an array of numbers. @example average([1, 2, 3]) @returns 2 +**Returns:** 2 + +### average + +Calculates the mean of an array of numbers. ```js [js] average([1, 2, 3]) ``` -### export function median -Calculates the median of an array of numbers. @example median([1, 2, 3]) @returns 2 +**Returns:** 2 + +### median + +Calculates the median of an array of numbers. ```js [js] median([1, 2, 3]) ``` -### export function mode -Calculates the mode of an array of numbers. @example mode([1, 2, 2, 3]) @returns 2 +**Returns:** 2 + +### mode + +Calculates the mode of an array of numbers. ```js [js] mode([1, 2, 2, 3]) ``` -### export function min -Finds the minimum value in an array of numbers. @example min([1, 2, 3]) @returns 1 +**Returns:** 2 + +### min + +Finds the minimum value in an array of numbers. ```js [js] min([1, 2, 3]) ``` -### export function max -Finds the maximum value in an array of numbers. @example max([1, 2, 3]) @returns 3 +**Returns:** 1 + +### max + +Finds the maximum value in an array of numbers. ```js [js] max([1, 2, 3]) ``` -### export function clamp -Clamps a number between the specified minimum and maximum values. @example clamp(1, 10, 20) @returns 10 +**Returns:** 3 + +### clamp + +Clamps a number between the specified minimum and maximum values. ```js [js] clamp(1, 10, 20) ``` -### -Returns the minimum and maximum values in an array of numbers. @example minMax([1, 2, 3, 4, 5]) @returns [1, 5] +**Returns:** 10 + +Returns the minimum and maximum values in an array of numbers. ```js [js] minMax([1, 2, 3, 4, 5]) ``` -### export function range -Returns the difference between two values, expressed as a positive number. @example range(-10, -20) @returns 10 +**Returns:** [1, 5] + +### range + +Returns the difference between two values, expressed as a positive number. ```js [js] range(-10, -20) ``` -### export function rangeAsPercentage -Returns the difference between two values, as a percentage. @example differenceAsPercentage(10, 20) @returns 100 +**Returns:** 10 + +### rangeAsPercentage + +Returns the difference between two values, as a percentage. ```js [js] differenceAsPercentage(10, 20) ``` -### export function percentage -Returns the percentage of a value, relative to another value. @example percentage(10, 100) @returns 10 +**Returns:** 100 + +### percentage + +Returns the percentage of a value, relative to another value. ```js [js] percentage(10, 100) ``` -### export function standardDeviation -Returns the standard deviation of an array of numbers. @example standardDeviation([1, 2, 3, 20, 120, 2000]) @returns 0.5 +**Returns:** 10 + +### standardDeviation + +Returns the standard deviation of an array of numbers. ```js [js] standardDeviation([1, 2, 3, 20, 120, 2000]) ``` -### export function skewness -Returns the measure of asymmetry of the probability distribution of an array of numbers. The skewness value can be positive, zero, negative, or undefined. @example skewness([1, 2, 3, 20, 120, 2000]) @returns 2.5 +**Returns:** 0.5 + +### skewness + +Returns the measure of asymmetry of the probability distribution of an array of numbers. ```js [js] skewness([1, 2, 3, 20, 120, 2000]) ``` -### -Return the frequency of all values (numbers, string or boolean) in an array as an object @example frequency([1, 3, 2, 3, 3, 3, 'a', 'b', 'c', 'c']) @returns { '1': 1, '2': 1, '3': 4, a: 1, b: 1, c: 2 } +**Returns:** 2.5 + +Return the frequency of all values (numbers, string or boolean) in an array as an object ```js [js] frequency([1, 3, 2, 3, 3, 3, 'a', 'b', 'c', 'c']) ``` -### -Returns the fequency of a property value in an array @example frequencyOfPropert([1, 3, 2, 3, 3, 3, 'a', 'b', 'c', 'c'], 3) @returns 4 +**Returns:** { '1': 1, '2': 1, '3': 4, a: 1, b: 1, c: 2 } + +Returns the fequency of a property value in an array ```js [js] frequencyOfPropert([1, 3, 2, 3, 3, 3, 'a', 'b', 'c', 'c'], 3) ``` +**Returns:** 4 + diff --git a/content/2.functions/validators.md b/content/2.functions/validators.md index 7e780555..e91b77f5 100644 --- a/content/2.functions/validators.md +++ b/content/2.functions/validators.md @@ -1,312 +1,444 @@ # Validators -#### A collection of validators for common data types +A collection of validators for common data types -### export function isEmail -Check if the input is a valid email address. @example isEmail('hello@usemods.com') @returns true +### isEmail + +Check if the input is a valid email address. ```js [js] isEmail('hello@usemods.com') ``` -### export function isNumber -Check if the input is a valid number. @example isNumber('123') @returns true +**Returns:** true + +### isNumber + +Check if the input is a valid number. ```js [js] isNumber('123') ``` -### export function isURL -Check if the input is a valid URL. @example isURL('https://usemods.com') @returns true +**Returns:** true + +### isURL + +Check if the input is a valid URL. ```js [js] isURL('https://usemods.com') ``` -### export function isUUID -Check if the input is a valid UUID. @example isUUID('c9bf9e57-1685-4c89-bafb-ff5af830be8a') @returns true +**Returns:** true + +### isUUID + +Check if the input is a valid UUID. ```js [js] isUUID('c9bf9e57-1685-4c89-bafb-ff5af830be8a') ``` -### export function isJSON -Check if the input is a valid JSON string. @example isJSON('{"hello": "world"}') @returns true +**Returns:** true + +### isJSON + +Check if the input is a valid JSON string. ```js [js] isJSON('{"hello": "world"}') ``` -### export function isHex -Check if the input is a valid hexadecimal color code. @example isHex('#fff') @returns true +**Returns:** true + +### isHex + +Check if the input is a valid hexadecimal color code. ```js [js] isHex('#fff') ``` -### export function isEmpty -Check if the input is an empty string. @example isEmpty('') @returns true +**Returns:** true + +### isEmpty + +Check if the input is an empty string. ```js [js] isEmpty('') ``` -### export function isAlpha -Check if the input contains only alphabetic characters. @example isAlpha('hello') @returns true +**Returns:** true + +### isAlpha + +Check if the input contains only alphabetic characters. ```js [js] isAlpha('hello') ``` -### export function isAlphanumeric -Check if the input contains only alphanumeric characters. @example isAlphanumeric('hello123') @returns true +**Returns:** true + +### isAlphanumeric + +Check if the input contains only alphanumeric characters. ```js [js] isAlphanumeric('hello123') ``` -### export function isArray -Check if the input is an array. @example isArray([1, 2, 3]) @returns true +**Returns:** true + +### isArray + +Check if the input is an array. ```js [js] isArray([1, 2, 3]) ``` -### export function isObject -Check if the input is an object. @example isObject({ hello: 'world' }) @returns true +**Returns:** true + +### isObject + +Check if the input is an object. ```js [js] isObject({ hello: 'world' }) ``` -### export function isBoolean -Check if the input is a boolean value. @example isBoolean(true) @returns true +**Returns:** true + +### isBoolean + +Check if the input is a boolean value. ```js [js] isBoolean(true) ``` -### export function isFunction -Check if the input is a function. @example isFunction(() => {}) @returns true +**Returns:** true + +### isFunction + +Check if the input is a function. ```js [js] isFunction(() => {}) ``` -### export function isUndefined -Check if the input is undefined. @example isUndefined(undefined) @returns true +**Returns:** true + +### isUndefined + +Check if the input is undefined. ```js [js] isUndefined(undefined) ``` -### export function isNull -Check if the input is null. @example isNull(null) @returns true +**Returns:** true + +### isNull + +Check if the input is null. ```js [js] isNull(null) ``` -### export function isDate -Check if the input is a valid Date object. @example isDate(new Date()) @returns true +**Returns:** true + +### isDate + +Check if the input is a valid Date object. ```js [js] isDate(new Date()) ``` -### export function isError -Check if the input is an Error object with a defined message. @example isError(new Error('hello')) @returns true +**Returns:** true + +### isError + +Check if the input is an Error object with a defined message. ```js [js] isError(new Error('hello')) ``` -### export function isTime -Check if the input is a valid time in HH:mm format. @example isTime('12:00') @returns true +**Returns:** true + +### isTime + +Check if the input is a valid time in HH:mm format. ```js [js] isTime('12:00') ``` -### export function isLeapYear -Check if the input year is a leap year. @example isLeapYear(2020) @returns true +**Returns:** true + +### isLeapYear + +Check if the input year is a leap year. ```js [js] isLeapYear(2020) ``` -### export function isPromise -Check if the input is a Promise object. @example isPromise(new Promise(() => {})) @returns true +**Returns:** true + +### isPromise + +Check if the input is a Promise object. ```js [js] isPromise(new Promise(() => {})) ``` -### export function isSet -Check if the input is a Set object. @example isSet(new Set()) @returns true +**Returns:** true + +### isSet + +Check if the input is a Set object. ```js [js] isSet(new Set()) ``` -### export function isMap -Check if the input is a Map object. @example isMap(new Map()) @returns true +**Returns:** true + +### isMap + +Check if the input is a Map object. ```js [js] isMap(new Map()) ``` -### export function isEven -Check if the number is even. @example isEven(2) @returns true +**Returns:** true + +### isEven + +Check if the number is even. ```js [js] isEven(2) ``` -### export function isOdd -Check if the number is odd. @example isOdd(3) @returns true +**Returns:** true + +### isOdd + +Check if the number is odd. ```js [js] isOdd(3) ``` -### export function isPositive -Check if the number is positive. @example isPositive(1) @returns true +**Returns:** true + +### isPositive + +Check if the number is positive. ```js [js] isPositive(1) ``` -### export function isNegative -Check if the number is negative. @example isNegative(-1) @returns true +**Returns:** true + +### isNegative + +Check if the number is negative. ```js [js] isNegative(-1) ``` -### export function isZero -Check if the number is zero. @example isZero(0) @returns true +**Returns:** true + +### isZero + +Check if the number is zero. ```js [js] isZero(0) ``` -### export function isPrime -Check if the number is a prime number. @example isPrime(7) @returns true +**Returns:** true + +### isPrime + +Check if the number is a prime number. ```js [js] isPrime(7) ``` -### export function isOptimusPrime -Check if the string is equal to "Optimus Prime". @example isOptimusPrime('Optimus Prime') @returns true +**Returns:** true + +### isOptimusPrime + +Check if the string is equal to "Optimus Prime". ```js [js] isOptimusPrime('Optimus Prime') ``` -### export function isPalindrome -Check if the string is a palindrome. @example isPalindrome('racecar') @returns true +**Returns:** true + +### isPalindrome + +Check if the string is a palindrome. ```js [js] isPalindrome('racecar') ``` -### export function isInteger -Check if the number is an integer. @example isInteger(1) @returns true +**Returns:** true + +### isInteger + +Check if the number is an integer. ```js [js] isInteger(1) ``` -### export function isFloat -Check if the number is a float. @example isFloat(1.5) @returns true +**Returns:** true + +### isFloat + +Check if the number is a float. ```js [js] isFloat(1.5) ``` -### export function isBetween -Check if the number is between the specified range. @example isBetween(5, 1, 10) @returns true +**Returns:** true + +### isBetween + +Check if the number is between the specified range. ```js [js] isBetween(5, 1, 10) ``` -### export function isDivisibleBy -Check if the number is divisible by the specified number. @example isDivisibleBy(10, 2) @returns true +**Returns:** true + +### isDivisibleBy + +Check if the number is divisible by the specified number. ```js [js] isDivisibleBy(10, 2) ``` -### export function isCreditCardNumber -Check if the input is a valid credit card number. @example isCreditCardNumber('4242424242424242') @returns true +**Returns:** true + +### isCreditCardNumber + +Check if the input is a valid credit card number. ```js [js] isCreditCardNumber('4242424242424242') ``` -### export function isIPAddress -Check if the input is a valid IP address. @example isIPAddress('127.0.0.0') @returns true +**Returns:** true + +### isIPAddress + +Check if the input is a valid IP address. ```js [js] isIPAddress('127.0.0.0') ``` -### export function isMACAddress -Check if the input is a valid MAC address. @example isMACAddress('00:00:00:00:00:00') @returns true +**Returns:** true + +### isMACAddress + +Check if the input is a valid MAC address. ```js [js] isMACAddress('00:00:00:00:00:00') ``` -### export function isLatLng -Check if the input is a valid latitude-longitude coordinate in the format lat,lng or lat,lng. @example isLatLng('40.741895,-73.989308') @returns true +**Returns:** true + +### isLatLng + +Check if the input is a valid latitude-longitude coordinate in the format lat,lng or lat,lng. ```js [js] isLatLng('40.741895,-73.989308') ``` -### export function isLatitude -Check if the input is a valid latitude coordinate. @example isLatitude('40.741895') @returns true +**Returns:** true + +### isLatitude + +Check if the input is a valid latitude coordinate. ```js [js] isLatitude('40.741895') ``` -### export function isLongitude -Check if the input is a valid longitude coordinate. @example isLongitude('-73.989308') @returns true +**Returns:** true + +### isLongitude + +Check if the input is a valid longitude coordinate. ```js [js] isLongitude('-73.989308') ``` -### export function isPort -Check if the input is a valid port number. @example isPort(3000) @returns true +**Returns:** true + +### isPort + +Check if the input is a valid port number. ```js [js] isPort(3000) ``` -### export function isPresent -Checks if a property and value pair exists in an object. @example hasPropertyValue({ hello: 'world' }, 'hello', 'world') @returns true +**Returns:** true + +### isPresent + +Checks if a property and value pair exists in an object. ```js [js] hasPropertyValue({ hello: 'world' }, 'hello', 'world') ``` -### export function hasProperties -Check if a property exists in an object without checking its value. @example hasProperties({ hello: 'world' }, ['hello', 'world']) @returns true +**Returns:** true + +### hasProperties + +Check if a property exists in an object without checking its value. ```js [js] hasProperties({ hello: 'world' }, ['hello', 'world']) ``` -### export function hasKeys -Check if an array of key exists in an object @example hasKeys({ hello: 'world' }, ['hello', 'world',]) @returns true +**Returns:** true + +### hasKeys + +Check if an array of key exists in an object ```js [js] hasKeys({ hello: 'world' }, ['hello', 'world',]) ``` +**Returns:** true + diff --git a/docs.ts b/docs.ts index eef268e9..ed5bfc4b 100644 --- a/docs.ts +++ b/docs.ts @@ -12,17 +12,18 @@ const subtitlePattern = /\/\/ (.+?)\/\/ <\/subtitle>/gs async function processFiles() { try { const tsFiles = (await readdir(directoryPath)).filter((file) => extname(file) === '.ts') + let combinedTsFile = '' + // Generate markdown files for (const tsFile of tsFiles) { const tsContent = await readFile(resolve(directoryPath, tsFile), 'utf-8') combinedTsFile += tsContent + '\n' - - const markdownContent = generateMarkdown(tsContent) - await writeFile(join(contentDirectory, `${basename(tsFile, '.ts')}.md`), markdownContent) + await writeFile(join(contentDirectory, `${basename(tsFile, '.ts')}.md`), generateMarkdown(tsContent)) console.log('Markdown documentation generated for:', tsFile) } + // Write combined file await writeFile(join(outputDirectory, 'mods.ts'), combinedTsFile) } catch (error) { console.error('Error processing files:', error) @@ -31,27 +32,33 @@ async function processFiles() { function generateMarkdown(tsContent: string): string { const metadata = Object.fromEntries([...tsContent.matchAll(metadataPattern)].map((m) => [m[1], m[2]])) - let markdownContent = `# ${metadata.title || ''}\n\n#### ${metadata.description || ''}\n\n` + let markdownContent = '' + + if (metadata.title) markdownContent += `# ${metadata.title}\n\n` + if (metadata.description) markdownContent += `${metadata.description}\n\n` const matches = [...tsContent.matchAll(functionPattern), ...tsContent.matchAll(subtitlePattern)] - matches.sort((a, b) => a.index! - b.index!) for (const match of matches) { if (match[0].startsWith('// ')) { markdownContent += `## ${match[1].trim()}\n\n` } else { - const [functionName] = /export function\s+([a-zA-Z0-9_]+)/.exec(match[0]) || [''] + const name = (match[0].match(/export\s+function\s+([a-zA-Z0-9_]+)\s*\(/) || [])[1] || '' + const jsDoc = /\/\*\*([\s\S]*?)\*\//.exec(match[0])?.[1].trim() || '' const description = jsDoc .split('\n') .map((line) => line.trim().replace(/\/?\*+/g, '')) - .filter((line) => !line.startsWith('@')) + .slice(0, 1) .join(' ') .trim() const example = (jsDoc.match(/@example\s+([^\r\n]*)/) || [])[1] || '' + const returns = (jsDoc.match(/@returns?\s+([^\r\n]*)/) || [])[1] || '' - markdownContent += `### ${functionName}\n${description}\n\n` + if (name) markdownContent += `### ${name}\n\n` + if (description) markdownContent += `${description}\n\n` if (example) markdownContent += '```js [js]\n' + example + '\n```\n\n' + if (returns) markdownContent += `**Returns:** ${returns}\n\n` } } diff --git a/utils/detections.ts b/utils/detections.ts index a7ccc3de..2a2620c0 100644 --- a/utils/detections.ts +++ b/utils/detections.ts @@ -256,16 +256,16 @@ export function detectPerformance(): Promise { }) } -/** - * Detect the current storage status of the user (Local Storage, Session Storage) - * @example detectStorage() - */ -export function detectStorage(): { localStorage: number; sessionStorage: number } { - return { - localStorage: JSON.stringify(localStorage).length, - sessionStorage: JSON.stringify(sessionStorage).length - } -} +// /** +// * Detect the current storage status of the user (Local Storage, Session Storage) +// * @example detectStorage() +// */ +// export function detectStorage(): { localStorage: number; sessionStorage: number } { +// return { +// localStorage: JSON.stringify(localStorage).length, +// sessionStorage: JSON.stringify(sessionStorage).length +// } +// } /** * Returns a cookie value by name @@ -281,7 +281,7 @@ export function detectCookie(name: string) { * Returns a local storage value by name and parses it into JSON * @example detectLocalStorage('name') */ -export function detectLocalStorage(name: string) { +export function detectLocalStorage(name: string): any { const item = localStorage.getItem(name) if (item) return JSON.parse(item) } @@ -329,7 +329,7 @@ export function detectURLSearchParameters() { * Returns the current URL * @example detectURL() */ -export function detectURL() { +export function detectURL(): string { return window.location.href } @@ -337,7 +337,7 @@ export function detectURL() { * Returns the current domain * @example detectDomain() */ -export function detectDomain() { +export function detectDomain(): string { return window.location.hostname } @@ -345,7 +345,7 @@ export function detectDomain() { * Returns the current IP address * @example detectIP() */ -export function detectIP() { +export function detectIP(): string { return window.location.host } @@ -353,7 +353,7 @@ export function detectIP() { * Returns the current port * @example detectPort() */ -export function detectPort() { +export function detectPort(): string { return window.location.port } @@ -379,11 +379,7 @@ export function detectReferrer() { */ export function detectCachedData(key?: string): PerformanceEntry[] { const cachedData = window.performance.getEntriesByType('resource') - - if (key) { - return cachedData.filter((data) => data.name.includes(key)) - } - + if (key) return cachedData.filter((data) => data.name.includes(key)) return cachedData } @@ -391,9 +387,9 @@ export function detectCachedData(key?: string): PerformanceEntry[] { /** * Detects if the element is currently in the viewport - * @example isInViewport(element) + * @example detectInViewport(element) */ -export function isInViewport(element: HTMLElement) { +export function detectInViewport(element: HTMLElement) { const rect = element.getBoundingClientRect() return ( rect.top >= 0 && @@ -405,9 +401,9 @@ export function isInViewport(element: HTMLElement) { /** * Detects if the element is currently in the container via ID - * @example isInContainer(element, 'container') + * @example detectInContainer(element, 'container') */ -export function isInContainer(element: HTMLElement, id: string) { +export function detectInContainer(element: HTMLElement, id: string) { const rect = element.getBoundingClientRect() const container = document.getElementById(id) if (!container) return false @@ -417,32 +413,32 @@ export function isInContainer(element: HTMLElement, id: string) { /** * Detects if the element is overflowing vertically - * @example isOverflowingY(element) + * @example detectOverflowingY(element) */ -export function isOverflowingY(element: HTMLElement) { +export function detectOverflowingY(element: HTMLElement) { return element.scrollWidth > element.clientWidth || element.scrollHeight > element.clientHeight } /** * Detects if the element is overflowing horizontally - * @example isOverflowingX(element) + * @example detectOverflowingX(element) */ -export function isOverflowingX(element: HTMLElement) { +export function detectOverflowingX(element: HTMLElement) { return element.scrollWidth > element.clientWidth } /** * Detects if the element is scrollable (overflowing vertically or horizontally) - * @example isScrollable(element) + * @example detectScrollable() */ -export function isScrollable(element: HTMLElement) { - return isOverflowingY(element) || isOverflowingX(element) +export function detectScrollable(element: HTMLElement) { + return detectOverflowingY(element) || detectOverflowingX(element) } /** * Detects if the elements is an HTML element - * @example isElement(element) + * @example detectElement() */ -export function isElement(element: HTMLElement) { +export function detectElement(element: HTMLElement) { return element instanceof HTMLElement }