react-vite-demo

react and vite demo

git clone https://9o.is/git/react-vite-demo.git

objects.ts

(1705B)


      1 type KeysOfType<T, U> = {
      2     [K in keyof T]: T[K] extends U ? K : never
      3 }[keyof T]
      4 
      5 type NumberKeysOf<T> = KeysOfType<T, number>
      6 
      7 export const SORT_TYPES = ["ascending", "descending"] as const
      8 export type SortType = typeof SORT_TYPES[number]
      9 
     10 export function isSortType(value: string | undefined | null): value is SortType {
     11     return value === "ascending" || value === "descending"
     12 }
     13 
     14 export function asArray<T>(value: T | T[] | undefined | null): T[] {
     15     return Array.isArray(value) ? value : 
     16         value !== undefined && value !== null ? [value] : []
     17 }
     18 
     19 export function filterByProp<T extends object>(prop: keyof T, value: T[keyof T], objects: T[]): T[] {
     20     return objects.filter(object => object[prop] === value)
     21 }
     22 
     23 export function sortByProp<T,>(prop: NumberKeysOf<T>, order: SortType, objects: T[]): T[] {
     24     return [...objects].sort((a: T, b: T) => {
     25         if (!order || typeof a[prop] !== "number" || typeof b[prop] !== "number") return 0
     26         if (order === "ascending") return a[prop] - b[prop]
     27         return b[prop] - a[prop]
     28     })
     29 }
     30 
     31 export function minByProp<T extends object>(prop: NumberKeysOf<T>, objects: T[]): T | null {
     32     if (objects.length === 0) return null
     33     if (objects.length === 1) return objects[0]
     34 
     35     const [fst, snd, ...tail] = objects
     36     const min = fst[prop] < snd[prop] ? fst : snd
     37     return minByProp(prop, [min, ...tail])
     38 }
     39 
     40 // Alternative implementation using reduce
     41 // const minByProp = <T extends object>(prop: NumberKeysOf<T>, objects: T[]): T | undefined => {
     42 //   if (objects.length === 0) return undefined
     43 
     44 //   return objects.reduce((minObj, currentObj) => {
     45 //     return currentObj[prop] < minObj[prop] ? currentObj : minObj
     46 //   })
     47 // }