camote-utils camote-utils

npm version License: MIT Total Downloads Coverage Maintenance GitHub Stars Twitter Follow
Buy Me A Coffee

Fast & Lightweight

Zero dependencies, tree-shakeable, and optimized for performance

Type-Safe

Written in TypeScript with full type definitions

Easy to Use

Simple, intuitive API with comprehensive documentation

Getting Started

Installation

Install camote-utils using npm:

npm install camote-utils

Basic Usage

Here are some examples of basic functionality:

import { _, pluralize } from 'camote-utils'

// String manipulation
pluralize('cat', 1)                  // 'cat'
pluralize('cat', 2)                  // 'cats'
pluralize('box', 2)                  // 'boxes'
pluralize('baby', 2)                 // 'babies'
pluralize('person', 1, 'people')     // 'person'
pluralize('person', 2, 'people')     // 'people'

// Masking
_.mask('1234567890')                 // '1234******'
_.mask('123456NiCe', '#')            // '1234######'
_.mask('123456NiCe', '#', 4, 'start')            // '####56NiCe'

// Basic formatting
_.humanReadableNumber(1234567.89)    // "1.2M"

// With units
_.humanReadableNumber(1500, { decimals: 0 })      // "2K"

Chain Operations

Chain operations allow you to perform multiple operations on a value in a fluent interface.

Chain Syntax

Use the chain syntax to perform multiple operations in sequence:

import { _ } from 'camote-utils
const result = _.chain('hello world')
    .capitalize()
    .truncate(5) // Hello

Static Methods

Use static methods for direct operations:

import { capitalize, truncate } from 'camote-utils

capitalize('hello world')   // Hello world
truncate('hello world', 5)  // hello...

Chain Methods

Methods available in the chain sequence:

  • capitalize(): Capitalizes the first character
  • truncate(length: number): Truncates to specified length
  • toLowerCase(): Converts to lowercase
  • toUpperCase(): Converts to uppercase
  • trim(): Removes leading/trailing whitespace

Checkers

Utility functions for type checking and validation.

Type Checking and String Validation

Available Functions

// Type checking functions
isString(value: any): boolean;    // Check if value is a string
isNumber(value: any): boolean;    // Check if value is a number
isBoolean(value: any): boolean;   // Check if value is a boolean
isArray(value: any): boolean;     // Check if value is an array
isObject(value: any): boolean;    // Check if value is an object
isNull(value: any): boolean;      // Check if value is null
isUndefined(value: any): boolean; // Check if value is undefined
isFunction(value: any): boolean;  // Check if value is a function
isEmpty(value: any): boolean;     // Check if value is empty

Usage Examples

// Basic type checking
isString('hello')      // true
isString(123)          // false

isNumber(42)           // true
isNumber('42')         // false

isArray([1, 2, 3])     // true
isArray({ foo: 'bar'}) // false

isObject({ name: 'John' }) // true
isObject([1, 2, 3])        // false

// Checking for null and undefined
isNull(null)           // true
isNull(undefined)      // false

isUndefined(undefined) // true
isUndefined(null)      // false

isEmpty('')            // true
isEmpty([])            // true
isEmpty({})            // true
isEmpty(null)          // true
isEmpty(undefined)     // true
isEmpty('hello')       // false

String Validation

Available Functions

// String validation functions
isEmail(value: string): boolean;     // Validate email format
isUrl(value: string): boolean;       // Validate URL format
isStrongPassword(value: string, options?: PasswordOptions): boolean; // Validate password strength
isValidTime(value: string): boolean; // Validate time format

interface PasswordOptions {
    minLength?: number;      // Minimum length (default: 8)
    minLowercase?: number;   // Minimum lowercase chars (default: 1)
    minUppercase?: number;   // Minimum uppercase chars (default: 1)
    minNumbers?: number;     // Minimum numbers (default: 1)
    minSymbols?: number;     // Minimum special chars (default: 1)
}

Usage Examples

// Email validation
isEmail('user@example.com')     // true
isEmail('invalid-email')        // false

// URL validation
isUrl('https://example.com')    // true
isUrl('not-a-url')              // false

// Password strength validation
const passwordOptions = {
    minLength: 8,
    minLowercase: 1,
    minUppercase: 1,
    minNumbers: 1,
    minSymbols: 1
};

isStrongPassword('Abc123!@#', passwordOptions)  // true
isStrongPassword('weakpass', passwordOptions)   // false

isValidTime('14:30') // true

Number Formatting

humanReadableNumber(number, options)

Formats a number with various options:

// Basic formatting
humanReadableNumber(1234567.89)                // "1.2M"
humanReadableNumber(1234.5, { decimals: 0 })   // "1,235"

// With units
humanReadableNumber(1500, { compact: true })    // "1.5K"
humanReadableNumber(1500000, { compact: true }) // "1.5M"
humanReadableNumber(1500, { decimals: 0 })      // "2K"
humanReadableNumber(999, { decimals: 0 })       // "999"

formatPercent(number, options)

Formats a number as a percentage:

formatPercent(0.1234)                    // "12.34%"
formatPercent(0.1234, { decimals: 1 })   // "12.3%"

formatDecimals(number, decimals)

Formats a number with fixed decimal places:

formatDecimals(123.456, 2)               // "123.46"
formatDecimals(123.4, 2)                 // "123.40"
formatDecimals(123.456, 2, 'ceil')       // "123.46"
formatDecimals(123.456, 2, 'floor')      // "123.45"

Currency Formatting

formatCurrency(amount, currency?, locale?)

Formats a number as currency:

// Basic usage
formatCurrency(1234.56)                  // "$1,234.56"
formatCurrency(1234.56, 'EUR')           // "€1,234.56"
formatCurrency(1234.56, 'JPY', 'ja-JP')  // "¥1,235"
formatCurrency(1234.56, 'GBP', 'en-GB')  // "£1,234.56"

Price Calculations

calculateDiscountPrice(price, discount)

Calculates the final price after applying a discount:

// Calculate a fixed discount of $30 on an original price of $100
calculateDiscountPrice(100, 30, '$')   // 70

// Calculate a percentage discount of 10% on an original price of $200
calculateDiscountPrice(200, 0.10, '%') // 180

// Calculate a fixed discount of $15 on an original price of $50
calculateDiscountPrice(50, 15, '$')    // 35

// Calculate a percentage discount of 25% on an original price of $80
calculateDiscountPrice(80, 0.25, '%')  // 60

// Calculate a fixed discount of $0 on an original price of $100 (no discount)
calculateDiscountPrice(100, 0, '$')    // 100

// Calculate a percentage discount of 0% on an original price of $150 (no discount)
calculateDiscountPrice(150, 0, '%')    // 150

String Manipulation

Functions for manipulating and formatting strings.

capitalize

Capitalizes the first letter of a string.

capitalize("hello") // "Hello"

capitalizeWords

Capitalizes the first letter of each word in a string.

capitalizeWords("hello world") // "Hello World"

truncate

Truncates a string to a specified length and adds an ellipsis.

truncate("Hello World", 8) // "Hello..."

toCamelCase

Converts a string to camelCase.

toCamelCase("hello-world") // "helloWorld"

toKebabCase

Converts a string to kebab-case.

toKebabCase("helloWorld") // "hello-world"

toSnakeCase

Converts a string to snake_case.

toSnakeCase("helloWorld") // "hello_world"

slugify

Converts a string to a URL-friendly slug.

slugify("Hello World!") // "hello-world"

slugifyRevert

Converts a slug back to title case.

slugifyRevert("hello-world") // "Hello World"

wordCount

Counts the number of words in a string.

wordCount("Hello world") // 2

pad

The pad function extends a string to a specified length by adding a specified character to the start, end, or both sides of the string. This is useful for aligning text or ensuring consistent string lengths in formatted outputs.

Examples:

pad("hello", 8)                 // "hello   "
pad("hello", 8, "*", "start")   // "***hello"
pad("hello", 8, "*", "both")    // "*hello**"
pad("hello", 8, " ", "both")    // " hello  "

Scenarios:

  • Aligning text in console outputs or logs for better readability.
  • Formatting numbers with leading zeros for consistency in reports.
  • Creating fixed-width fields in text-based user interfaces.

mask

The mask function extends a string to a specified length by adding a specified character to the start, end, or both sides of the string. This is useful for aligning text or ensuring consistent string lengths in formatted outputs.

Examples:

// Number of characters to keep visible (default: 6)
mask('1234567890')                        // '1234******'
mask('123456NiCe', '#')                   // '1234######'
mask('1234567890', '*', 4)                // '1234******'
mask('1234567890', '*', 7, 'start')       // '*******890'
mask('1234567890', '*', 5, 'end')         // '12345*****'
mask('camote2025', '*', 4)                // 'camote****'
// default true
mask('1234567890', '*', 6, 'end', false)  // '1234567890'

Scenarios:

  • Masking sensitive information, such as credit card numbers or social security numbers.
  • Creating placeholders for user input fields in forms.
  • Displaying sensitive data in a secure way in console logs or error messages.

format

Formats a string by replacing placeholders with provided values.

format("Hello {name}!", { name: "World" }) // "Hello World!"

reverse

Reverses a string.

reverse("hello") // "olleh"

clean

Removes extra whitespace from a string.

clean("  hello   world  ") // "hello world"

pluralize

The pluralize function adjusts a word to its plural form based on the provided count or a custom plural form. It is particularly useful for dynamically generating grammatically correct text based on quantities.

Examples:

pluralize("cat", 1)                        // "cat"
pluralize('cat', 2)                        // 'cats'
pluralize('box', 2)                        // 'boxes'
pluralize('baby', 2)                       // 'babies'
pluralize('person', 1, 'people')           // 'person'
pluralize('person', 2, 'people')           // 'people'
pluralize("person", undefined, "people")   // "people"

Scenarios:

  • Displaying item counts in a shopping cart with correct singular or plural forms.
  • Generating user-friendly messages in applications, such as "1 new message" vs. "5 new messages".
  • Handling irregular plural forms in internationalized applications.

toUpperCase

Converts a string to uppercase with optional locale support.

toUpperCase("hello") // "HELLO"

toLowerCase

Converts a string to lowercase with optional locale support.

toLowerCase("HELLO") // "hello"

chopStart

Removes a specified number of characters from the start of a string.

chopStart("hello", 2) // "llo"

chopEnd

Removes a specified number of characters from the end of a string.

chopEnd("hello", 2) // "hel"

contains

The contains function checks if a given substring exists within a string. It can be configured to perform case-sensitive or case-insensitive searches, making it versatile for various text processing tasks.

Examples:

contains("Hello World", "world", true)   // false
contains("Hello World", "world", false)  // true
contains("Hello World", "lo")            // true

Scenarios:

  • Searching for keywords within user-generated content or documents.
  • Implementing basic search functionality in applications.
  • Validating input by checking for the presence of specific substrings.

exactly

Checks if two strings match exactly.

exactly("Hello", "hello", false) // true

trim

Removes leading and trailing whitespace from a string.

trim("  Hello  ") // "Hello"

explode

Splits a string into an array of characters.

explode("Hello,World", ",")          // ["Hello", "World"]
explode("Hello,World,Again", ",", 2) // ["Hello", "World,Again"]
explode("Hello,World,Again", ",", 3) // ["Hello", "World", "Again"]
                

toUnicodes

Converts a string into its Unicode escape sequence representation.

toUnicodes("Hello"); //"\u{0048}\u{0065}\u{006C}\u{006C}\u{006F}"
toUnicodes("Hi 😀"); //" \u{0048}\u{0069}\u{0020}\u{1F600}"
toUnicodes("Hello", "He"); // "He\u{006C}\u{006C}\u{006F}"
toUnicodes("Hi 😀", ["H", "i"]); // "Hi\u{0020}\u{1F600}"

toHtmlEntities

Converts a string into its HTML Entities representation.

toHtmlEntities("Hello");  // "Hello"
toHtmlEntities('Hi 😀'); // "Hi 😀"
toHtmlEntities("Hello", "He"); // "Hello"
toHtmlEntities("Hi 😀", ["H", "i"]); // "Hi 😀"

swapCase

Swaps the case of each alphabetic character in a string. Uppercase letters are converted to lowercase, and lowercase letters to uppercase. Non-alphabetic characters remain unchanged.

swapCase("Hello World");  // "hELLO wORLD"
swapCase("JavaScript");   // "jAVAsCRIPT"
swapCase("123 ABC!");     // "123 abc!"
swapCase("");             // ""

Array Manipulation

Functions for manipulating and working with arrays.

removeDuplicates

Removes duplicate elements from an array.

removeDuplicates([1, 2, 2, 3, 4, 4, 5]) // [1, 2, 3, 4, 5]

flattenArray

Flattens a nested array into a single level array.

flattenArray([1, 2, [3, 4], [5, 6]]) // [1, 2, 3, 4, 5, 6]

filterArray

Filters an array based on a predicate function.

filterArray([1, 2, 3, 4, 5], (num) => num % 2 === 0)             // [2, 4]
filterArray([1, 2, 3, 4, 5, 6, 7, 8], (num) => num % 2 !== 0)    // [1, 3, 5, 7]
filterArray([1, 2, 3, 4, 5, 6, 7, 8], (num) => num > 4)          // [5, 6, 7, 8]
filterArray([1, 2, 3, 4, 5, 6, 7, 8], (num) => num <= 4)         // [1, 2, 3, 4]

transformArray

Transforms an array by applying a function to each element.

transformArray([1, 2, 3], (num) => num * 2) // [2, 4, 6]

capitalizeEach

Capitalizes the first letter of each word in each string within an array.

capitalizeEach(["hello world", "typescript rocks"])   // ["Hello World", "Typescript Rocks"]

implode

Converts an array into a comma-separated string.

implode([1, 2, 3]) // "1,2,3"
implode(["Hello", "World"], " ") // "Hello World"
implode(["Hello", "World"], ", ") // "Hello, World"
                

Object Manipulation

Functions for manipulating and working with objects.

removeEmptyKeysEntries

Removes empty keys and entries from an object.

const input = {
    a: 1,
    b: null,
    c: undefined,
    d: '',
    e: [],
    f: {},
    g: 0,
    h: 'value',
    i: [1, 2, 3],
}

const expectedOutput = {
    a: 1,
    g: 0,
    h: 'value',
    i: [1, 2, 3],
}

expect(removeEmptyKeysEntries(input)).toEqual(expectedOutput)  // true

objectToQueryString

Converts an object, array of key-value pairs (matrix), or a flat array of alternating keys and values into a URL query string.
The function can handle different input formats:
- A plain object (Record <string, any>),
- A matrix (an array of arrays, where each sub-array has two elements representing a key-value pair),
- A flat array with an even number of elements, where each even-indexed element is a key, and the following odd-indexed element is its corresponding value.

// Using a plain object
objectToQueryString({ key1: 'value1', key2: 'value2' });
// Returns: "key1=value1&key2=value2"

// Using a matrix (array of key-value pairs)
objectToQueryString([['key1', 'value1'], ['key2', 'value2']]);
// Returns: "key1=value1&key2=value2"

// Using a flat array
objectToQueryString(['key1', 'value1', 'key2', 'value2']);
// Returns: "key1=value1&key2=value2"

// Throws an error for an invalid array format
objectToQueryString([['key1', 'value1'], 'invalid']);
// Throws: Error: Invalid array format: Expected either an array of key-value pairs (matrix) or a flat array with an even number of elements.

// Throws an error for an empty object / array
objectToQueryString([]);
objectToQueryString({});
// Throws: Error: Invalid input format: Expected a non-empty object or a valid array format.

objectFilterByKeys

Filters an object by keys and returns a new object with only the specified keys.

const input = {
    a: 1,
    b: 2,
    c: 3,
    d: 4,
}

const keys = ['a', 'b']

const expectedOutput = {
    a: 1,
    b: 2,
}

const output = objectFilterByKeys(input, keys)

expect(output).toEqual(expectedOutput)  // true

Deep Manipulation

Functions for deep manipulation and working with objects, strings, and arrays recursively.

deepClone

Creates a deep copy of an object. It handles nested objects, arrays, dates, and other complex structures.

deepClone({ a: 1, b: { c: 2 } })          // { a: 1, b: { c: 2 } }
deepClone([1, { a: 2 }])                  // [1, { a: 2 }]
deepClone(new Date(2024, 11, 20))         // Date object with the same date
deepClone(object)                         // Deep copy of the object
deepClone([{ a: 1 }, { b: 2 }])           // [{ a: 1 }, { b: 2 }]
deepClone({ a: [1, 2, { b: 3 }] })        // { a: [1, 2, { b: 3 }] }

deepCompare

Compares two objects deeply and returns either true or false based on equality. Optionally, returns an object containing the differences.

deepCompare = (originalObject: any, toCompareObject: any, returnChanges: boolean = false): boolean | object => {}

// Example 1: Objects are equal
const obj1 = { a: 1, b: { c: 2 } }
const obj2 = { a: 1, b: { c: 2 } }
deepCompare(obj1, obj2)  // true
deepCompare(obj1, obj2, true)  // {}

// Example 2: Objects are not equal
const obj1 = { a: 1, b: { c: 2 } }
const obj2 = { a: 1, b: { c: 3 } }
deepCompare(obj1, obj2, true)     // { b: { c: 3 } }
deepCompare(obj1, obj2)           // false

// Example 3: Comparing arrays
const arrayWithObject1 = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]
const arrayWithObject2 = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Charlie' }]
deepCompare(arrayWithObject1, arrayWithObject2, true);           // [{ id: 2, name: 'Charlie' }]
deepCompare(arrayWithObject1, arrayWithObject2)                  // false

// Example 4: Comparing nested objects
const nestedObj1 = { users: [{ id: 1, name: 'Alice' }], settings: { theme: 'dark' } };
const nestedObj2 = { users: [{ id: 1, name: 'Alice' }], settings: { theme: 'light' } };
// Return true if objects are equal
deepCompare(nestedObj1, nestedObj2)                              // false
// Returns an object with the differences
deepCompare(nestedObj1, nestedObj2, true);                       // { settings: { theme: 'light' } }

deepMerge

Merges two objects recursively, overwriting values in the first object with values from the second objects or arrays.

deepMerge({ a: 1, b: { c: 2 } }, { b: { d: 3 } })   // { a: 1, b: { c: 2, d: 3 } }
deepMerge({ a: 1 }, { b: 2 })                       // { a: 1, b: 2 }
deepMerge({ a: 1 }, { a: 2 })                       // { a: 2 }
deepMerge({ a: { b: 1 } }, { a: { c: 2 } })         // { a: { b: 1, c: 2 } }
deepMerge({ arr: [1, 2, 3] }, { arr: [3, 4, 5] })   // { arr: [1, 2, 3, 4, 5] }
// Exclude keys
deepMerge( { a: 1, b: 2 }, { c: 3, d: 4, e: 5 }, ['d', 'e'])   // { a: 1, b: 2, c: 3 }

deepSortAlphabetical

Sorts an object or array alphabetically by key.

deepSortAlphabetical({ a: 1, b: 2, c: 3 })   // { a: 1, b: 2, c: 3 }
deepSortAlphabetical([1, 2, 3])              // [1, 2, 3]

// Example with nested objects
deepSortAlphabetical({ c: { d: 4, a: 1 }, b: 2 })        // { b: 2, c: { a: 1, d: 4 } }
deepSortAlphabetical([{ b: 2 }, { a: 1 }, { c: 3 }])     // [{ a: 1 }, { b: 2 }, { c: 3 }]

// Reverse order
deepSortAlphabetical({ a: { b: 1, c: 2 }, d: 3 }, true)   // { d: 3, a: { b: 1, c: 2 } }
deepSortAlphabetical([1, 2, 3], true)                     // [3, 2, 1]
            

Date Validation

isDateWithinRange(date, startDate, endDate)

Checks if a date is within a specified range:

const date = new Date('2024-01-15')
const start = new Date('2024-01-01')
const end = new Date('2024-01-31')

isDateWithinRange(start, end, date)  // true

// Check if the current date is within the range
isDateWithinRange(start, end)        // true (using default current date)

Random Generation

A comprehensive set of functions for generating various types of random data.

Integer Generation

Functions for generating random integers with various constraints:

// Basic random integer
generateRandomInteger(10)    // e.g., 7 (0-10)
generateRandomInteger(100)   // e.g., 42 (0-100)

// Random integer in range
generateRandomIntegerInRange(5, 10)     // e.g., 7 (5-10)
generateRandomIntegerInRange(-10, 10)   // e.g., -3 (-10 to 10)

// Array of random integers
generateRandomIntegerArray(5, 1, 10)    // e.g., [3, 7, 1, 9, 4]
generateRandomIntegerArray(3, 0, 100)   // e.g., [42, 67, 13]

// Generates an array of random integers
generateRandomIntegerExcluding(1, 10, [5, 6])    // Returns a number between 1-4 or 7-10
generateRandomIntegerExcluding(1, 3, [2])        // Returns either 1 or 3

String Generation

Generate random strings with different patterns and constraints:

// Basic random string
generateRandomString(8)        // e.g., "Kj#9mP2$"
generateRandomString(12)       // e.g., "aB3$kL9#mN5@"

// Alphabetic string (a-z, A-Z)
generateRandomAlpha(8)         // e.g., "KjNmPqRs"
generateRandomAlpha(8, true)   // e.g., "kjnmpqrs" (lowercase only)
generateRandomAlpha(8, false)  // e.g., "KJNMPQRS" (uppercase only)

// Alphanumeric string (a-z, A-Z, 0-9)
generateRandomAlphanumeric(8)  // e.g., "Kj9mP2Nx"

// Hexadecimal string
generateRandomHex(8)           // e.g., "a1b2c3d4"
generateRandomHex(6)           // e.g., "ff8800" (useful for colors)

Password Generation

Generate secure random passwords with customizable options:

// Basic password generation
generateRandomPassword(12);  // "aB3$kL9p#mN4"

// Custom password options
generateRandomPassword(8, { exclude: 'O0Il1' }); // Excludes ambiguous characters

// Excludes all character types
generateRandomPassword(8, { lowercase: false, uppercase: false, numbers: false, special: false });

// Uses custom character set
generateRandomPassword(8, { custom: "ABC123" });

// Uses custom character set and excludes ambiguous characters
generateRandomPassword(8, { exclude: 'O0Il1', custom: "ABC123" });

// Generate strong password (enforces security rules)
generateStrongPassword()    // e.g., "StrongP@ssw0"
generateStrongPassword(16)  // e.g., "StrongP@ssw0rd#2"

Color Generation

Generate random colors in various formats:

// Basic color generation
generateRandomColor()           // e.g., "#FF5733"
generateRandomColor('rgb')      // e.g., "rgb(255, 87, 51)"
generateRandomColor('hsl')      // e.g., "hsl(20, 100%, 60%)"

// Specific color format generation
generateRandomRGB()            // e.g., [255, 87, 51]
generateRandomRGB(true)        // e.g., "rgb(255, 87, 51)"
generateRandomHSL()            // e.g., [20, 100, 60]
generateRandomHSL(true)        // e.g., "hsl(20, 100%, 60%)"

// Generate color palette
generateColorPalette(5)         // e.g., ["#FF5733", "#33FF57", "#5733FF", "#FF3333", "#33FFFF"]
generateColorPalette(3, 'rgb')  // e.g., ["rgb(255,87,51)", "rgb(51,255,87)", "rgb(87,51,255)"]

UUID Generation

Generate various versions of UUIDs:

// Basic UUID generation (v4)
generateUUID()     // e.g., "123e4567-e89b-12d3-a456-426614174000"

// Specific UUID versions
generateUUIDv4()   // e.g., "110ec58a-a0f2-4ac4-8393-c866d813b8d1"

Generate Random By Type

Generate random data of various types:

// Custom data with options
generateRandom({ type: 'integer', min: 1, max: 10 })     // 7
generateRandom({ type: 'float', min: 0, max: 1 })        // 0.123456
generateRandom({ type: 'boolean' })                      // true
generateRandom({ type: 'string', length: 8 })            // "aB3$kL9p"
generateRandom({ type: 'hexColor' })                     // "#FF5733"
generateRandom({ type: 'rgbColor' })                     // "rgb(255, 87, 51)"
generateRandom({ type: 'rgbColor', format: 'array' })    // [255, 87, 51]
generateRandom({ type: 'hslColor' })                     // "hsl(20, 100%, 60%)"
generateRandom({ type: 'hslColor', format: 'array' })    // [20, 100, 60]
generateRandom({ type: 'colorPalette', numColors: 3 })   // ["#FF5733", "#33FF57", "#5733FF"]
generateRandom({ type: 'uuid' })                         // "123e4567-e89b-12d3-a456-426614174000"

Available Options

interface RandomOptions {
    // General options
    length?: number;       // Length of generated data
    type?: string;         // Type of data for arrays
    format?: string;       // Output format (e.g., 'hex', 'rgb')

    // Number options
    min?: number;          // Minimum value
    max?: number;          // Maximum value
    decimals?: number;     // Number of decimal places

    // String options
    case?: 'lower' | 'upper' | 'mixed  // Case for string generation
    symbols?: boolean;     // Include symbols
    numbers?: boolean;     // Include numbers

    // Date options
    start?: Date;         // Start date for range
    end?: Date;           // End date for range

    // Custom options
    template?: string;    // Custom template for generation
    exclude?: string[];   // Characters to exclude
    include?: string[];   // Characters to include
}

Advanced

TypeScript Usage

camote-utils is written in TypeScript and includes type definitions.

import { generateRandom } from 'camote-utils

// TypeScript will infer the correct return type
const uuid: string = generateRandom('uuid')

Browser Support

This library is compatible with all modern browsers and Node.js environments. It's built using ES2018+ features and includes necessary polyfills for older environments.

<script src="https://unpkg.com/camote-utils"></script>
<script>
    const { humanReadableNumber } = window.camoteUtils;

    humanReadableNumber(1234567)); // "1.23M"
</script>

Supported Browsers

This library supports the following browsers:

  • Chrome (latest 2 versions)
  • Firefox (latest 2 versions)
  • Safari (latest 2 versions)
  • Edge (latest 2 versions)
  • Opera (latest version)

Polyfills

For older browsers, you may need the following polyfills:

npm install core-js regenerator-runtime

Then import them in your entry file:

import 'core-js/stable
import 'regenerator-runtime/runtime

Known Issues

Current known browser-specific issues:

  • IE11 requires additional polyfills for ES6+ features
  • Safari <14 may have issues with certain RegExp features
  • Mobile browsers may have varying support for newer JavaScript features

License

This project is licensed under the MIT License.

Security

For security concerns, please report them through our security policy.

Contributors

Thanks goes to these wonderful people who have contributed to this project:

Want to Contribute?

We welcome contributions of all kinds! Check out our contribution guidelines to get started.