### Install @julianobazzi/utils Source: https://github.com/julianobazzi/utils/blob/master/README.md Install the package using npm. This command adds the utility library to your project dependencies. ```bash npm install @julianobazzi/utils ``` -------------------------------- ### Explicit Configuration Example Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/configuration.md Demonstrates explicit inline configuration for `formatCurrency` using a fallback value. This contrasts with implicit configuration which is not used by the library. ```typescript // EXPLICIT - Clear what configuration is being used formatCurrency(price, 100, { fallback: "—" }); // NOT IMPLICIT - No environment variables or globals // formatCurrency(price); // Just uses defaults ``` -------------------------------- ### Tree-shaking Example Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/README.md Demonstrates how only the imported function is bundled by modern bundlers. Ensure your bundler is configured for tree-shaking. ```typescript // Only formatDate is bundled import { formatDate } from "@julianobazzi/utils"; ``` -------------------------------- ### Importing and Using formatDate with Options Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/DOCUMENTATION_INDEX.md Demonstrates how to import the formatDate function and its options type, then use it with custom options. Ensure you have the library installed. ```typescript import { formatDate, type FormatDateOptions } from "@julianobazzi/utils"; const opts: FormatDateOptions = { simplified: false }; const result: string = formatDate("2024-01-02", opts); ``` -------------------------------- ### Import Statements Source: https://github.com/julianobazzi/utils/blob/master/llms.txt Examples of how to import utility functions from the @julianobazzi/utils library using both ESM/TypeScript and CommonJS module systems. ```typescript // ESM / TypeScript import { formatCPF, isValidEmail, truncate } from "@julianobazzi/utils"; // CommonJS const { formatCPF, isValidEmail } = require("@julianobazzi/utils"); ``` -------------------------------- ### Tree-shaking Example: Importing Specific Function Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/DOCUMENTATION_INDEX.md Illustrates the tree-shakeable nature of the library by importing only the formatDate function. Avoid importing the entire library with `import * as utils` to keep bundle sizes small. ```typescript // Only formatDate in bundle import { formatDate } from "@julianobazzi/utils"; // Don't do this (imports all 90+ functions) import * as utils from "@julianobazzi/utils"; ``` -------------------------------- ### Example Usage of getLabelById Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/api-object.md Demonstrates how to use the getLabelById function with different scenarios, including retrieving a name, an email, and handling a fallback value for a non-existent ID. ```typescript import { getLabelById } from "@julianobazzi/utils"; const users = [ { id: 1, name: "John", email: "john@example.com" }, { id: 2, name: "Jane", email: "jane@example.com" } ]; getLabelById(users, "1"); // "John" getLabelById(users, "1", "email"); // "john@example.com" getLabelById(users, "99", "name", "Unknown"); // "Unknown" ``` -------------------------------- ### Export Structure Example Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/README.md Shows the ESM export structure for individual functions and the package's main entry points. All functions are exported flat from the package root. ```typescript // ESM (modern) export { formatDate } from "./formatting/formatDate.js"; export { isValidCPF } from "./validation/isValidCPF.js"; // ... etc for all 90+ functions ``` ```json // Available in package.json { "main": "./dist/index.cjs", // CommonJS "module": "./dist/index.js", // ESM "types": "./dist/index.d.ts" // TypeScript definitions } ``` -------------------------------- ### Get Image Dimensions Source: https://github.com/julianobazzi/utils/blob/master/README.md Retrieves the dimensions and extension of an image file. Returns a Promise with width, height, and extension. ```javascript getImageDimensions(file) ``` -------------------------------- ### maskSecret Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/api-formatting.md Partially masks a secret string, keeping a specified number of characters visible at the start and end. ```APIDOC ## maskSecret Partially masks a secret, keeping the ends visible. ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | value | string \| null | no | — | Secret string to mask | | options | MaskSecretOptions | no | `{}` | Configuration object | | options.visibleStart | number | no | `5` | Number of characters visible at the start | | options.visibleEnd | number | no | `5` | Number of characters visible at the end | | options.mask | string | no | `"••••••"` | Mask characters to insert in the middle | ### Return Value Returns a partially masked string (`string`). ### Example ```typescript import { maskSecret } from "@julianobazzi/utils"; maskSecret("$2y$10$abcdefghijklmnop"); // "$2y$1••••••mnop" maskSecret("12345678", { visibleStart: 2, visibleEnd: 2 }); // "12••••78" ``` ``` -------------------------------- ### Development Build Source: https://github.com/julianobazzi/utils/blob/master/README.md Builds the project in watch mode for development. ```bash npm run dev ``` -------------------------------- ### Build Project Source: https://github.com/julianobazzi/utils/blob/master/README.md Bundles the project into `dist/` using tsup, generating ESM, CJS, and .d.ts files. ```bash npm run build ``` -------------------------------- ### Basic Usage of @julianobazzi/utils Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/README.md Demonstrates importing and using various utility functions for formatting, validation, generation, and object operations. Ensure necessary functions are imported before use. ```typescript import { formatDate, formatCurrency, isValidCPF, generateCPF, contains, omitFields } from "@julianobazzi/utils"; // Formatting formatDate("2024-01-02"); // "02/01/24" formatCurrency(1990); // "R$ 19,90" // Validation isValidCPF("529.982.247-25"); // true isValidEmail("user@example.com"); // true // Generation (for tests) const cpf = generateCPF({ formatted: true }); // "529.982.247-25" const phone = generatePhone({ mobile: true }); // "11987654321" // Object operations contains("a", ["a", "b"]); // true omitFields({ a: 1, b: 2 }, ["b"]); // { a: 1 } ``` -------------------------------- ### Get Property Safely Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/api-object.md Safely access a property from an object. Returns null if the object is null or the property does not exist. ```typescript import { getProperty } from "@julianobazzi/utils"; const user = { id: 1, name: "John" }; getProperty(user, "name"); // "John" getProperty(user, "id"); // 1 getProperty(null, "name"); // null ``` -------------------------------- ### Importing Utilities from @julianobazzi/utils Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/README.md Shows the correct way to import individual functions from the package root. All functions are exported flat from the package. ```typescript // ✓ These work import { formatDate } from "@julianobazzi/utils"; import { isValidCPF } from "@julianobazzi/utils"; // Functions are also grouped internally by module: // src/formatting/* — 45+ formatting functions // src/validation/* — 22 validation functions // src/number/* — 7 number utilities // src/object/* — 7 object utilities // src/parse/* — 4 parse utilities // src/generate/* — 10 generator functions // src/browser/* — 4 browser utilities // src/mask/* — 8 mask constants // src/transform/* — 2 form transforms ``` -------------------------------- ### MaskSecretOptions Interface Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/types.md Defines options for the maskSecret function. Control the number of visible characters at the start and end, and the mask character. ```typescript interface MaskSecretOptions { visibleStart?: number; visibleEnd?: number; mask?: string; } ``` -------------------------------- ### Importing Utilities (ESM/TypeScript and CommonJS) Source: https://github.com/julianobazzi/utils/blob/master/llms.txt Demonstrates how to import functions from the library using both ECMAScript Modules (ESM) and CommonJS module systems. ```typescript // ESM / TypeScript import { formatCPF, isValidEmail, truncate } from "@julianobazzi/utils"; ``` ```javascript // CommonJS const { formatCPF, isValidEmail } = require("@julianobazzi/utils"); ``` -------------------------------- ### Get Last Character of a String Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/api-formatting.md Returns the last character of a given string. Returns an empty string if the input is null, undefined, or empty. ```typescript import { getLastCharacter } from "@julianobazzi/utils"; getLastCharacter("Hello"); // "o" getLastCharacter(""); // "" ``` -------------------------------- ### Run Tests Source: https://github.com/julianobazzi/utils/blob/master/README.md Executes all tests once using Vitest. ```bash npm run test ``` -------------------------------- ### Get Image Dimensions Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/api-browser.md Reads an image File's pixel dimensions and file extension. Useful for validating image sizes or displaying metadata before uploading. ```typescript import { getImageDimensions } from "@julianobazzi/utils"; const input = document.getElementById("fileInput") as HTMLInputElement; input.addEventListener("change", async (e) => { const file = (e.target as HTMLInputElement).files?.[0]; if (file) { try { const { width, height, extension } = await getImageDimensions(file); console.log(`Image: ${width}x${height} (${extension})`); } catch (error) { console.error("Failed to read dimensions:", error); } } }); ``` -------------------------------- ### Mask Secret String Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/api-formatting.md Partially masks a secret string, keeping a specified number of characters visible at the start and end. Uses a default mask of '••••••' if not specified. ```typescript import { maskSecret } from "@julianobazzi/utils"; maskSecret("$2y$10$abcdefghijklmnop"); // "$2y$1••••••mnop" maskSecret("12345678", { visibleStart: 2, visibleEnd: 2 }); // "12••••78" ``` -------------------------------- ### Lint and Format Check Source: https://github.com/julianobazzi/utils/blob/master/README.md Checks code style and formatting using Biome. ```bash npm run lint ``` -------------------------------- ### Extract ID from an Option Object Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/api-object.md Use this function to get the `id` property from a single object. It handles cases where the object or its `id` property is missing, returning `null`. ```typescript import { getOptionId } from "@julianobazzi/utils"; const user = { id: 123, name: "John" }; getOptionId(user); // 123 getOptionId({ id: "abc-def", name: "Item" }); // "abc-def" getOptionId(null); // null getOptionId({ name: "No ID" }); // null ``` -------------------------------- ### Apply Lint and Format Fixes Source: https://github.com/julianobazzi/utils/blob/master/README.md Automatically applies safe fixes for linting and formatting issues using Biome. ```bash npm run lint:fix ``` -------------------------------- ### Text Formatting and Casing Options Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/configuration.md Apply various text transformations including casing, abbreviation, truncation, and masking. Options like `casing`, `visibleStart`, and `visibleEnd` customize the output. ```typescript // Text formatting abbreviateName("John Smith", { casing: "titlecase" }); applyCasing("text", "uppercase"); truncate("Long text", 20); maskSecret("secret123", { visibleStart: 2, visibleEnd: 2 }); ``` -------------------------------- ### Handle Image Dimension Errors Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/errors.md Catch errors when attempting to get image dimensions. This covers FileReader errors, image decode issues, and invalid image files. ```typescript import { getImageDimensions } from "@julianobazzi/utils"; try { const { width, height } = await getImageDimensions(file); console.log(`Image dimensions: ${width}x${height}`); } catch (error) { console.error("Unable to read image:", error.message); } ``` -------------------------------- ### Validation Functions: Check Boolean Return Values Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/errors.md Validation functions typically return a boolean. Check the boolean return value to determine if validation failed. This example checks the result of `isValidCPF`. ```typescript if (!isValidCPF(input)) { setError("Invalid CPF"); } ``` -------------------------------- ### Run Tests with Coverage Source: https://github.com/julianobazzi/utils/blob/master/README.md Executes tests and generates a coverage report, enforcing defined thresholds. ```bash npm run test:coverage ``` -------------------------------- ### Browser Functions: Wrap in Try-Catch Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/errors.md Asynchronous browser functions that might fail should be wrapped in a try-catch block. This ensures that errors during operations like loading images are handled gracefully. The example demonstrates catching errors from `loadImageFromBlob`. ```typescript try { const img = await loadImageFromBlob(blob); } catch (error) { setError("Failed to load image"); } ``` -------------------------------- ### Formatting Options for Custom Output Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/README.md Most formatting functions accept an optional configuration object to customize output, such as date format, casing, or sorting. ```typescript formatDate(date, { simplified: false }); formatPhone(phone, { fallback: "—" }); abbreviateName(name, { casing: "uppercase" }); joinByKey(items, "name", { sort: "desc", divider: ", " }); ``` -------------------------------- ### Parse/Resolve Functions: Wrap Async Operations in Try-Catch Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/errors.md Asynchronous parse or resolve functions that interact with external resources or perform complex operations should be enclosed in try-catch blocks. This handles potential errors during data fetching or resolution. The example shows error handling for `resolveIdsToObjects`. ```typescript try { const data = await resolveIdsToObjects(ids, resolver); } catch (error) { setError("Failed to load data"); } ``` -------------------------------- ### Apply Casing with LetterCasing Type Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/types.md Demonstrates how to use the LetterCasing type with the applyCasing function to format text. Ensure LetterCasing and applyCasing are imported. ```typescript import { applyCasing, type LetterCasing } from "@julianobazzi/utils"; const casing: LetterCasing = "titlecase"; applyCasing("joão silva", casing); // "João Silva" ``` -------------------------------- ### Tree-Shaking for Bundle Size Reduction Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/configuration.md Minimize bundle size by importing only the specific functions you need from the library. Avoid importing the entire library using `import * as utils`. ```typescript // Import only what you use import { formatDate, formatCurrency } from "@julianobazzi/utils"; // Don't do this (imports everything) import * as utils from "@julianobazzi/utils"; ``` -------------------------------- ### Format Address String Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/api-formatting.md Builds a single-line address string from address components. Use this when you need to display a complete address in a compact format. Requires an Address object. ```typescript import { formatAddress } from "@julianobazzi/utils"; formatAddress({ street: "Rua A", number: "123", city: "São Paulo", state: "SP" }); // "Rua A, 123 - São Paulo - SP" ``` -------------------------------- ### Link and URL Building Source: https://github.com/julianobazzi/utils/blob/master/README.md Functions for constructing URLs for various online services. ```APIDOC ## buildWhatsAppUrl ### Description Builds a `wa.me` URL for WhatsApp, optionally including a pre-filled message. ### Signature `buildWhatsAppUrl(phone?, message?, { countryCode = '55', fallback? })` ### Parameters - **phone** (string, optional) - The phone number. - **message** (string, optional) - The pre-filled message. - **countryCode** (string, optional) - The country code (e.g., '55' for Brazil). Set to `null` to omit. - **fallback** (string, optional) - Value to return if formatting fails. ``` ```APIDOC ## buildPhoneUrl ### Description Builds a `tel:` link for initiating a phone call. ### Signature `buildPhoneUrl(phone?, { countryCode = '55', fallback? })` ### Parameters - **phone** (string, optional) - The phone number. - **countryCode** (string, optional) - The country code (e.g., '55' for Brazil). Set to `null` to omit the `+` prefix. - **fallback** (string, optional) - Value to return if formatting fails. ``` ```APIDOC ## buildEmailUrl ### Description Builds a `mailto:` link for sending an email, with optional subject and body. ### Signature `buildEmailUrl(email?, { subject?, body?, fallback? })` ### Parameters - **email** (string, optional) - The recipient's email address. - **subject** (string, optional) - The email subject. - **body** (string, optional) - The email body. - **fallback** (string, optional) - Value to return if formatting fails. ``` ```APIDOC ## buildInstagramUrl ### Description Builds an Instagram profile URL. ### Signature `buildInstagramUrl(username?, { fallback? })` ### Parameters - **username** (string, optional) - The Instagram username (leading `@` is stripped). - **fallback** (string, optional) - Value to return if formatting fails. ``` ```APIDOC ## buildFacebookUrl ### Description Builds a Facebook profile or page URL. ### Signature `buildFacebookUrl(username?, { fallback? })` ### Parameters - **username** (string, optional) - The Facebook username or ID (leading `@` is stripped). - **fallback** (string, optional) - Value to return if formatting fails. ``` ```APIDOC ## buildLinkedInUrl ### Description Builds a LinkedIn profile or company URL. ### Signature `buildLinkedInUrl(handle?, { type = 'profile', fallback? })` ### Parameters - **handle** (string, optional) - The LinkedIn profile or company handle. - **type** (string, optional) - The type of URL to build: `'profile'` or `'company'`. Defaults to `'profile'`. - **fallback** (string, optional) - Value to return if formatting fails. ``` -------------------------------- ### Numeric and Currency Formatting Source: https://github.com/julianobazzi/utils/blob/master/README.md Functions for formatting numbers, currencies, and percentages. ```APIDOC ## formatCurrency ### Description Formats a numeric value as Brazilian Real (BRL) currency (e.g., `R$ 19,90`). ### Signature `formatCurrency(value?, divisor = 100, { fallback? })` ### Parameters - **value** (number, optional) - **divisor** (number, optional) - The divisor to use for conversion (defaults to 100). - **fallback** (string, optional) - Value to return if formatting fails. ``` ```APIDOC ## formatCompactNumber ### Description Formats a number using compact notation (e.g., `1.5M`, `100K`). ### Signature `formatCompactNumber(value?, { decimals?, fallback? })` ### Parameters - **value** (number, optional) - **decimals** (number, optional) - The number of decimal places to show. - **fallback** (string, optional) - Value to return if formatting fails. ``` ```APIDOC ## formatPercentage ### Description Formats a numeric value as a percentage (e.g., `12,50%`). ### Signature `formatPercentage(value?, round = false, { fallback? })` ### Parameters - **value** (number, optional) - **round** (boolean, optional) - If true, rounds the percentage value. Defaults to false. - **fallback** (string, optional) - Value to return if formatting fails. ``` ```APIDOC ## numberToWords ### Description Converts an integer into its Portuguese (Brazil) word representation up to trillions (e.g., `mil duzentos e trinta e quatro`). ### Signature `numberToWords(value?, { fallback? })` ### Parameters - **value** (number, optional) - **fallback** (string, optional) - Value to return if formatting fails. ``` ```APIDOC ## currencyToWords ### Description Converts a BRL currency amount into its Portuguese (Brazil) word representation (e.g., `dezenove reais e noventa centavos`). ### Signature `currencyToWords(value?, divisor = 100, { fallback? })` ### Parameters - **value** (number, optional) - **divisor** (number, optional) - The divisor to use for conversion (defaults to 100). - **fallback** (string, optional) - Value to return if formatting fails. ``` -------------------------------- ### Validate CPF and Email with @julianobazzi/utils Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/errors.md Demonstrates how to use `isValidCPF` and `isValidEmail` functions. These validation functions return `false` for invalid inputs instead of throwing errors. Always check the return value. ```typescript import { isValidCPF, isValidEmail } from "@julianobazzi/utils"; const cpf = "529.982.247-25"; if (!isValidCPF(cpf)) { console.error("Invalid CPF provided"); } const email = "user@example.com"; if (isValidEmail(email)) { // Email is valid } ``` -------------------------------- ### FormatAddressOptions Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/types.md Options for the formatAddress function. Allows specifying a fallback value. ```APIDOC ## FormatAddressOptions ### Description Options for the `formatAddress` function. Allows specifying a fallback value when the address is invalid or missing. ### Fields #### Optional Fields - **fallback** (string) - Optional - Default: `""` - Value returned when address is invalid or missing. ``` -------------------------------- ### FormatCityAndStateOptions Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/types.md Options for the formatCityAndState function. Allows customization of separator, fallback, and casing. ```APIDOC ## FormatCityAndStateOptions ### Description Options for the `formatCityAndState` function. Allows customization of the separator between city and state, a fallback value, and letter casing. ### Fields #### Optional Fields - **separator** (string) - Optional - Default: `" - "` - Separator between city and state. - **fallback** (string) - Optional - Default: `""` - Value returned when both inputs are missing. - **casing** (LetterCasing) - Optional - Specifies the letter casing transformation. ``` -------------------------------- ### joinByKey Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/api-formatting.md Joins a single property of each object in an array into a string, with options for dividers and sorting. ```APIDOC ## joinByKey Joins a single property of each object in an array into a string. ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | values | T[] | yes | — | Array of objects | | key | K | yes | — | Property name to extract from each object | | dividerOrOptions | string \| JoinByKeyOptions | no | `" \|" ` | Divider string or options object | ### Return Value Returns a joined string (`string`). Skips falsy entries and returns empty string for missing arrays. ### Example ```typescript import { joinByKey } from "@julianobazzi/utils"; joinByKey([{ name: "a" }, { name: "b" }], "name"); // "a | b" joinByKey([{ id: 1 }, { id: 2 }], "id", ", "); // "1, 2" joinByKey([{ name: "b" }, { name: "a" }], "name", { sort: true }); // "a | b" joinByKey([{ id: 1 }, { id: 2 }], "id", { sort: "desc", divider: ", " }); // "2, 1" ``` ``` -------------------------------- ### formatAddress Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/api-formatting.md Builds a single-line address string from address components. ```APIDOC ## formatAddress ### Description Builds a single-line address string from address components. ### Method ```typescript function formatAddress(address: Address, options?: FormatAddressOptions): string ``` ### Parameters #### Path Parameters - **address** (Address) - Required - Address object with street, number, complement, city, state fields - **options** (FormatAddressOptions) - Optional - Configuration object - **fallback** (string) - Optional - Value returned when address is invalid/missing ### Return Value Returns a formatted address string (`string`). ### Example ```typescript import { formatAddress } from "@julianobazzi/utils"; formatAddress({ street: "Rua A", number: "123", city: "São Paulo", state: "SP" }); // "Rua A, 123 - São Paulo - SP" ``` ``` -------------------------------- ### Number Formatting and Rounding Options Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/configuration.md Format numbers into compact representations or round them to a specified precision. Use `decimals` for compact formatting and the second argument for precision rounding. ```typescript // Number formatting formatCompactNumber(1500000, { decimals: 2 }); // "1.50M" precisionRound(1.234567, 2); // 1.23 ``` -------------------------------- ### Age and Date Text Formatting Source: https://github.com/julianobazzi/utils/blob/master/README.md Functions for calculating and formatting age, and formatting dates with weekdays. ```APIDOC ## getAge ### Description Calculates the age in full years based on a birth date. Returns `0` for invalid or future dates. ### Signature `getAge(birthDate?)` ### Parameters - **birthDate** (Date | string | number, optional) - The date of birth. ``` ```APIDOC ## formatAge ### Description Formats the age into Portuguese (Brazil) text (e.g., `"36 anos"` / `"1 ano"`). ### Signature `formatAge(birthDate?, { fallback? })` ### Parameters - **birthDate** (Date | string | number, optional) - **fallback** (string, optional) - Value to return if formatting fails. ``` ```APIDOC ## formatLongDate ### Description Formats a date into a long, human-readable string in Portuguese (Brazil) (e.g., `1º de julho de 2026`). ### Signature `formatLongDate(value?, { fallback?, casing? })` ### Parameters - **value** (Date | string | number, optional) - **fallback** (string, optional) - Value to return if formatting fails. - **casing** (string, optional) - Desired casing for the output. ``` ```APIDOC ## formatWeekDay ### Description Formats a date to include the date and the abbreviated weekday (e.g., `15/6 - Sáb`). ### Signature `formatWeekDay(date?, { fallback?, casing?, dateFormat? })` ### Parameters - **date** (Date | string | number, optional) - **fallback** (string, optional) - Value to return if formatting fails. - **casing** (string, optional) - Desired casing for the output. - **dateFormat** (string, optional) - The format for the date part. Defaults to `D/M`. ``` -------------------------------- ### Run Tests in Watch Mode Source: https://github.com/julianobazzi/utils/blob/master/README.md Runs tests continuously in watch mode using Vitest. ```bash npm run test:watch ``` -------------------------------- ### FormatBytesOptions Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/types.md Options for the formatBytes function. Allows specifying optional casing transformation. ```APIDOC ## FormatBytesOptions ### Description Options for the `formatBytes` function. Allows specifying optional casing transformation. ### Fields #### casing - **casing** (LetterCasing) - Optional - Optional casing transformation. ``` -------------------------------- ### currencyToWords Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/api-formatting.md Converts a BRL amount to Portuguese words, mirroring the behavior of formatCurrency. It handles numeric values, optional divisors, and configuration for fallback. ```APIDOC ## currencyToWords ### Description Converts a BRL amount to Portuguese words (mirrors `formatCurrency`). ### Method ```typescript function currencyToWords(value?: number | null, divisor?: number, options?: CurrencyToWordsOptions): string ``` ### Parameters #### Parameters - **value** (number | null) - Optional - Description: Numeric value - **divisor** (number) - Optional - Default: 100 - Description: Divides the value first - **options** (CurrencyToWordsOptions) - Optional - Description: Configuration object - **options.fallback** (string) - Optional - Default: "" - Description: Value returned when input is zero/missing ### Return Value Returns a BRL amount spelled in Portuguese (`string`). ### Example ```typescript import { currencyToWords } from "@julianobazzi/utils"; currencyToWords(1990); // "dezenove reais e noventa centavos" currencyToWords(100, 1); // "cem reais" ``` ``` -------------------------------- ### Import and Use Utility Functions (CommonJS) Source: https://github.com/julianobazzi/utils/blob/master/README.md Import utility functions like onlyNumbers using require for CommonJS environments. This allows for compatibility with older Node.js projects or build systems. ```js const { onlyNumbers } = require("@julianobazzi/utils"); onlyNumbers("(11) 98765-4321"); // "11987654321" ``` -------------------------------- ### FormatAddressOptions Interface Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/types.md Options for the formatAddress function. Use to provide a fallback string when the address is invalid or missing. ```typescript interface FormatAddressOptions { fallback?: string; } ``` -------------------------------- ### CurrencyToWordsOptions Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/types.md Options for the `currencyToWords` function. Allows specifying a fallback value. ```APIDOC ## CurrencyToWordsOptions ### Description Options for the `currencyToWords` function. Allows specifying a fallback value. ### Fields #### fallback (string) - Optional - Value returned when input is zero or missing ``` -------------------------------- ### Date and Time Formatting Options Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/configuration.md Control date and time output formats using specific options like `simplified` and `showSeconds`. Ensure correct date/time objects or strings are passed. ```typescript // Date formatting formatDate("2024-01-02", { simplified: false }); // 4-digit year formatDateTime(date, { showSeconds: true }); // Include :ss formatHour(time, { simplified: false }); // Include seconds ``` -------------------------------- ### JoinByKeyOptions Interface Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/types.md Defines options for the joinByKey function. Configure the divider string and whether to sort entries by key before joining. ```typescript interface JoinByKeyOptions { divider?: string; sort?: boolean | 'asc' | 'desc'; } ``` -------------------------------- ### applyCasing Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/api-formatting.md Transforms a string's letter casing to lowercase, uppercase, or titlecase. ```APIDOC ## applyCasing ### Description Transforms a string's letter casing. ### Method Signature ```typescript function applyCasing(value: string, casing?: LetterCasing): string ``` ### Parameters #### Parameters - **value** (string) - Required - String to transform - **casing** (LetterCasing) - Optional - Casing type: `lowercase`, `uppercase`, or `titlecase` ### Return Value Returns the cased string (`string`). `titlecase` uppercases the first letter of each word while preserving the rest. ### Example ```typescript import { applyCasing } from "@julianobazzi/utils"; applyCasing("são paulo", "uppercase"); // "SÃO PAULO" applyCasing("são paulo", "titlecase"); // "São Paulo" applyCasing("1.50 KB", "titlecase"); // "1.50 KB" ``` ``` -------------------------------- ### FormatBytesOptions Interface Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/types.md Options for the formatBytes function. Allows specifying the casing for the output. ```typescript interface FormatBytesOptions { casing?: LetterCasing; } ``` -------------------------------- ### FormatMonthOptions Interface Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/types.md Defines options for the `formatMonth` function. Use the `fallback` field to specify a value returned when the input month is missing. ```typescript interface FormatMonthOptions { fallback?: string; } ``` -------------------------------- ### Default Fallback Values for Formatting Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/README.md Formatting functions provide sensible defaults when input is null or zero. Custom fallbacks can be specified using an options object. ```typescript formatDate(null); formatCurrency(0); formatAge(null); ``` ```typescript formatDate(null, { fallback: "Não Informado" }); formatCurrency(0, 100, { fallback: "—" }); ``` -------------------------------- ### Date and Time Formatting Source: https://github.com/julianobazzi/utils/blob/master/README.md Functions for formatting dates and times into various string representations. ```APIDOC ## formatDate ### Description Formats a date value into a `DD/MM/YY` or `DD/MM/YYYY` string. ### Signature `formatDate(value?, { simplified?, fallback? })` ### Parameters - **value** (Date | string | number, optional) - **simplified** (boolean, optional) - If true, uses `DD/MM/YY`. Otherwise, uses `DD/MM/YYYY`. - **fallback** (string, optional) - Value to return if formatting fails. ``` ```APIDOC ## formatDateTime ### Description Formats a date and time value into a `DD/MM/YY HH:mm` string, with options for a 4-digit year and seconds. ### Signature `formatDateTime(date?, { simplified?, showSeconds?, fallback? })` ### Parameters - **date** (Date | string | number, optional) - **simplified** (boolean, optional) - If true, uses `DD/MM/YY`. Otherwise, uses `DD/MM/YYYY`. - **showSeconds** (boolean, optional) - If true, includes seconds in the format (`HH:mm:ss`). - **fallback** (string, optional) - Value to return if formatting fails. ``` ```APIDOC ## formatMonth ### Description Formats a date value into a `MM/YYYY` string. ### Signature `formatMonth(value?, { fallback? })` ### Parameters - **value** (Date | string | number, optional) - **fallback** (string, optional) - Value to return if formatting fails. ``` ```APIDOC ## formatHour ### Description Formats a date value into a `HH:mm` or `HH:mm:ss` string. ### Signature `formatHour(date?, { simplified?, fallback? })` ### Parameters - **date** (Date | string | number, optional) - **simplified** (boolean, optional) - If true, includes seconds (`HH:mm:ss`). Otherwise, uses `HH:mm`. - **fallback** (string, optional) - Value to return if formatting fails. ``` ```APIDOC ## formatSecondsToTime ### Description Converts seconds into a `HH:mm:ss` or `HH:mm` string. ### Signature `formatSecondsToTime(value?, showSeconds = true)` ### Parameters - **value** (number, optional) - The total number of seconds. - **showSeconds** (boolean, optional) - If true, includes seconds in the output. Defaults to true. ``` -------------------------------- ### formatAge Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/api-formatting.md Formats age as Portuguese text (e.g., `36 anos` or `1 ano`). Accepts an optional birth date and configuration options. ```APIDOC ## formatAge ### Description Formats age as Portuguese text (e.g., `36 anos` or `1 ano`). Accepts an optional birth date and configuration options. ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters - **birthDate** (string | null) - Optional - ISO date string - **options** (FormatAgeOptions) - Optional - Configuration object - **options.fallback** (string) - Optional - Value returned when input is missing/invalid ### Return Value Returns age as a Portuguese string (`string`). ### Example ```typescript import { formatAge } from "@julianobazzi/utils"; formatAge("1990-05-15"); // "34 anos" formatAge("2023-05-15"); // "1 ano" ``` ``` -------------------------------- ### FormatWeekDayOptions Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/types.md Options for the formatWeekDay function. Allows specifying fallback, casing, and date format. ```APIDOC ## FormatWeekDayOptions ### Description Options for the `formatWeekDay` function. Allows specifying a fallback value, letter casing, and date format. ### Fields #### Optional Fields - **fallback** (string) - Optional - Default: `""` - Value returned when input is missing. - **casing** (LetterCasing) - Optional - Specifies the letter casing transformation. - **dateFormat** (string) - Optional - Default: `"D/M"` - dayjs format string for the date part. ``` -------------------------------- ### Address and Location Formatting Source: https://github.com/julianobazzi/utils/blob/master/README.md Functions for formatting address components and location-related strings. ```APIDOC ## formatAddress ### Description Builds a single-line address string from address components. ### Signature `formatAddress(address, { fallback? })` ### Parameters - **address** (object) - An object containing address details. - **fallback** (string, optional) - Value to return if formatting fails. ``` ```APIDOC ## formatCityAndState ### Description Formats a city and state into a ` ``` ```APIDOC ## formatCityAndState ### Description Formats a city and state into a `"City - UF"` string. Returns empty if both are missing. ### Signature `formatCityAndState(city?, state?, { fallback?, separator?, casing? })` ### Parameters - **city** (string, optional) - **state** (string, optional) - **fallback** (string, optional) - Value to return if formatting fails. - **separator** (string, optional) - Separator between city and state. Defaults to `' - '`. - **casing** (string, optional) - Desired casing for the output. ``` -------------------------------- ### Browser Image Utilities Return Promises Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/README.md Image utility functions that operate in the browser return Promises and can reject on failure. Use try-catch blocks for error handling. ```typescript try { const img = await loadImageFromBlob(blob); document.body.appendChild(img); } catch (error) { console.error("Failed to load:", error); } ``` -------------------------------- ### Legacy and Barcode Generation Options Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/configuration.md Generate legacy formats for Renavam and Plates, or control barcode length for EAN-13 and EAN-8. Use `legacy` and `length` options accordingly. ```typescript // Legacy formats generateRenavam({ legacy: true }); // 9 digits generatePlate({ mercosul: false, formatted: true }); // "ABC-1234" (legacy) // Barcode generation generateBarcode({ length: 13 }); // EAN-13 (default) generateBarcode({ length: 8 }); // EAN-8 ``` -------------------------------- ### FormatPostalCodeOptions Interface Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/types.md Defines options for the formatPostalCode function, with a fallback value. ```typescript interface FormatPostalCodeOptions { fallback?: string; } ``` -------------------------------- ### Format City and State String Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/api-formatting.md Formats city and state into a "City - UF" string. Supports custom separators and fallback values. Use this for displaying location information concisely. ```typescript import { formatCityAndState } from "@julianobazzi/utils"; formatCityAndState("São Paulo", "SP"); // "São Paulo - SP" formatCityAndState("Rio", null); // "Rio" ``` -------------------------------- ### Convert Currency to Portuguese Words Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/api-formatting.md Converts a Brazilian Real (BRL) amount to its Portuguese word representation, including reais and centavos. Use this for spelling out monetary values. ```typescript import { currencyToWords } from "@julianobazzi/utils"; currencyToWords(1990); // "dezenove reais e noventa centavos" currencyToWords(100, 1); // "cem reais" ``` -------------------------------- ### Document Generation Options Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/configuration.md Control the format and content of generated documents like CPF, CNPJ, PIS, and Plates. Use options like `formatted`, `alphanumeric`, and `mercosul` to customize output. ```typescript // Document generation generateCPF({ formatted: true }); // "529.982.247-25" generateCNPJ({ formatted: true, alphanumeric: true }); // "34.ABC.316/DEF-86" generatePIS({ formatted: true }); // "120.12345.67-0" generatePlate({ mercosul: true, formatted: true }); // "ABC-1D23" ``` -------------------------------- ### findOptionsByIds Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/api-object.md Finds multiple options from an array that match the given IDs. Returns an array of matching options, preserving the order of input IDs. ```APIDOC ## findOptionsByIds ### Description Maps each id to its matching option, dropping non-matches. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **options** (O[] | null) - Optional - Array of options with `id` properties - **value** ((string | number)[] | null) - Optional - Array of IDs to search for ### Return Value Returns an array of matching options (`O[]`), preserving the order of input ids. Missing options are skipped. ### Example ```typescript import { findOptionsByIds } from "@julianobazzi/utils"; const users = [ { id: 1, name: "John" }, { id: 2, name: "Jane" }, { id: 3, name: "Bob" } ]; findOptionsByIds(users, [1, 3]); // [{ id: 1, name: "John" }, { id: 3, name: "Bob" }] findOptionsByIds(users, ["2", 3, 99]); // [{ id: 2, name: "Jane" }, { id: 3, name: "Bob" }] findOptionsByIds(users, null); // [] ``` ``` -------------------------------- ### Sorting Options for joinByKey Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/configuration.md Configure sorting behavior for the `joinByKey` function using the `sort` option, which accepts boolean or specific order ('asc', 'desc'). The `divider` option customizes the join separator. ```typescript interface JoinByKeyOptions { divider?: string; sort?: boolean | 'asc' | 'desc'; } // Sort options joinByKey(users, "name"); // No sorting joinByKey(users, "name", { sort: true }); // Ascending joinByKey(users, "name", { sort: "asc" }); // Ascending joinByKey(users, "name", { sort: "desc" }); // Descending joinByKey(users, "age", { divider: ", ", sort: "desc" }); // Numeric sort ``` -------------------------------- ### Convert Currency to Words (BRL) Source: https://github.com/julianobazzi/utils/blob/master/llms.txt Converts a BRL currency value into its Portuguese word representation. Handles centavos, millions, and provides a fallback for invalid or missing inputs. ```javascript currencyToWords(123456) // -> "cento e vinte e três mil quatrocentos e cinquenta e seis reais" currencyToWords(1234.56, 1) // -> "mil duzentos e trinta e quatro reais e cinquenta e seis centavos" currencyToWords(0) // -> "zero reais" ``` -------------------------------- ### Duration Formatting Source: https://github.com/julianobazzi/utils/blob/master/README.md Functions for converting time durations into human-readable strings. ```APIDOC ## formatMinutesToDuration ### Description Converts a duration in minutes into a human-readable string (e.g., `1h e 30 min`). ### Signature `formatMinutesToDuration(minutes?, { fallback?, spaced? })` ### Parameters - **minutes** (number, optional) - **fallback** (string, optional) - Value to return if formatting fails. - **spaced** (boolean, optional) - If true, uses spaced format (e.g., `1h 30min`). ``` ```APIDOC ## formatSecondsToDuration ### Description Converts a duration in seconds into a human-readable string, rounding to minutes if 60 seconds or more. ### Signature `formatSecondsToDuration(seconds?, { fallback?, spaced? })` ### Parameters - **seconds** (number, optional) - **fallback** (string, optional) - Value to return if formatting fails. - **spaced** (boolean, optional) - If true, uses spaced format. ``` ```APIDOC ## formatDuration ### Description **Deprecated**: Alias for `formatMinutesToDuration`. ### Signature `formatDuration(minutes?, { fallback?, spaced? })` ``` -------------------------------- ### formatWithPattern Source: https://github.com/julianobazzi/utils/blob/master/_autodocs/api-formatting.md Applies a character mask to a string using a provided pattern. The '#' character in the pattern represents the next character from the input value. ```APIDOC ## formatWithPattern ### Description Applies a character mask to a string (char-agnostic pattern). The '#' character in the pattern represents the next character from the input value. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **value** (string | null) - Optional - String to mask - **pattern** (string | null) - Optional - Mask pattern where '#' represents next character from value ### Return Value Returns a masked string (string). ### Example ```typescript import { formatWithPattern } from "@julianobazzi/utils"; formatWithPattern("12345678900", "###.###.###-##"); // "123.456.789-00" formatWithPattern("1234567890", "(##) ####-####"); // "(12) 3456-7890" ``` ```