-1

Is there a way to make this line syntax shorter?

this.props.sortBy === 'newToOld' ?
  posts.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()) :
  posts.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime())
isherwood
  • 58,414
  • 16
  • 114
  • 157
Niko Konovalov
  • 161
  • 1
  • 13
  • It should be cautioned that if the `date` property holds strings and not `Date` objects or numbers, that you may have problems with formats other than a few very specific ones. See [Why does Date.parse give incorrect results?](https://stackoverflow.com/q/2587345/215552) – Heretic Monkey Oct 21 '20 at 15:59

2 Answers2

1

Just create a single comparator:

const sorter = (a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());

And then you can create a generic higher order modifier for any comparator that reverses the order:

const reverse = comparator => (a, b) => comparator(b, a);

Pair with an identity:

const identity = comparator => comparator;

And you can model your sorting via composition:

const reverse = comparator => (a, b) => comparator(b, a);
const identity = x => x;

const sorter = (a, b) => new Date(a.date).getTime() - new Date(b.date).getTime();

function showSorting(items, sortBy) {
  let modifier = identity;
  
  if (sortBy === 'newToOld') {
    modifier = reverse;
  }
  
  return items.sort(modifier(sorter));
}

const data = [
  {date: "2020-03-19", name: "C"},
  {date: "2020-01-19", name: "A"},
  {date: "2020-04-19", name: "D"},
  {date: "2020-02-19", name: "B"},
];

console.log("----------newToOld", showSorting(data, "newToOld"));
console.log("----------oldToNew", showSorting(data, "oldToNew"));
VLAZ
  • 26,331
  • 9
  • 49
  • 67
0

There is a way to make it shorter. Up to you if it is more readable.

posts.sort((a, b) => (new Date(b.date).getTime() - new Date(a.date).getTime()) * (this.props.sortBy === 'newToOld' ? 1 : -1))
Lachlan D
  • 137
  • 1
  • 7