aboutsummaryrefslogtreecommitdiffstats
path: root/apps/Notes/hooks/useSort.js
blob: 78c01b41e814a7baf4598f6ac9a1f534d9774654 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import {useState} from 'react'
import {faSortAmountDown, faSortAmountUp} from '@fortawesome/free-solid-svg-icons'
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'

const useSort = (d) => {
  const [sort, setSort] = useState(d)

  const sortedBy = s => Math.abs(sort) === s && <FontAwesomeIcon icon={sort>0 ? faSortAmountDown : faSortAmountUp} />
  const sortBy = s => sort === s ? setSort(-1*s) : setSort(s)
  const sortFn = (a, b) => {
    const d = sort > 0 ? 1 : -1
    switch (Math.abs(sort)) {
      case 1: return d * a.title.localeCompare(b.title)
      case 2: return d * (new Date(b.created_at) - new Date(a.created_at))
      case 3: return d * (new Date(b.updated_at) - new Date(a.updated_at))
    }
  }

  return [sortedBy, sortBy, sortFn]
}

export default useSort