All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.codepoetics.protonpack.selectors.Selectors Maven / Gradle / Ivy

There is a newer version: 1.16
Show newest version
package com.codepoetics.protonpack.selectors;

import java.util.Comparator;
import java.util.stream.Stream;

public final class Selectors {
    private Selectors() {
    }

    public static  Selector roundRobin() {
        return new Selector() {
            private int startIndex = 0;
            @Override
            public Integer apply(T[] options) {
                int result = startIndex;
                while (options[result] == null) {
                    result = (result + 1) % options.length;
                }

                startIndex = (result + 1) % options.length;
                return result;
            }
        };
    }

    public static > Selector takeMin() {
        return takeMin(Comparator.naturalOrder());
    }

    public static  Selector takeMin(Comparator comparator) {
        return new Selector() {

            private int startIndex = 0;

            @Override
            public Integer apply(T[] options) {
                T smallest = Stream.of(options).filter(t -> t != null).min(comparator).get();

                int result = startIndex;
                while (options[result] == null || comparator.compare(smallest, options[result]) != 0) {
                    result = (result + 1) % options.length;
                }

                startIndex = (result + 1) % options.length;
                return result;
            }
        };
    }

    public static > Selector takeMax() {
        return takeMax(Comparator.naturalOrder());
    }

    public static  Selector takeMax(Comparator comparator) {
        return takeMin(comparator.reversed());
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy