npm package: @j471n/helpers-utils
Description: A comprehensive TypeScript utility library with modular helper functions for arrays, objects, strings, dates, validation, and more
Author: Jatin Sharma
Latest version: 1.0.0

# @helpers/utils

A comprehensive TypeScript utility library with modular helper functions for arrays, objects, strings, dates, validation, async operations, and math calculations.

[![npm version](https://badge.fury.io/js/@helpers/utils.svg)](https://badge.fury.io/js/@helpers/utils)
[![Build Status](https://github.com/yourusername/helpers/workflows/CI/badge.svg)](https://github.com/yourusername/helpers/actions)
[![Coverage Status](https://coveralls.io/repos/github/yourusername/helpers/badge.svg?branch=main)](https://coveralls.io/github/yourusername/helpers?branch=main)
[![TypeScript](https://img.shields.io/badge/%3C%2F%3E-TypeScript-%230074c1.svg)](http://www.typescriptlang.org/)

## Features

- 🔥 **Tree-shakeable**: Import only what you need
- 📘 **TypeScript**: Full type safety with excellent IntelliSense
- 🧪 **Well tested**: Comprehensive test coverage
- 📦 **Zero dependencies**: No external runtime dependencies
- 🌍 **Universal**: Works in Node.js and browsers
- 📖 **Well documented**: JSDoc comments for all functions

## Installation

```bash
npm install @helpers/utils
```

```bash
yarn add @helpers/utils
```

```bash
pnpm add @helpers/utils
```

## Usage

### Import Everything

```typescript
import * as utils from '@helpers/utils';

const chunked = utils.chunk([1, 2, 3, 4, 5], 2);
const cloned = utils.deepClone({ a: { b: 1 } });
```

### Import Individual Functions (Recommended)

```typescript
import { chunk, deepClone, debounce } from '@helpers/utils';

const chunked = chunk([1, 2, 3, 4, 5], 2);
const cloned = deepClone({ a: { b: 1 } });
const debouncedFn = debounce(myFunction, 300);
```

### Import by Category

```typescript
import { chunk, flatten, unique } from '@helpers/utils/array';
import { deepClone, pick, omit } from '@helpers/utils/object';
import { camelCase, slugify } from '@helpers/utils/string';
```

## API Documentation

### Array Functions

| Function                | Description              | Example                                  |
| ----------------------- | ------------------------ | ---------------------------------------- |
| `chunk(array, size)`    | Split array into chunks  | `chunk([1,2,3,4], 2)` → `[[1,2], [3,4]]` |
| `flatten(array)`        | Flatten array one level  | `flatten([[1,2], [3,4]])` → `[1,2,3,4]`  |
| `unique(array)`         | Remove duplicates        | `unique([1,1,2,3])` → `[1,2,3]`          |
| `groupBy(array, keyFn)` | Group by key function    | `groupBy(users, u => u.role)`            |
| `shuffle(array)`        | Randomly shuffle array   | `shuffle([1,2,3])` → `[3,1,2]`           |
| `sample(array, count)`  | Random sample from array | `sample([1,2,3,4], 2)` → `[3,1]`         |

### Object Functions

| Function                        | Description         | Example                             |
| ------------------------------- | ------------------- | ----------------------------------- |
| `deepClone(obj)`                | Deep clone object   | `deepClone({a: {b: 1}})`            |
| `deepMerge(target, ...sources)` | Deep merge objects  | `deepMerge({a: 1}, {b: 2})`         |
| `pick(obj, keys)`               | Pick properties     | `pick({a:1, b:2}, ['a'])` → `{a:1}` |
| `omit(obj, keys)`               | Omit properties     | `omit({a:1, b:2}, ['b'])` → `{a:1}` |
| `get(obj, path, defaultValue)`  | Get nested property | `get(obj, 'a.b.c', 'default')`      |
| `set(obj, path, value)`         | Set nested property | `set(obj, 'a.b.c', 42)`             |

### String Functions

| Function                        | Description              | Example                                     |
| ------------------------------- | ------------------------ | ------------------------------------------- |
| `camelCase(str)`                | Convert to camelCase     | `camelCase('hello-world')` → `'helloWorld'` |
| `kebabCase(str)`                | Convert to kebab-case    | `kebabCase('helloWorld')` → `'hello-world'` |
| `snakeCase(str)`                | Convert to snake_case    | `snakeCase('helloWorld')` → `'hello_world'` |
| `capitalize(str)`               | Capitalize first letter  | `capitalize('hello')` → `'Hello'`           |
| `truncate(str, length, suffix)` | Truncate string          | `truncate('Hello World', 5)` → `'Hello...'` |
| `slugify(str)`                  | Create URL-friendly slug | `slugify('Hello World!')` → `'hello-world'` |

### Date Functions

| Function                   | Description          | Example                                  |
| -------------------------- | -------------------- | ---------------------------------------- |
| `formatDate(date, format)` | Format date          | `formatDate(date, 'YYYY-MM-DD')`         |
| `addDays(date, days)`      | Add days to date     | `addDays(date, 7)`                       |
| `diffDays(date1, date2)`   | Days between dates   | `diffDays(date1, date2)`                 |
| `isWeekend(date)`          | Check if weekend     | `isWeekend(date)` → `true/false`         |
| `getQuarter(date)`         | Get quarter of year  | `getQuarter(date)` → `1-4`               |
| `formatRelative(date)`     | Relative time format | `formatRelative(date)` → `'2 hours ago'` |

### Async Functions

| Function                     | Description             | Example                        |
| ---------------------------- | ----------------------- | ------------------------------ |
| `debounce(fn, delay)`        | Debounce function calls | `debounce(handleInput, 300)`   |
| `throttle(fn, limit)`        | Throttle function calls | `throttle(handleScroll, 100)`  |
| `delay(ms)`                  | Promise-based delay     | `await delay(1000)`            |
| `retry(fn, attempts, delay)` | Retry with backoff      | `await retry(fetchData, 3)`    |
| `timeout(promise, ms)`       | Add timeout to promise  | `await timeout(fetch(), 5000)` |

### Validation Functions

| Function               | Description           | Example                                    |
| ---------------------- | --------------------- | ------------------------------------------ |
| `isEmail(str)`         | Validate email        | `isEmail('user@domain.com')` → `true`      |
| `isUrl(str)`           | Validate URL          | `isUrl('https://example.com')` → `true`    |
| `isEmpty(value)`       | Check if empty        | `isEmpty([])` → `true`                     |
| `isPlainObject(value)` | Check if plain object | `isPlainObject({})` → `true`               |
| `isPromise(value)`     | Check if Promise      | `isPromise(Promise.resolve())` → `true`    |
| `isValidJSON(str)`     | Validate JSON string  | `isValidJSON('{"key": "value"}')` → `true` |

### Math Functions

| Function                   | Description                    | Example                        |
| -------------------------- | ------------------------------ | ------------------------------ |
| `clamp(value, min, max)`   | Clamp number between bounds    | `clamp(10, 0, 5)` → `5`        |
| `randomBetween(min, max)`  | Random number in range         | `randomBetween(1, 10)` → `7`   |
| `roundTo(value, decimals)` | Round to decimal places        | `roundTo(3.14159, 2)` → `3.14` |
| `formatBytes(bytes)`       | Format bytes to human readable | `formatBytes(1024)` → `'1 KB'` |
| `percentage(value, total)` | Calculate percentage           | `percentage(25, 100)` → `25`   |

## Examples

### Working with Arrays

```typescript
import { chunk, groupBy, unique } from '@helpers/utils';

// Process data in chunks
const data = [1, 2, 3, 4, 5, 6, 7, 8];
const batches = chunk(data, 3);
// [[1, 2, 3], [4, 5, 6], [7, 8]]

// Group users by role
const users = [
  { name: 'Alice', role: 'admin' },
  { name: 'Bob', role: 'user' },
  { name: 'Carol', role: 'admin' },
];
const usersByRole = groupBy(users, user => user.role);
// { admin: [Alice, Carol], user: [Bob] }

// Remove duplicates
const uniqueNumbers = unique([1, 2, 2, 3, 3, 3]);
// [1, 2, 3]
```

### Async Operations

```typescript
import { debounce, retry, timeout } from '@helpers/utils';

// Debounce search input
const debouncedSearch = debounce(async (query: string) => {
  const results = await searchAPI(query);
  updateUI(results);
}, 300);

// Retry failed operations
const robustFetch = async (url: string) => {
  return retry(
    () => fetch(url).then(res => res.json()),
    3, // max attempts
    1000 // base delay
  );
};

// Add timeout to operations
const fetchWithTimeout = (url: string) => {
  return timeout(fetch(url), 5000, 'Request timed out');
};
```

### Object Manipulation

```typescript
import { deepClone, pick, get, set } from '@helpers/utils';

const config = {
  api: {
    endpoints: {
      users: '/api/users',
      posts: '/api/posts',
    },
    timeout: 5000,
  },
  ui: {
    theme: 'dark',
    language: 'en',
  },
};

// Safe deep cloning
const configCopy = deepClone(config);

// Extract specific fields
const apiConfig = pick(config, ['api']);

// Safe property access
const usersEndpoint = get(config, 'api.endpoints.users', '/api/default');

// Set nested properties
set(config, 'api.endpoints.comments', '/api/comments');
```

## TypeScript Support

This library is written in TypeScript and provides excellent type safety:

```typescript
import { groupBy, pick } from '@helpers/utils';

interface User {
  id: number;
  name: string;
  role: 'admin' | 'user';
}

const users: User[] = [
  { id: 1, name: 'Alice', role: 'admin' },
  { id: 2, name: 'Bob', role: 'user' },
];

// TypeScript knows the return type is Record<'admin' | 'user', User[]>
const grouped = groupBy(users, user => user.role);

// TypeScript ensures only valid keys are picked
const userSummaries = users.map(user => pick(user, ['id', 'name']));
```

## Performance

All functions are optimized for performance and memory efficiency:

- **Tree-shaking**: Only bundle functions you actually use
- **Zero dependencies**: No bloat from external libraries
- **Efficient algorithms**: Well-tested implementations
- **Memory conscious**: Minimal memory allocation where possible

## Browser Support

- Chrome ≥ 60
- Firefox ≥ 60
- Safari ≥ 12
- Edge ≥ 79
- Node.js ≥ 16

## Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

## License

MIT © [Your Name](https://github.com/yourusername)

---

## Development

### Setup

```bash
git clone https://github.com/yourusername/helpers.git
cd helpers
npm install
```

### Scripts

```bash
npm run build          # Build the library
npm run test           # Run tests
npm run test:watch     # Run tests in watch mode
npm run test:coverage  # Run tests with coverage
npm run lint           # Lint code
npm run format         # Format code
```

### Publishing

This project uses automated releases with semantic versioning. Simply push to main and the CI will handle versioning and publishing based on conventional commits.