npm package: @letmein_by10/arc-utils
Description: Utility library combining arc-debounce and arc-logger
Author: pizle0210
Latest version: 1.0.3

# @letmein_by10/arc-utils

A comprehensive utility library that combines the power of `@letmein_by10/arc-logger` and `@letmein_by10/arc-debounce` into a single, convenient package. Perfect for modern TypeScript/JavaScript applications.

## Features

- 🚀 **All-in-One**: Complete logging and timing utilities in one package
- 🎯 **Convenience API**: Single import with organized utility object
- 📦 **Re-exports**: Access all individual functions directly  
- 🔧 **Quick Setup**: Pre-configured instances ready to use
- 🎨 **Consistent API**: Unified interface across all utilities
- 📱 **Universal**: Works in Node.js and browsers
- 🌲 **Tree Shakeable**: Import only what you need
- 💪 **TypeScript First**: Full type safety and IntelliSense

## Installation

```bash
npm install @letmein_by10/arc-utils
# or
yarn add @letmein_by10/arc-utils
# or
pnpm add @letmein_by10/arc-utils
```

## Quick Start

### Using the Convenience API

```typescript
import { arc } from '@letmein_by10/arc-utils';

// Logging
arc.info('Application started');
arc.success('Operation completed');
arc.error('Something went wrong');

// Timing utilities
const debouncedFn = arc.debounce(() => console.log('Debounced!'), 300);
const throttledFn = arc.throttle(() => console.log('Throttled!'), 100);

// Quick aliases
const quickDebounce = arc.deb(() => console.log('Quick!'), 500);
const quickThrottle = arc.thr(() => console.log('Fast!'), 200);

// Create custom logger
const customLogger = arc.createLogger({
  prefix: '🚀 MyApp',
  level: arc.LogLevel.DEBUG
});
```

### Using Individual Imports

```typescript
// Import everything from both packages
import { 
  // Logger exports
  logger, ArcLogger, LogLevel,
  
  // Debounce exports  
  debounce, throttle, once, delay, sleep, rateLimit 
} from '@letmein_by10/arc-utils';

// Use them directly
const debouncedSearch = debounce(searchFunction, 300);
logger.info('Search function created');
```

## API Reference

### The `arc` Object

The main convenience object that provides quick access to all utilities:

```typescript
const arc = {
  // Logger utilities
  logger,              // Default logger instance
  ArcLogger,          // Logger class
  LogLevel,           // Log level enum
  log: logger,        // Alias for logger

  // Timing utilities
  debounce,           // Debounce function
  throttle,           // Throttle function  
  once,               // Once function
  delay,              // Delay function
  sleep,              // Sleep function
  rateLimit,          // Rate limit function

  // Convenience methods
  createLogger,       // Create new logger instance

  // Quick access functions
  info,               // logger.info shortcut
  error,              // logger.error shortcut
  warn,               // logger.warn shortcut
  success,            // logger.success shortcut
  debug,              // logger.debug shortcut

  // Quick aliases
  deb: debounce,      // Quick debounce alias
  thr: throttle,      // Quick throttle alias
};
```

## Examples

### Complete Application Setup

```typescript
import { arc } from '@letmein_by10/arc-utils';

// Configure application logger
const appLogger = arc.createLogger({
  prefix: '🚀 MyApp',
  level: arc.LogLevel.INFO,
  enableTimestamp: true
});

// Create debounced search function
const debouncedSearch = arc.debounce((query: string) => {
  appLogger.info(`Searching for: ${query}`);
  // Perform search...
}, 300);

// Create throttled scroll handler  
const throttledScroll = arc.throttle(() => {
  appLogger.debug('Scroll event handled');
  // Handle scroll...
}, 100);

// Rate-limited API calls
const limitedAPI = arc.rateLimit(async (data: any) => {
  appLogger.info('Making API call');
  return fetch('/api/data', {
    method: 'POST',
    body: JSON.stringify(data)
  });
}, 10, 60000); // Max 10 calls per minute

// Application startup
async function startApp() {
  arc.info('Starting application...');
  
  try {
    // Initialize components
    await arc.sleep(100); // Brief pause
    arc.success('Application started successfully!');
  } catch (error) {
    arc.error('Failed to start application:', error);
  }
}

startApp();
```

### React Component Example

```typescript
import React, { useCallback, useEffect, useState } from 'react';
import { arc } from '@letmein_by10/arc-utils';

const SearchComponent: React.FC = () => {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState([]);

  // Create debounced search function
  const debouncedSearch = useCallback(
    arc.deb(async (searchQuery: string) => {
      if (!searchQuery) return;
      
      arc.info(`Searching for: ${searchQuery}`);
      
      try {
        const response = await fetch(`/api/search?q=${searchQuery}`);
        const data = await response.json();
        setResults(data);
        arc.success(`Found ${data.length} results`);
      } catch (error) {
        arc.error('Search failed:', error);
      }
    }, 500),
    []
  );

  useEffect(() => {
    debouncedSearch(query);
  }, [query, debouncedSearch]);

  const handleInputChange = arc.thr((value: string) => {
    setQuery(value);
    arc.debug('Query updated:', value);
  }, 100);

  return (
    <div>
      <input 
        type="text" 
        onChange={(e) => handleInputChange(e.target.value)}
        placeholder="Search..."
      />
      {/* Results display */}
    </div>
  );
};
```

### Express.js Server Example

```typescript
import express from 'express';
import { arc } from '@letmein_by10/arc-utils';

const app = express();
const port = 3000;

// Create server logger
const serverLogger = arc.createLogger({
  prefix: '🌐 Server',
  level: arc.LogLevel.INFO
});

// Rate-limited middleware
const rateLimitMiddleware = arc.rateLimit((req: any, res: any, next: any) => {
  next();
}, 100, 60000); // 100 requests per minute

// Throttled request logger
const logRequest = arc.throttle((method: string, path: string) => {
  serverLogger.info(`${method} ${path}`);
}, 1000);

app.use((req, res, next) => {
  logRequest(req.method, req.path);
  next();
});

app.get('/', (req, res) => {
  arc.success('Home page accessed');
  res.json({ message: 'Hello World!' });
});

app.listen(port, () => {
  arc.info(`Server running on port ${port}`);
});
```

### Performance Monitoring

```typescript
import { arc } from '@letmein_by10/arc-utils';

class PerformanceMonitor {
  private static instance: PerformanceMonitor;
  private logger = arc.createLogger({ prefix: '⏱️  PERF' });

  static getInstance() {
    if (!this.instance) {
      this.instance = new PerformanceMonitor();
    }
    return this.instance;
  }

  // Debounced performance report
  private reportMetrics = arc.deb(() => {
    const metrics = performance.getEntriesByType('measure');
    this.logger.table(metrics);
  }, 1000);

  startTimer(label: string) {
    this.logger.time(label);
    performance.mark(`${label}-start`);
  }

  endTimer(label: string) {
    performance.mark(`${label}-end`);
    performance.measure(label, `${label}-start`, `${label}-end`);
    this.logger.timeEnd(label);
    this.reportMetrics();
  }

  // Rate-limited error reporting
  reportError = arc.rateLimit((error: Error) => {
    this.logger.error('Performance issue detected:', error);
  }, 5, 60000); // Max 5 error reports per minute
}

// Usage
const monitor = PerformanceMonitor.getInstance();
monitor.startTimer('database-query');
// ... database operation
monitor.endTimer('database-query');
```

## Package Contents

This package re-exports everything from its dependencies:

### From @letmein_by10/arc-logger:
- `logger` - Default logger instance
- `ArcLogger` - Logger class  
- `LogLevel` - Log level enumeration
- `LoggerConfig` - Configuration interface

### From @letmein_by10/arc-debounce:
- `debounce` - Debounce function
- `throttle` - Throttle function
- `once` - Once function  
- `delay` - Delay function
- `sleep` - Sleep function
- `rateLimit` - Rate limit function
- All related interfaces and types

## TypeScript Support

Complete TypeScript support with full type inference:

```typescript
import { arc, LogLevel, DebounceOptions } from '@letmein_by10/arc-utils';

// Type-safe logger configuration
const logger = arc.createLogger({
  level: LogLevel.DEBUG,  // ✅ Enum
  prefix: '🚀'           // ✅ String
});

// Type-safe debounce options
const debouncedFn = arc.debounce(
  (x: number): number => x * 2,
  300,
  { immediate: true } as DebounceOptions  // ✅ Typed options
);

// Return type inference
const result: number | undefined = debouncedFn(5); // ✅ Correctly typed
```

## When to Use This Package

Choose `@letmein_by10/arc-utils` when you:

- ✅ Want both logging and timing utilities
- ✅ Prefer a single dependency  
- ✅ Like convenient APIs and shortcuts
- ✅ Want pre-configured instances
- ✅ Need consistent interfaces

Choose individual packages when you:
- ❌ Only need specific functionality
- ❌ Want to minimize bundle size
- ❌ Prefer granular dependencies

## License

MIT © [pizle0210](mailto:fajobiadedoyin@hotmail.com)