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())
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())
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"));
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))