# All files / src/utils format.ts

0% Statements 0/37
0% Branches 0/9
0% Functions 0/9
0% Lines 0/35

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69

     // Formatting utilities

    import { format, formatDistanceToNow, parseISO } from 'date-fns';

    export function formatDate(dateString: string, formatStr: string = 'PPP'): string {
      try {
        const date = parseISO(dateString);
        return format(date, formatStr);
      } catch {
        return 'Invalid date';
      }
    }

    export function formatDateTime(dateString: string): string {
      return formatDate(dateString, 'PPP p');
    }

    export function formatRelativeTime(dateString: string): string {
      try {
        const date = parseISO(dateString);
        return formatDistanceToNow(date, { addSuffix: true });
      } catch {
        return 'Invalid date';
      }
    }

    export function formatDuration(minutes: number): string {
      if (minutes < 60) {
        return `${minutes}m`;
      }

      const hours = Math.floor(minutes / 60);
      const remainingMinutes = minutes % 60;

      if (remainingMinutes === 0) {
        return `${hours}h`;
      }

      return `${hours}h ${remainingMinutes}m`;
    }

    export function formatFileSize(bytes: number): string {
      const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
      if (bytes === 0) return '0 Bytes';

      const i = Math.floor(Math.log(bytes) / Math.log(1024));
      return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i];
    }

    export function formatCredits(credits: number): string {
      return new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD',
        minimumFractionDigits: 2}).format(credits);
    }

    export function truncateText(text: string, maxLength: number): string {
      if (text.length <= maxLength) return text;
      return text.slice(0, maxLength) + '...';
    }

    export function capitalizeFirst(text: string): string {
      return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
    }

    export function formatUsername(username: string): string {
      return username.toLowerCase().replace(/[^a-z0-9_]/g, '');
    }