An elegant way to compare time sequences in forward / reverse order

Say my comparator function fooaccepts a time sequence as an input, which can be a series of time from small to large or from large to small.

foo might look like this:

Foo(List<double> timestampList) {
  if (currentTime > previousMaxValueTimestamp) {
    ...
  } else if (curremtTime > previousMinValueTimestamp) {
    ...
  }
}

The above works for direct sequence, but not vice versa. How can I elegantly write logic that works for both types of sequences? Below I want to do this, but it duplicates most of the code, which is undesirable.

Foo(List<double> timestampList, boolean isForward) {
  if (isForward) {
        if (currentTime > previousMaxValueTimestamp) {
            ...
        } else if (curremtTime > previousMinValueTimestamp) {
            ...
        }
  } else {
        if (currentTime < previousMaxValueTimestamp) {
            ...
        } else if (curremtTime < previousMinValueTimestamp) {
            ...
        }
  }
}

My current solution is similar to below. Is this a good coding style?

Foo(List<double> timestampList, boolean isForward) {
    if ((isForward && currentTime > previousMaxValueTimestamp) || (!isForward && currentTime < previousMaxValueTimestamp)) {
        ...
    } else if ((isForward && curremtTime < previousMinValueTimestamp) || (!isForward && currentTime > previousMaxValueTimestamp)) {
        ...
    }
}
+4
source share
3 answers

, - , ,

if (isForward ? currentTime > previousMaxValueTimestamp :
    currentTime < previousMaxValueTimestamp)
{

} else if (!isForward ? currentTime < previousMaxValueTimestamp :
           currentTime < previousMinValueTimestamp)
{

}
+5

, , , :

ListIterator li = a.listIterator(a.size());
while(isForward ? li.hasPrevious() : li.hasNext()) {
  nextItem = isForward ? li.previous() : li.next());
  //do stuff

}

,

, , Collections.sort(yourList, yourSpecialComparator), .

+1

"" .reverse() . , , , .

+1

Source: https://habr.com/ru/post/1615183/


All Articles