npm package: @murad-wahid/js-utility
Description: Collection of utility functions designed to simplify common programming tasks.
Author: Murad Wahid
Latest version: 0.0.2

# JavaScript Utility Library Documentation

A comprehensive collection of production-ready JavaScript utility functions covering all aspects of modern web development.

## Table of Contents

1. [Performance Utilities](#performance-utilities)
2. [Validation Utilities](#validation-utilities)
3. [String Utilities](#string-utilities)
4. [Object & Array Utilities](#object--array-utilities)
5. [Date Utilities](#date-utilities)
6. [Number & Currency Utilities](#number--currency-utilities)
7. [ID Generation](#id-generation)
8. [Storage Utilities](#storage-utilities)
9. [DOM Utilities](#dom-utilities)
10. [Color Utilities](#color-utilities)
11. [URL & Query Utilities](#url--query-utilities)
12. [File & Data Utilities](#file--data-utilities)
13. [Async Utilities](#async-utilities)
14. [Type Checking Utilities](#type-checking-utilities)
15. [Browser & Environment Utilities](#browser--environment-utilities)
16. [Cookie Utilities](#cookie-utilities)
17. [Event System](#event-system)
18. [Caching System](#caching-system)
19. [Functional Programming](#functional-programming)
20. [Data Structures](#data-structures)
21. [Geolocation](#geolocation)
22. [Performance Monitoring](#performance-monitoring)
23. [Network Utilities](#network-utilities)
24. [Security Utilities](#security-utilities)
25. [Accessibility Utilities](#accessibility-utilities)

---

## Performance Utilities

### `debounce(func, wait)`
Delays function execution until after wait milliseconds have elapsed since the last time it was invoked.

**Parameters:**
- `func` (Function): The function to debounce
- `wait` (number): The number of milliseconds to delay

**Returns:** Function - The debounced function

**Example:**
```javascript
const debouncedSearch = debounce((query) => {
  console.log('Searching for:', query);
}, 300);

// Will only execute once after 300ms of no calls
debouncedSearch('hello');
debouncedSearch('hello world'); // Previous call cancelled
```

### `throttle(func, limit)`
Limits function execution to once per specified time period.

**Parameters:**
- `func` (Function): The function to throttle
- `limit` (number): The number of milliseconds to throttle

**Returns:** Function - The throttled function

**Example:**
```javascript
const throttledScroll = throttle(() => {
  console.log('Scroll event handled');
}, 100);

window.addEventListener('scroll', throttledScroll);
```

### `memoize(fn)`
Caches function results to improve performance for expensive operations.

**Parameters:**
- `fn` (Function): The function to memoize

**Returns:** Function - The memoized function

**Example:**
```javascript
const expensiveCalculation = memoize((n) => {
  console.log('Computing...');
  return n * n * n;
});

expensiveCalculation(5); // Computes and caches
expensiveCalculation(5); // Returns cached result
```

### `once(fn)`
Ensures a function is only called once, returning the same result on subsequent calls.

**Parameters:**
- `fn` (Function): The function to call once

**Returns:** Function - The once-wrapped function

**Example:**
```javascript
const initialize = once(() => {
  console.log('Initializing...');
  return 'initialized';
});

initialize(); // Logs and returns 'initialized'
initialize(); // Returns 'initialized' without logging
```

---

## Validation Utilities

### `validateEmail(email)`
Validates email address format using regex pattern.

**Parameters:**
- `email` (string): Email address to validate

**Returns:** boolean - True if valid email format

**Example:**
```javascript
validateEmail('user@example.com'); // true
validateEmail('invalid-email'); // false
```

### `validatePhone(phone)`
Validates phone number format, supports international formats.

**Parameters:**
- `phone` (string): Phone number to validate

**Returns:** boolean - True if valid phone format

**Example:**
```javascript
validatePhone('+1234567890'); // true
validatePhone('123-456-7890'); // true
validatePhone('invalid'); // false
```

### `validateURL(url)`
Validates URL format using URL constructor.

**Parameters:**
- `url` (string): URL to validate

**Returns:** boolean - True if valid URL

**Example:**
```javascript
validateURL('https://example.com'); // true
validateURL('invalid-url'); // false
```

### `validateCreditCard(cardNumber)`
Validates credit card number using Luhn algorithm.

**Parameters:**
- `cardNumber` (string): Credit card number to validate

**Returns:** boolean - True if valid credit card number

**Example:**
```javascript
validateCreditCard('4532015112830366'); // true (Visa test number)
validateCreditCard('1234567890'); // false
```

### `validatePassword(password)`
Validates password strength with detailed feedback.

**Parameters:**
- `password` (string): Password to validate

**Returns:** Object - `{ isValid: boolean, errors: string[] }`

**Example:**
```javascript
validatePassword('Password123!');
// { isValid: true, errors: [] }

validatePassword('weak');
// { isValid: false, errors: ['At least 8 characters', 'One uppercase letter', ...] }
```

### `validateIPAddress(ip)`
Validates IPv4 and IPv6 address formats.

**Parameters:**
- `ip` (string): IP address to validate

**Returns:** boolean - True if valid IP address

**Example:**
```javascript
validateIPAddress('192.168.1.1'); // true
validateIPAddress('2001:0db8:85a3:0000:0000:8a2e:0370:7334'); // true
validateIPAddress('invalid'); // false
```

### `validateJSON(jsonString)`
Validates JSON string format.

**Parameters:**
- `jsonString` (string): JSON string to validate

**Returns:** boolean - True if valid JSON

**Example:**
```javascript
validateJSON('{"name": "John"}'); // true
validateJSON('invalid json'); // false
```

---

## String Utilities

### `capitalizeWords(str)`
Capitalizes the first letter of each word in a string.

**Parameters:**
- `str` (string): String to capitalize

**Returns:** string - Capitalized string

**Example:**
```javascript
capitalizeWords('hello world'); // 'Hello World'
```

### `truncateText(text, maxLength)`
Truncates text to specified length with ellipsis.

**Parameters:**
- `text` (string): Text to truncate
- `maxLength` (number): Maximum length

**Returns:** string - Truncated text

**Example:**
```javascript
truncateText('This is a long text', 10); // 'This is a...'
```

### `slugify(text)`
Converts text to URL-friendly slug format.

**Parameters:**
- `text` (string): Text to slugify

**Returns:** string - Slugified text

**Example:**
```javascript
slugify('Hello World!'); // 'hello-world'
```

### `camelCase(str)`
Converts string to camelCase format.

**Parameters:**
- `str` (string): String to convert

**Returns:** string - camelCase string

**Example:**
```javascript
camelCase('hello world'); // 'helloWorld'
```

### `kebabCase(str)`
Converts string to kebab-case format.

**Parameters:**
- `str` (string): String to convert

**Returns:** string - kebab-case string

**Example:**
```javascript
kebabCase('Hello World'); // 'hello-world'
```

### `snakeCase(str)`
Converts string to snake_case format.

**Parameters:**
- `str` (string): String to convert

**Returns:** string - snake_case string

**Example:**
```javascript
snakeCase('Hello World'); // 'hello_world'
```

### `reverseString(str)`
Reverses a string.

**Parameters:**
- `str` (string): String to reverse

**Returns:** string - Reversed string

**Example:**
```javascript
reverseString('hello'); // 'olleh'
```

### `isPalindrome(str)`
Checks if a string is a palindrome (ignoring case and non-alphanumeric characters).

**Parameters:**
- `str` (string): String to check

**Returns:** boolean - True if palindrome

**Example:**
```javascript
isPalindrome('A man a plan a canal Panama'); // true
isPalindrome('hello'); // false
```

### `countWords(str)`
Counts the number of words in a string.

**Parameters:**
- `str` (string): String to count words in

**Returns:** number - Word count

**Example:**
```javascript
countWords('Hello world'); // 2
```

### `escapeHtml(text)`
Escapes HTML special characters to prevent XSS attacks.

**Parameters:**
- `text` (string): Text to escape

**Returns:** string - HTML-escaped text

**Example:**
```javascript
escapeHtml('<script>alert("xss")</script>'); // '&lt;script&gt;alert("xss")&lt;/script&gt;'
```

### `extractEmails(text)`
Extracts email addresses from text.

**Parameters:**
- `text` (string): Text to extract emails from

**Returns:** string[] - Array of email addresses

**Example:**
```javascript
extractEmails('Contact us at info@example.com or support@test.org');
// ['info@example.com', 'support@test.org']
```

### `maskString(str, maskChar, visibleStart, visibleEnd)`
Masks part of a string for privacy (useful for credit cards, SSNs).

**Parameters:**
- `str` (string): String to mask
- `maskChar` (string): Character to use for masking (default: '*')
- `visibleStart` (number): Characters visible at start (default: 2)
- `visibleEnd` (number): Characters visible at end (default: 2)

**Returns:** string - Masked string

**Example:**
```javascript
maskString('1234567890123456', '*', 4, 4); // '1234********3456'
```

### `levenshteinDistance(str1, str2)`
Calculates the edit distance between two strings.

**Parameters:**
- `str1` (string): First string
- `str2` (string): Second string

**Returns:** number - Edit distance

**Example:**
```javascript
levenshteinDistance('kitten', 'sitting'); // 3
```

---

## Object & Array Utilities

### `deepClone(obj)`
Creates a deep copy of an object or array.

**Parameters:**
- `obj` (any): Object to clone

**Returns:** any - Deep cloned object

**Example:**
```javascript
const original = { a: 1, b: { c: 2 } };
const cloned = deepClone(original);
cloned.b.c = 3; // original.b.c remains 2
```

### `removeDuplicates(array)`
Removes duplicate values from an array.

**Parameters:**
- `array` (Array): Array to remove duplicates from

**Returns:** Array - Array without duplicates

**Example:**
```javascript
removeDuplicates([1, 2, 2, 3, 3, 4]); // [1, 2, 3, 4]
```

### `groupBy(array, key)`
Groups array elements by a specified key.

**Parameters:**
- `array` (Array): Array to group
- `key` (string): Key to group by

**Returns:** Object - Grouped object

**Example:**
```javascript
const users = [
  { name: 'John', age: 25 },
  { name: 'Jane', age: 25 },
  { name: 'Bob', age: 30 }
];
groupBy(users, 'age');
// { '25': [{ name: 'John', age: 25 }, { name: 'Jane', age: 25 }], '30': [{ name: 'Bob', age: 30 }] }
```

### `sortBy(array, key, direction)`
Sorts array by specified key and direction.

**Parameters:**
- `array` (Array): Array to sort
- `key` (string): Key to sort by
- `direction` (string): 'asc' or 'desc' (default: 'asc')

**Returns:** Array - Sorted array

**Example:**
```javascript
const users = [{ name: 'John', age: 30 }, { name: 'Jane', age: 25 }];
sortBy(users, 'age', 'desc'); // [{ name: 'John', age: 30 }, { name: 'Jane', age: 25 }]
```

### `chunk(array, size)`
Splits array into chunks of specified size.

**Parameters:**
- `array` (Array): Array to chunk
- `size` (number): Chunk size

**Returns:** Array - Array of chunks

**Example:**
```javascript
chunk([1, 2, 3, 4, 5], 2); // [[1, 2], [3, 4], [5]]
```

### `shuffle(array)`
Randomly shuffles array elements.

**Parameters:**
- `array` (Array): Array to shuffle

**Returns:** Array - Shuffled array

**Example:**
```javascript
shuffle([1, 2, 3, 4, 5]); // [3, 1, 5, 2, 4] (random order)
```

### `sample(array, count)`
Returns random sample of elements from array.

**Parameters:**
- `array` (Array): Array to sample from
- `count` (number): Number of elements to sample (default: 1)

**Returns:** Array - Sampled elements

**Example:**
```javascript
sample([1, 2, 3, 4, 5], 3); // [2, 5, 1] (random selection)
```

### `partition(array, predicate)`
Splits array into two arrays based on predicate function.

**Parameters:**
- `array` (Array): Array to partition
- `predicate` (Function): Function to test elements

**Returns:** Array - [truthyArray, falsyArray]

**Example:**
```javascript
partition([1, 2, 3, 4, 5], x => x % 2 === 0); // [[2, 4], [1, 3, 5]]
```

### `deepMerge(target, source)`
Deeply merges two objects.

**Parameters:**
- `target` (Object): Target object
- `source` (Object): Source object

**Returns:** Object - Merged object

**Example:**
```javascript
const target = { a: 1, b: { c: 2 } };
const source = { b: { d: 3 }, e: 4 };
deepMerge(target, source); // { a: 1, b: { c: 2, d: 3 }, e: 4 }
```

### `pick(obj, keys)`
Creates object with only specified keys.

**Parameters:**
- `obj` (Object): Source object
- `keys` (Array): Keys to pick

**Returns:** Object - Object with picked keys

**Example:**
```javascript
pick({ a: 1, b: 2, c: 3 }, ['a', 'c']); // { a: 1, c: 3 }
```

### `omit(obj, keys)`
Creates object without specified keys.

**Parameters:**
- `obj` (Object): Source object
- `keys` (Array): Keys to omit

**Returns:** Object - Object without omitted keys

**Example:**
```javascript
omit({ a: 1, b: 2, c: 3 }, ['b']); // { a: 1, c: 3 }
```

---

## Date Utilities

### `formatDate(date, format)`
Formats date according to specified format.

**Parameters:**
- `date` (Date|string): Date to format
- `format` (string): Format type ('short', 'long', 'iso')

**Returns:** string - Formatted date

**Example:**
```javascript
formatDate(new Date(), 'long'); // 'January 15, 2024'
formatDate(new Date(), 'iso'); // '2024-01-15'
```

### `getRelativeTime(date)`
Gets relative time description (e.g., "2 hours ago").

**Parameters:**
- `date` (Date|string): Date to get relative time for

**Returns:** string - Relative time description

**Example:**
```javascript
getRelativeTime(new Date(Date.now() - 3600000)); // '1 hours ago'
```

### `addDays(date, days)`
Adds specified number of days to a date.

**Parameters:**
- `date` (Date): Base date
- `days` (number): Number of days to add

**Returns:** Date - New date

**Example:**
```javascript
addDays(new Date('2024-01-15'), 7); // Date for 2024-01-22
```

### `getDaysBetween(date1, date2)`
Calculates number of days between two dates.

**Parameters:**
- `date1` (Date): First date
- `date2` (Date): Second date

**Returns:** number - Number of days between dates

**Example:**
```javascript
getDaysBetween(new Date('2024-01-15'), new Date('2024-01-20')); // 5
```

### `isWeekend(date)`
Checks if date falls on weekend.

**Parameters:**
- `date` (Date): Date to check

**Returns:** boolean - True if weekend

**Example:**
```javascript
isWeekend(new Date('2024-01-13')); // true (Saturday)
```

### `getAge(birthDate)`
Calculates age from birth date.

**Parameters:**
- `birthDate` (Date): Birth date

**Returns:** number - Age in years

**Example:**
```javascript
getAge(new Date('1990-01-15')); // 34 (as of 2024)
```

### `startOfDay(date)`, `endOfDay(date)`, `startOfWeek(date)`, `endOfWeek(date)`, `startOfMonth(date)`, `endOfMonth(date)`
Get start/end of time periods.

**Parameters:**
- `date` (Date): Reference date

**Returns:** Date - Start/end of period

**Example:**
```javascript
startOfDay(new Date('2024-01-15 14:30:00')); // 2024-01-15 00:00:00
endOfMonth(new Date('2024-01-15')); // 2024-01-31 23:59:59
```

### `isLeapYear(year)`
Checks if year is a leap year.

**Parameters:**
- `year` (number): Year to check

**Returns:** boolean - True if leap year

**Example:**
```javascript
isLeapYear(2024); // true
isLeapYear(2023); // false
```

---

## Number & Currency Utilities

### `formatCurrency(amount, currency)`
Formats number as currency.

**Parameters:**
- `amount` (number): Amount to format
- `currency` (string): Currency code (default: 'USD')

**Returns:** string - Formatted currency

**Example:**
```javascript
formatCurrency(1234.56, 'USD'); // '$1,234.56'
formatCurrency(1234.56, 'EUR'); // '€1,234.56'
```

### `clamp(num, min, max)`
Clamps number between min and max values.

**Parameters:**
- `num` (number): Number to clamp
- `min` (number): Minimum value
- `max` (number): Maximum value

**Returns:** number - Clamped number

**Example:**
```javascript
clamp(15, 0, 10); // 10
clamp(-5, 0, 10); // 0
clamp(5, 0, 10); // 5
```

### `roundTo(num, decimals)`
Rounds number to specified decimal places.

**Parameters:**
- `num` (number): Number to round
- `decimals` (number): Number of decimal places

**Returns:** number - Rounded number

**Example:**
```javascript
roundTo(3.14159, 2); // 3.14
```

### `percentage(value, total)`
Calculates percentage of value relative to total.

**Parameters:**
- `value` (number): Value
- `total` (number): Total

**Returns:** number - Percentage

**Example:**
```javascript
percentage(25, 100); // 25
```

### `average(numbers)`
Calculates average of array of numbers.

**Parameters:**
- `numbers` (Array): Array of numbers

**Returns:** number - Average

**Example:**
```javascript
average([1, 2, 3, 4, 5]); // 3
```

### `sum(numbers)`
Calculates sum of array of numbers.

**Parameters:**
- `numbers` (Array): Array of numbers

**Returns:** number - Sum

**Example:**
```javascript
sum([1, 2, 3, 4, 5]); // 15
```

### `factorial(n)`
Calculates factorial of a number.

**Parameters:**
- `n` (number): Number to calculate factorial for

**Returns:** number - Factorial

**Example:**
```javascript
factorial(5); // 120
```

### `isPrime(num)`
Checks if number is prime.

**Parameters:**
- `num` (number): Number to check

**Returns:** boolean - True if prime

**Example:**
```javascript
isPrime(17); // true
isPrime(18); // false
```

### `gcd(a, b)`, `lcm(a, b)`
Calculates greatest common divisor and least common multiple.

**Parameters:**
- `a` (number): First number
- `b` (number): Second number

**Returns:** number - GCD or LCM

**Example:**
```javascript
gcd(12, 18); // 6
lcm(12, 18); // 36
```

### `median(numbers)`, `mode(numbers)`, `standardDeviation(numbers)`
Statistical functions for arrays of numbers.

**Parameters:**
- `numbers` (Array): Array of numbers

**Returns:** number|Array - Statistical result

**Example:**
```javascript
median([1, 2, 3, 4, 5]); // 3
mode([1, 2, 2, 3, 3, 3]); // [3]
standardDeviation([1, 2, 3, 4, 5]); // 1.58...
```

---

## ID Generation

### `generateId(length)`
Generates random alphanumeric ID.

**Parameters:**
- `length` (number): Length of ID (default: 8)

**Returns:** string - Random ID

**Example:**
```javascript
generateId(12); // 'aB3dE5fG7hI9'
```

### `generateUUID()`
Generates RFC4122 compliant UUID.

**Returns:** string - UUID

**Example:**
```javascript
generateUUID(); // '550e8400-e29b-41d4-a716-446655440000'
```

### `generateSlug()`
Generates human-readable slug.

**Returns:** string - Random slug

**Example:**
```javascript
generateSlug(); // 'amazing-project-123'
```

### `generatePassword(length, includeSymbols)`
Generates secure password.

**Parameters:**
- `length` (number): Password length (default: 12)
- `includeSymbols` (boolean): Include symbols (default: true)

**Returns:** string - Generated password

**Example:**
```javascript
generatePassword(16, true); // 'aB3$dE5!fG7@hI9#'
```

### `generateOTP(length)`
Generates numeric one-time password.

**Parameters:**
- `length` (number): OTP length (default: 6)

**Returns:** string - Numeric OTP

**Example:**
```javascript
generateOTP(6); // '123456'
```

---

## Storage Utilities

### `storage.set(key, value)`, `storage.get(key, defaultValue)`, `storage.remove(key)`, `storage.clear()`
LocalStorage utilities with JSON serialization.

**Example:**
```javascript
storage.set('user', { name: 'John', age: 30 });
storage.get('user'); // { name: 'John', age: 30 }
storage.remove('user');
storage.clear();
```

### `storage.exists(key)`, `storage.size()`, `storage.keys()`, `storage.getSize()`
Additional storage utilities.

**Example:**
```javascript
storage.exists('user'); // true/false
storage.size(); // Number of items
storage.keys(); // Array of keys
storage.getSize(); // Total size in characters
```

---

## DOM Utilities

### `copyToClipboard(text)`
Copies text to clipboard.

**Parameters:**
- `text` (string): Text to copy

**Returns:** Promise<boolean> - Success status

**Example:**
```javascript
await copyToClipboard('Hello World'); // true
```

### `scrollToTop(smooth)`, `scrollToElement(element, smooth)`
Scroll utilities.

**Parameters:**
- `smooth` (boolean): Use smooth scrolling (default: true)
- `element` (HTMLElement): Element to scroll to

**Example:**
```javascript
scrollToTop(true);
scrollToElement(document.getElementById('section'), true);
```

### `isElementInViewport(element)`
Checks if element is visible in viewport.

**Parameters:**
- `element` (HTMLElement): Element to check

**Returns:** boolean - True if in viewport

**Example:**
```javascript
isElementInViewport(document.getElementById('myElement')); // true/false
```

### `getViewportSize()`
Gets viewport dimensions.

**Returns:** Object - `{ width: number, height: number }`

**Example:**
```javascript
getViewportSize(); // { width: 1920, height: 1080 }
```

### `isMobile()`, `isTablet()`, `isDesktop()`
Device type detection.

**Returns:** boolean - Device type

**Example:**
```javascript
isMobile(); // true on mobile devices
isTablet(); // true on tablets
isDesktop(); // true on desktop
```

---

## Color Utilities

### `hexToRgb(hex)`, `rgbToHex(r, g, b)`
Convert between hex and RGB color formats.

**Example:**
```javascript
hexToRgb('#ff0000'); // { r: 255, g: 0, b: 0 }
rgbToHex(255, 0, 0); // '#ff0000'
```

### `generateRandomColor()`
Generates random hex color.

**Returns:** string - Random hex color

**Example:**
```javascript
generateRandomColor(); // '#a3b5c7'
```

### `lightenColor(hex, percent)`, `darkenColor(hex, percent)`
Lighten or darken a color by percentage.

**Parameters:**
- `hex` (string): Hex color
- `percent` (number): Percentage to lighten/darken

**Returns:** string - Modified hex color

**Example:**
```javascript
lightenColor('#ff0000', 20); // '#ff3333'
darkenColor('#ff0000', 20); // '#cc0000'
```

### `getContrastColor(hex)`
Gets contrasting color (black or white) for given color.

**Parameters:**
- `hex` (string): Hex color

**Returns:** string - Contrasting color

**Example:**
```javascript
getContrastColor('#000000'); // '#ffffff'
getContrastColor('#ffffff'); // '#000000'
```

---

## URL & Query Utilities

### `getQueryParams(url)`, `setQueryParam(key, value)`, `removeQueryParam(key)`
URL query parameter utilities.

**Example:**
```javascript
getQueryParams('?name=John&age=30'); // { name: 'John', age: '30' }
setQueryParam('theme', 'dark'); // Updates URL
removeQueryParam('theme'); // Removes from URL
```

### `buildUrl(base, params)`
Builds URL with query parameters.

**Parameters:**
- `base` (string): Base URL
- `params` (Object): Query parameters

**Returns:** string - Complete URL

**Example:**
```javascript
buildUrl('https://api.example.com', { q: 'search', limit: 10 });
// 'https://api.example.com?q=search&limit=10'
```

### `parseUrl(url)`
Parses URL into components.

**Parameters:**
- `url` (string): URL to parse

**Returns:** Object - URL components

**Example:**
```javascript
parseUrl('https://example.com:8080/path?q=search#section');
// { protocol: 'https:', hostname: 'example.com', port: '8080', ... }
```

---

## File & Data Utilities

### `formatFileSize(bytes)`
Formats file size in human-readable format.

**Parameters:**
- `bytes` (number): File size in bytes

**Returns:** string - Formatted size

**Example:**
```javascript
formatFileSize(1024); // '1 KB'
formatFileSize(1048576); // '1 MB'
```

### `downloadFile(data, filename, type)`
Downloads data as file.

**Parameters:**
- `data` (string): File data
- `filename` (string): File name
- `type` (string): MIME type (default: 'text/plain')

**Example:**
```javascript
downloadFile('Hello World', 'hello.txt', 'text/plain');
```

### `base64Encode(str)`, `base64Decode(str)`
Base64 encoding/decoding utilities.

**Example:**
```javascript
base64Encode('Hello World'); // 'SGVsbG8gV29ybGQ='
base64Decode('SGVsbG8gV29ybGQ='); // 'Hello World'
```

### `csvToArray(csv)`, `arrayToCsv(data)`
CSV parsing and generation utilities.

**Example:**
```javascript
csvToArray('name,age\nJohn,30\nJane,25');
// [['name', 'age'], ['John', '30'], ['Jane', '25']]

arrayToCsv([['name', 'age'], ['John', '30']]);
// 'name,age\nJohn,30'
```

---

## Async Utilities

### `sleep(ms)`
Pauses execution for specified milliseconds.

**Parameters:**
- `ms` (number): Milliseconds to sleep

**Returns:** Promise<void>

**Example:**
```javascript
await sleep(1000); // Wait 1 second
```

### `retry(fn, maxAttempts, delay)`
Retries async function with exponential backoff.

**Parameters:**
- `fn` (Function): Async function to retry
- `maxAttempts` (number): Maximum attempts (default: 3)
- `delay` (number): Initial delay in ms (default: 1000)

**Returns:** Promise - Function result

**Example:**
```javascript
const result = await retry(async () => {
  const response = await fetch('/api/data');
  if (!response.ok) throw new Error('Failed');
  return response.json();
}, 3, 1000);
```

### `timeout(promise, ms)`
Adds timeout to promise.

**Parameters:**
- `promise` (Promise): Promise to timeout
- `ms` (number): Timeout in milliseconds

**Returns:** Promise - Promise with timeout

**Example:**
```javascript
const result = await timeout(fetch('/api/slow'), 5000);
```

### `batchProcess(items, processor, batchSize)`
Processes array items in batches.

**Parameters:**
- `items` (Array): Items to process
- `processor` (Function): Async processor function
- `batchSize` (number): Batch size (default: 10)

**Returns:** Promise<Array> - Processed results

**Example:**
```javascript
const results = await batchProcess(
  [1, 2, 3, 4, 5],
  async (item) => item * 2,
  2
); // [2, 4, 6, 8, 10]
```

---

## Type Checking Utilities

### `isString(value)`, `isNumber(value)`, `isBoolean(value)`, `isArray(value)`, `isObject(value)`, `isFunction(value)`, `isDate(value)`
Type checking utilities.

**Example:**
```javascript
isString('hello'); // true
isNumber(42); // true
isArray([1, 2, 3]); // true
isObject({ a: 1 }); // true
```

### `isEmpty(value)`
Checks if value is empty (null, undefined, empty string, array, or object).

**Parameters:**
- `value` (any): Value to check

**Returns:** boolean - True if empty

**Example:**
```javascript
isEmpty(''); // true
isEmpty([]); // true
isEmpty({}); // true
isEmpty(null); // true
```

### `getType(value)`
Gets detailed type of value.

**Parameters:**
- `value` (any): Value to get type of

**Returns:** string - Type name

**Example:**
```javascript
getType([]); // 'array'
getType(new Date()); // 'date'
getType(/regex/); // 'regexp'
```

---

## Browser & Environment Utilities

### `getBrowserInfo()`
Gets browser information.

**Returns:** Object - `{ name: string, version: string, platform: string }`

**Example:**
```javascript
getBrowserInfo(); // { name: 'Chrome', version: '91', platform: 'Win32' }
```

### `getDeviceInfo()`
Gets device information.

**Returns:** Object - Device details

**Example:**
```javascript
getDeviceInfo();
// { type: 'desktop', os: 'Windows', screen: { width: 1920, height: 1080 } }
```

### `supportsFeature(feature)`
Checks if browser supports specific feature.

**Parameters:**
- `feature` (string): Feature name

**Returns:** boolean - True if supported

**Example:**
```javascript
supportsFeature('localStorage'); // true
supportsFeature('geolocation'); // true/false
```

---

## Event System

### `createEventEmitter()`
Creates custom event emitter for decoupled communication.

**Returns:** Object - Event emitter with on, off, emit, once methods

**Example:**
```javascript
const emitter = createEventEmitter();

emitter.on('user:login', (user) => {
  console.log('User logged in:', user);
});

emitter.emit('user:login', { id: 1, name: 'John' });

emitter.once('app:init', () => {
  console.log('App initialized'); // Only fires once
});
```

---

## Caching System

### `createCache(maxSize)`
Creates intelligent cache with TTL support and size limits.

**Parameters:**
- `maxSize` (number): Maximum cache size (default: 100)

**Returns:** Object - Cache with set, get, has, delete, clear, size methods

**Example:**
```javascript
const cache = createCache(50);

// Set with 5 second TTL
cache.set('user:1', userData, 5000);

// Get cached data
const user = cache.get('user:1'); // Returns data or null if expired

// Check if exists and not expired
cache.has('user:1'); // true/false

// Cache size
cache.size(); // Current number of items
```

---

## Functional Programming

### `pipe(...fns)`
Pipes value through sequence of functions (left to right).

**Parameters:**
- `fns` (Function[]): Functions to pipe through

**Returns:** Function - Piped function

**Example:**
```javascript
const add5 = x => x + 5;
const multiply2 = x => x * 2;
const square = x => x * x;

const pipeline = pipe(add5, multiply2, square);
pipeline(3); // ((3 + 5) * 2)² = 256
```

### `compose(...fns)`
Composes functions (right to left).

**Parameters:**
- `fns` (Function[]): Functions to compose

**Returns:** Function - Composed function

**Example:**
```javascript
const add5 = x => x + 5;
const multiply2 = x => x * 2;

const composed = compose(multiply2, add5);
composed(3); // (3 + 5) * 2 = 16
```

### `curry(fn)`
Converts function to curried version for partial application.

**Parameters:**
- `fn` (Function): Function to curry

**Returns:** Function - Curried function

**Example:**
```javascript
const add = (a, b, c) => a + b + c;
const curriedAdd = curry(add);

const add5 = curriedAdd(5);
const add5And3 = add5(3);
add5And3(2); // 10
```

### `partial(fn, ...partialArgs)`
Creates partially applied function.

**Parameters:**
- `fn` (Function): Function to partially apply
- `partialArgs` (any[]): Arguments to pre-fill

**Returns:** Function - Partially applied function

**Example:**
```javascript
const multiply = (a, b, c) => a * b * c;
const multiplyBy2 = partial(multiply, 2);
multiplyBy2(3, 4); // 24
```

---

## Data Structures

### `createQueue()`
Creates queue data structure (FIFO).

**Returns:** Object - Queue with enqueue, dequeue, peek, isEmpty, size, clear methods

**Example:**
```javascript
const queue = createQueue();
queue.enqueue('first');
queue.enqueue('second');
queue.dequeue(); // 'first'
queue.peek(); // 'second'
queue.isEmpty(); // false
```

### `createStack()`
Creates stack data structure (LIFO).

**Returns:** Object - Stack with push, pop, peek, isEmpty, size, clear methods

**Example:**
```javascript
const stack = createStack();
stack.push('bottom');
stack.push('top');
stack.pop(); // 'top'
stack.peek(); // 'bottom'
```

---

## Geolocation

### `getCurrentPosition()`
Gets user's current geographic position.

**Returns:** Promise<GeolocationPosition> - Position data

**Example:**
```javascript
try {
  const position = await getCurrentPosition();
  console.log(position.coords.latitude, position.coords.longitude);
} catch (error) {
  console.error('Geolocation error:', error);
}
```

### `calculateDistance(lat1, lon1, lat2, lon2)`
Calculates distance between two geographic points using Haversine formula.

**Parameters:**
- `lat1`, `lon1` (number): First point coordinates
- `lat2`, `lon2` (number): Second point coordinates

**Returns:** number - Distance in kilometers

**Example:**
```javascript
const distance = calculateDistance(
  40.7128, -74.0060, // New York
  34.0522, -118.2437  // Los Angeles
); // ~3944 km
```

---

## Performance Monitoring

### `measurePerformance(fn, label)`
Measures synchronous function execution time.

**Parameters:**
- `fn` (Function): Function to measure
- `label` (string): Optional label for logging

**Returns:** any - Function result

**Example:**
```javascript
const result = measurePerformance(() => {
  // Expensive computation
  return heavyCalculation();
}, 'Heavy Calculation'); // Logs: "Heavy Calculation: 123.45ms"
```

### `measureAsyncPerformance(fn, label)`
Measures asynchronous function execution time.

**Parameters:**
- `fn` (Function): Async function to measure
- `label` (string): Optional label for logging

**Returns:** Promise<any> - Function result

**Example:**
```javascript
const result = await measureAsyncPerformance(async () => {
  return await fetch('/api/data').then(r => r.json());
}, 'API Call'); // Logs: "API Call: 456.78ms"
```

---

## Network Utilities

### `fetchWithTimeout(url, options, timeoutMs)`
Fetch with timeout support.

**Parameters:**
- `url` (string): URL to fetch
- `options` (Object): Fetch options
- `timeoutMs` (number): Timeout in milliseconds (default: 5000)

**Returns:** Promise<Response> - Fetch response

**Example:**
```javascript
const response = await fetchWithTimeout('/api/data', {}, 3000);
```

### `fetchWithRetry(url, options, maxRetries)`
Fetch with automatic retry on failure.

**Parameters:**
- `url` (string): URL to fetch
- `options` (Object): Fetch options
- `maxRetries` (number): Maximum retry attempts (default: 3)

**Returns:** Promise<Response> - Fetch response

**Example:**
```javascript
const response = await fetchWithRetry('/api/unreliable', {}, 5);
```

### `isOnline()`
Checks if browser is online.

**Returns:** boolean - Online status

**Example:**
```javascript
if (isOnline()) {
  // Make network requests
}
```

### `getConnectionType()`
Gets connection type information.

**Returns:** string - Connection type ('4g', '3g', 'wifi', etc.)

**Example:**
```javascript
const connectionType = getConnectionType(); // '4g'
```

---

## Security Utilities

### `sanitizeInput(input)`
Sanitizes user input to prevent XSS attacks.

**Parameters:**
- `input` (string): Input to sanitize

**Returns:** string - Sanitized input

**Example:**
```javascript
sanitizeInput('<script>alert("xss")</script>Hello');
// 'Hello' (script tags removed)
```

### `generateSecureToken(length)`
Generates cryptographically secure random token.

**Parameters:**
- `length` (number): Token length (default: 32)

**Returns:** string - Secure token

**Example:**
```javascript
const token = generateSecureToken(64);
// 'a1b2c3d4e5f6...' (64 character secure token)
```

### `hashString(str)`
Creates SHA-256 hash of string.

**Parameters:**
- `str` (string): String to hash

**Returns:** Promise<string> - SHA-256 hash

**Example:**
```javascript
const hash = await hashString('password123');
// 'ef92b778bafe771e89245b89ecbc08a44a4e166c06659911881f383d4473e94f'
```

---

## Accessibility Utilities

### `announceToScreenReader(message)`
Announces message to screen readers.

**Parameters:**
- `message` (string): Message to announce

**Example:**
```javascript
announceToScreenReader('Form submitted successfully');
```

### `trapFocus(element)`
Traps keyboard focus within specified element.

**Parameters:**
- `element` (HTMLElement): Element to trap focus in

**Returns:** Function - Cleanup function

**Example:**
```javascript
const modal = document.getElementById('modal');
const cleanup = trapFocus(modal);

// Later, when modal closes:
cleanup();
```

---

## Usage Examples

### Complete Example: User Management System

```javascript
import {
  validateEmail,
  generateId,
  formatDate,
  storage,
  createEventEmitter,
  sanitizeInput,
  debounce
} from './utils';

class UserManager {
  constructor() {
    this.users = storage.get('users', []);
    this.emitter = createEventEmitter();
    
    // Debounced search
    this.search = debounce(this.performSearch.bind(this), 300);
  }
  
  addUser(userData) {
    // Validate and sanitize input
    if (!validateEmail(userData.email)) {
      throw new Error('Invalid email');
    }
    
    const user = {
      id: generateId(12),
      name: sanitizeInput(userData.name),
      email: userData.email,
      createdAt: formatDate(new Date(), 'iso')
    };
    
    this.users.push(user);
    storage.set('users', this.users);
    
    // Emit event
    this.emitter.emit('user:added', user);
    
    return user;
  }
  
  performSearch(query) {
    const results = this.users.filter(user => 
      user.name.toLowerCase().includes(query.toLowerCase()) ||
      user.email.toLowerCase().includes(query.toLowerCase())
    );
    
    this.emitter.emit('search:results', results);
  }
  
  onUserAdded(callback) {
    this.emitter.on('user:added', callback);
  }
}

// Usage
const userManager = new UserManager();

userManager.onUserAdded((user) => {
  console.log('New user added:', user);
});

userManager.addUser({
  name: 'John Doe',
  email: 'john@example.com'
});
```

This comprehensive documentation covers all utility functions in the library with detailed explanations, parameters, return values, and practical examples. Each function is designed to be production-ready and can be used independently or combined for complex operations.