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

net.intelie.pipes.util.PipesComparator Maven / Gradle / Ivy

There is a newer version: 0.25.5
Show newest version
package net.intelie.pipes.util;

import net.intelie.pipes.types.Type;

import java.util.Comparator;

public class PipesComparator implements Comparator {
    private static final PipesComparator instance = new PipesComparator();

    public static PipesComparator instance() {
        return instance;
    }

    @Override
    public int compare(Object c1, Object c2) {
        if (!(c1 instanceof Comparable))
            return !(c2 instanceof Comparable) ? 0 : -1;
        if (!(c2 instanceof Comparable))
            return 1;

        Type type1 = Type.infer(c1);
        Type type2 = Type.infer(c2);

        if (!type1.name().equals(type2.name()))
            return type1.name().compareTo(type2.name());

        if (Type.COMPARABLE.equals(type1))
            return 0;

        c1 = maybeNumber(c1);
        c2 = maybeNumber(c2);

        return ((Comparable) c1).compareTo(c2);
    }

    private Object maybeNumber(Object value) {
        if (value instanceof Number)
            value = ((Number) value).doubleValue();
        return value;
    }
}