Groovy web console

subscribe to the feed Subscribe
to this
site

Untitled

Published 1 month ago by Anonymous
Actions Execute script  ▶ Edit in console Back to console Show/hide line numbers View recent scripts
enum Ordering {  
    LT(-1), EQ(0), GT(1)

    static Ordering from(int val) {
        if (val < 0) return LT;
        if (val > 0) return GT;
        return EQ;
    }
    public Ordering(int value) {
        this.value = value
    }
    final int value


    Ordering combine(Ordering other) {
        if (this == LT) return LT;
        if (this == EQ) return other;
        if (this == GT) return GT;
    }

    static Ordering neutral = EQ;
}


List.metaClass.fold << {
    Monoid -> delegate.inject(Monoid.neutral) { acc, val -> acc.combine(Monoid.from(val)) }
}


class SemanticRevision implements Comparable<SemanticRevision> {
    SemanticRevision(String version) {
        this( (version =~ /[\d+\.?]+/)[0].tokenize('.').collect { it.toInteger() } )
    }
    SemanticRevision(ArrayList<Integer> components) {
        this(*[*components, 0, 0, 0][0..2])
    }
    SemanticRevision(int major, int minor, int patch) {
        this.major = major
        this.minor= minor
        this.patch= patch
    }

    public int compareTo(SemanticRevision other) {
        return [
            this.major <=> other.major,
            this.minor <=> other.minor,
            this.patch <=> other.patch
        ].fold(Ordering).value
    }

    private int major
    private int minor
    private int patch
}

new SemanticRevision("1.2.3") < new SemanticRevision("1.32")