Say my comparator function foo
takes a time sequence as input, which could be a series of time from small to large, or from large to small.
Foo
may look like this:
Foo(List<double> timestampList) {
if (currentTime > previousMaxValueTimestamp) {
...
} else if (curremtTime > previousMinValueTimestamp) {
...
}
}
The above works for forward sequence, but not the reverse one. How can I elegantly write a logic that works for both types of sequence? Below is what I want to do, but it duplicates most of the code, which is not desired.
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 like below. Is it good coding style?
Foo(List<double> timestampList, boolean isForward) {
if ((isForward && currentTime > previousMaxValueTimestamp) || (!isForward && currentTime < previousMaxValueTimestamp)) {
...
} else if ((isForward && curremtTime < previousMinValueTimestamp) || (!isForward && currentTime > previousMaxValueTimestamp)) {
...
}
}