npm package: @mdigital_ui/utils
Description: Functional programming utilities and React hooks for modern web development
Author: Mr.Luke
Latest version: 1.0.3

# @mdigital_ui/utils

Functional programming utilities and React hooks for modern web development.

## Installation

```bash
pnpm add @mdigital_ui/utils
```

## Requirements

- React 19.0.0 or higher
- Modern bundler with ESM support (Vite, Next.js 13+, etc.)

## Features

- Full functional programming suite (currying, composition, immutable operations)
- React 19+ hooks and utilities
- Tree-shakeable ESM modules
- Full TypeScript support with excellent type inference
- Category-based imports

## Usage

### Full Import

```typescript
import { map, filter, compose, useDebounce, useToggle } from '@mdigital_ui/utils';
```

### Category Import

```typescript
import * as array from '@mdigital_ui/utils/array';
import * as object from '@mdigital_ui/utils/object';
import { useDebounce, useLocalStorage } from '@mdigital_ui/utils/react';
import * as file from '@mdigital_ui/utils/file';
import { validateFileSize } from '@mdigital_ui/utils/validation';
```

## Categories

### Array Utilities

Immutable array operations for functional programming.

```typescript
import { map, filter, reduce, groupBy, uniq } from '@mdigital_ui/utils/array';

// Transform arrays
const doubled = map(x => x * 2, [1, 2, 3]); // [2, 4, 6]

// Filter with predicates
const evens = filter(x => x % 2 === 0, [1, 2, 3, 4]); // [2, 4]

// Group by criteria
const grouped = groupBy(x => x % 2 === 0 ? 'even' : 'odd', [1, 2, 3, 4]);
// { odd: [1, 3], even: [2, 4] }

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

**Available Functions:**
`map`, `filter`, `reduce`, `take`, `drop`, `groupBy`, `partition`, `flatten`, `flatMap`, `uniq`, `uniqBy`

### Object Utilities

Immutable object operations for data manipulation.

```typescript
import { pick, omit, merge, path, clone } from '@mdigital_ui/utils/object';

// Pick specific properties
const user = pick(['name', 'email'], { name: 'John', email: 'john@example.com', age: 30 });
// { name: 'John', email: 'john@example.com' }

// Omit properties
const publicUser = omit(['password'], { name: 'John', password: 'secret' });
// { name: 'John' }

// Safe path access
const value = path(['user', 'address', 'city'], data); // Safely access nested properties

// Property access (Ramda-style)
const getName = prop('name');
getName({ name: 'Alice', age: 30 }); // 'Alice'

// Property access with default
const getAge = propOr(0, 'age');
getAge({ name: 'Alice' }); // 0 (default)
getAge({ name: 'Bob', age: 25 }); // 25

// Deep cloning
const cloned = cloneDeep(complexObject);
```

**Available Functions:**
`pick`, `omit`, `merge`, `mergeDeep`, `clone`, `cloneDeep`, `keys`, `values`, `entries`, `path`, `pathOr`, `prop`, `propOr`

### Function Utilities

Function composition, currying, and higher-order utilities.

```typescript
import { pipe, compose, curry2, memoize } from '@mdigital_ui/utils/function';

// Pipe functions left to right
const transform = pipe(
  (x: number) => x + 1,
  (x: number) => x * 2,
  (x: number) => x.toString()
);
transform(3); // '8'

// Compose functions right to left
const calculate = compose(
  (x: number) => x * 2,
  (x: number) => x + 1
);
calculate(3); // 8

// Curry functions
const add = curry2((a: number, b: number) => a + b);
const add5 = add(5);
add5(10); // 15

// Memoize expensive functions
const expensive = memoize((n: number) => {
  // expensive computation
  return result;
});
```

**Available Functions:**
`curry2`, `curry3`, `curry4`, `compose`, `pipe`, `partial`, `memoize`

### Logic Utilities

Functional logic operations and conditional utilities.

```typescript
import { cond, ifElse, and, or, not } from '@mdigital_ui/utils/logic';

// Conditional logic
const classify = cond([
  [(x: number) => x < 0, () => 'negative'],
  [(x: number) => x === 0, () => 'zero'],
  [(x: number) => x > 0, () => 'positive']
]);
classify(-5); // 'negative'

// If-else as a function
const abs = ifElse(
  (x: number) => x >= 0,
  (x: number) => x,
  (x: number) => -x
);
abs(-5); // 5
```

**Available Functions:**
`and`, `or`, `not`, `cond`, `ifElse`

### Math Utilities

Mathematical operations and calculations.

```typescript
import { add, multiply, clamp, sum, mean } from '@mdigital_ui/utils/math';

// Basic operations
add(2, 3); // 5
multiply(3, 4); // 12

// Clamp values
clamp(0, 10, 15); // 10
clamp(0, 10, 5); // 5

// Array operations
sum([1, 2, 3, 4]); // 10
mean([1, 2, 3, 4]); // 2.5
```

**Available Functions:**
`add`, `subtract`, `multiply`, `divide`, `clamp`, `sum`, `mean`

### String Utilities

String manipulation and transformation utilities.

```typescript
import { capitalize, split, replace } from '@mdigital_ui/utils/string';

// Capitalize strings
capitalize('hello'); // 'Hello'

// Split strings
split(',', 'a,b,c'); // ['a', 'b', 'c']

// Replace patterns
replace(/o/g, 'a', 'hello'); // 'hella'
```

**Available Functions:**
`trim`, `split`, `capitalize`, `toLower`, `toUpper`, `replace`

### React Hooks

Custom React 19+ hooks for common patterns.

```typescript
import {
  useDebounce,
  useToggle,
  useLocalStorage,
  useClickOutside,
  useMediaQuery
} from '@mdigital_ui/utils/react';

// Debounce values
function SearchInput() {
  const [search, setSearch] = useState('');
  const debouncedSearch = useDebounce(search, 300);

  useEffect(() => {
    // API call with debounced value
    fetchResults(debouncedSearch);
  }, [debouncedSearch]);

  return <input value={search} onChange={e => setSearch(e.target.value)} />;
}

// Toggle state
function Modal() {
  const [isOpen, toggle] = useToggle(false);

  return (
    <>
      <button onClick={toggle}>Open Modal</button>
      {isOpen && <div>Modal Content</div>}
    </>
  );
}

// Persistent storage
function ThemeSelector() {
  const [theme, setTheme] = useLocalStorage('theme', 'light');

  return (
    <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
      Current: {theme}
    </button>
  );
}

// Click outside detection
function Dropdown() {
  const [isOpen, setIsOpen] = useState(false);
  const ref = useClickOutside<HTMLDivElement>(() => setIsOpen(false));

  return (
    <div ref={ref}>
      <button onClick={() => setIsOpen(!isOpen)}>Toggle</button>
      {isOpen && <div>Dropdown Content</div>}
    </div>
  );
}

// Media queries
function ResponsiveComponent() {
  const isMobile = useMediaQuery('(max-width: 768px)');

  return <div>{isMobile ? 'Mobile View' : 'Desktop View'}</div>;
}
```

**Available Hooks:**
`useDebounce`, `useThrottle`, `useLocalStorage`, `useSessionStorage`, `usePrevious`, `useToggle`, `useClickOutside`, `useMediaQuery`, `useIntersectionObserver`, `useMountEffect`, `useUpdateEffect`

### React Utilities

Helper utilities for React development.

```typescript
import { cn, createContext } from '@mdigital_ui/utils/react';

// Conditional classnames
const buttonClass = cn(
  'btn',
  isPrimary && 'btn-primary',
  isDisabled && 'btn-disabled'
);

// Type-safe context
const [ThemeProvider, useTheme] = createContext<{ theme: string }>('Theme');

function App() {
  return (
    <ThemeProvider value={{ theme: 'dark' }}>
      <Child />
    </ThemeProvider>
  );
}

function Child() {
  const { theme } = useTheme(); // Type-safe!
  return <div>{theme}</div>;
}
```

**Available Utilities:**
`cn` (classname concatenation), `createContext` (type-safe context)

## TypeScript Support

All functions and hooks are fully typed with TypeScript. The library provides excellent type inference:

```typescript
import { map, pipe } from '@mdigital_ui/utils';

// Type inference works automatically
const numbers = [1, 2, 3];
const strings = map(x => x.toString(), numbers); // string[]

// Complex type inference
const transform = pipe(
  (x: number) => x + 1,    // number -> number
  (x: number) => x * 2,    // number -> number
  (x: number) => String(x) // number -> string
);
const result = transform(5); // string
```

## Tree Shaking

The library is fully tree-shakeable. Only import what you need:

```typescript
// Only bundles the map function
import { map } from '@mdigital_ui/utils';

// Only bundles array utilities
import * as array from '@mdigital_ui/utils/array';
```

## License

MIT

## Contributing

Contributions are welcome! Please feel free to submit issues and pull requests.