utils.ts


Overview

The utils.ts file provides a set of utility functions designed to simplify common tasks related to CSS class name management and data size formatting. This file primarily offers:

These utilities are generally used throughout the application to maintain consistency in styling and data representation.


Functions

cn(...inputs: ClassValue[]): string

Description

Combines multiple CSS class values into a single string with proper merging and conflict resolution tailored for Tailwind CSS classes.

Parameters

Returns

Usage Example

import { cn } from './utils';

const buttonClass = cn(
  'btn',
  isPrimary && 'btn-primary',
  isDisabled ? 'opacity-50 cursor-not-allowed' : 'hover:bg-blue-500'
);

// buttonClass might output: "btn btn-primary hover:bg-blue-500"

Implementation Details


formatBytes(bytes: number, opts?: { decimals?: number; sizeType?: 'accurate' | 'normal' }): string

Description

Converts a byte count into a human-readable string with appropriate size units, supporting both standard decimal units (KB, MB) and binary IEC units (KiB, MiB).

Parameters

Returns

Usage Example

import { formatBytes } from './utils';

console.log(formatBytes(1024)); 
// Output: "1 KB"

console.log(formatBytes(1024, { decimals: 2, sizeType: 'accurate' }));
// Output: "1.00 KiB"

console.log(formatBytes(123456789, { decimals: 1 }));
// Output: "117.7 MB"

Implementation Details


Interaction with Other Parts of the System


Mermaid Diagram

flowchart TD
    A[cn(...inputs: ClassValue[])] --> B[clsx(inputs)]
    B --> C[twMerge(classString)]
    C --> D[Returns merged class string]

    E[formatBytes(bytes, opts?)] --> F{bytes === 0?}
    F -- Yes --> G["Returns '0 Byte'"]
    F -- No --> H[Calculate index i = floor(log(bytes)/log(1024))]
    H --> I[Divide bytes by 1024^i and format with decimals]
    I --> J{opts.sizeType === 'accurate'?}
    J -- Yes --> K[Use accurateSizes[i]]
    J -- No --> L[Use sizes[i]]
    K & L --> M[Return formatted string]

Summary

The utils.ts file provides essential helper functions that enhance styling management and data size formatting within the application. By abstracting common patterns into reusable utilities, it promotes cleaner code and consistent behavior across UI components and data presentation layers. The use of well-maintained external libraries (clsx and tailwind-merge) combined with straightforward algorithms (logarithmic scaling for byte formatting) makes these utilities reliable and performant.