3 ms·
Java version using higher order functions :) public interface Matcher { Optional<String> match(int value); static Matcher divideBy(int div, String t
by _old_dude_ 8y ago
Java version using higher order functions :)
public interface Matcher {
Optional<String> match(int value);
static Matcher divideBy(int div, String text) {
return value -> Optional.of(value).filter(v -> v % div == 0).map(__ -> text);
}
default Matcher zip(Matcher matcher, BinaryOperator<String> op) {
return value -> Stream.of(match(value), matcher.match(value)).flatMap(Optional::stream).reduce(op);
}
public static void main(String[] args) {
var matcher = divideBy(3, "Fizz").zip(divideBy(5, "Buzz"), String::concat);
IntStream.rangeClosed(0, 100)
.mapToObj(value -> matcher.match(value).orElse("" + value))
.skip(1).forEach(System.out::println);
}
}