Live Code Demonstrations

Advanced TypeScript patterns and clean architecture

Explore my coding style through real examples. Each demo showcases different aspects of clean, maintainable, and performant code.

Demonstrations

Algorithm Optimization

Efficient sorting with TypeScript generics and performance monitoring

Key Concepts

GenericsPerformanceBig OType Safety
interface PerformanceMetrics {
  executionTime: number
  memoryUsage: number
  operations: number
}

class OptimizedSorter<T> {
  private metrics: PerformanceMetrics = {
    executionTime: 0,
    memoryUsage: 0,
    operations: 0
  }

  quickSort<K extends keyof T>(
    array: T[],
    compareKey?: K,
    compareFn?: (a: T[K], b: T[K]) => number
  ): { sorted: T[]; metrics: PerformanceMetrics } {
    const startTime = performance.now()
    const startMemory = (performance as any).memory?.usedJSHeapSize || 0
    
    this.metrics.operations = 0
    const sorted = this.quickSortRecursive([...array], compareKey, compareFn)
    
    this.metrics.executionTime = performance.now() - startTime
    this.metrics.memoryUsage = ((performance as any).memory?.usedJSHeapSize || 0) - startMemory
    
    return { sorted, metrics: { ...this.metrics } }
  }

  private quickSortRecursive<K extends keyof T>(
    array: T[],
    compareKey?: K,
    compareFn?: (a: T[K], b: T[K]) => number
  ): T[] {
    if (array.length <= 1) return array
    
    const pivot = array[Math.floor(array.length / 2)]
    const left: T[] = []
    const right: T[] = []
    const equal: T[] = []
    
    for (const item of array) {
      this.metrics.operations++
      const comparison = this.compare(item, pivot, compareKey, compareFn)
      
      if (comparison < 0) left.push(item)
      else if (comparison > 0) right.push(item)
      else equal.push(item)
    }
    
    return [
      ...this.quickSortRecursive(left, compareKey, compareFn),
      ...equal,
      ...this.quickSortRecursive(right, compareKey, compareFn)
    ]
  }

  private compare<K extends keyof T>(
    a: T,
    b: T,
    compareKey?: K,
    compareFn?: (a: T[K], b: T[K]) => number
  ): number {
    if (compareKey && compareFn) {
      return compareFn(a[compareKey], b[compareKey])
    }
    if (compareKey) {
      const aVal = a[compareKey]
      const bVal = b[compareKey]
      return aVal < bVal ? -1 : aVal > bVal ? 1 : 0
    }
    return String(a).localeCompare(String(b))
  }
}

// Usage Example
interface User {
  id: number
  name: string
  score: number
  createdAt: Date
}

const sorter = new OptimizedSorter<User>()
const users: User[] = [
  { id: 1, name: "Alice", score: 95, createdAt: new Date('2023-01-01') },
  { id: 2, name: "Bob", score: 87, createdAt: new Date('2023-01-02') },
  { id: 3, name: "Charlie", score: 92, createdAt: new Date('2023-01-03') }
]

const result = sorter.quickSort(users, 'score', (a, b) => b - a)
console.log('Sorted users:', result.sorted)
console.log('Performance:', result.metrics)