vendredi 11 septembre 2015

Groovy half-exclusive range strange behaviour

Why is Groovy showing this behaviour when using half-exclusive range. It is supposed to return all but the last element in the range but it sometimes show all elements in the range plus one.

This is the sample.

 class Weekday implements Comparable {
    static final DAYS = [
        'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'
    ]
    private int idx = 0

    Weekday(index)     { idx = index }
    Weekday next()     { new Weekday(idx+1) }
    Weekday previous() { new Weekday(idx+1) }
    int compareTo(Object other) { this.idx <=> other.idx }

    String toString() {
        def index = idx % DAYS.size()
        while (index < 0 ) index += DAYS.size()
            DAYS[index]
    }
}

def mon = new Weekday(1)
def fri = new Weekday(5)

7.times { mon++ } // Monday following week

println fri.idx   //  5
println mon.idx   //  8

println 5 .. 8    // [5, 6, 7, 8]
println fri..mon  // [Fri, Sat, Sun, Mon] Ok without half-exclusive
println 5 ..< 8   // [5, 6, 7]
println fri..<mon // [Fri, Sat, Sun, Mon, Tue] ????????



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire