import { Sort } from './types'

// TODO: Add it from UI-Utils
/** Comparator for Array.sort when sorting arrays of objects by given key with optional order. */
export function compareBy<T extends object, K extends keyof T>(key: K, order: Sort['order'] = 'asc') {
  const ord = order === 'asc' ? 1 : -1

  return (item1: T, item2: T) => {
    if (order === null) return 0
    const a = item1[key]
    const b = item2[key]

    if (typeof a === 'string' && typeof b === 'string') {
      return a.localeCompare(b) * ord
    } else if (typeof a === 'number' && typeof b === 'number') {
      return a > b ? ord : a < b ? -ord : 0
    }
    return 0
  }
}

// TODO: Add it from UI-Utils
/** Adds given item to the array if it wasn't there yet, or removes it otherwise. */
export function toggleItem<T>(array: T[], item: T): T[] {
  return array.includes(item) ? array.filter(it => it !== item) : [...array, item]
}
