I have done the leap year check on https://exercism.io already in a lot of languages. Today I came back to the exercise in Java and was playing around with some maybe more funny ways to do the check. The following more functional one kept me thinking of:
import java.util.stream.IntStream;
class Leap {
boolean isLeapYear(final int year) {
return IntStream.of(4, 100, 400)
.filter(divisor -> year % divisor == 0)
.count() % 2 == 1;
}
}
What do you think? Is this readable? At least it seems to be extensible in case more rules will ever get added ;)
Another funny fact: due to prime factorization we actually could also use the IntStream.of(2, 25, 16)
(but for sure that doesn't help in readability).
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
, note. \$\endgroup\$return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
isn't a functional implementation. It has no side effects and the result only depends on the input. \$\endgroup\$