0

What do I do wrong:

assert  'foo'  == 'foo'  //PASS
assert  '500'  == '500'  //PASS
assert  '500'  <  '1000' //FAIL <-- Supposed to pass
assert  '500'  <= '1000' //FAIL <-- Supposed to pass
assert  '1000' >  '500'  //FAIL <-- Supposed to pass
assert  '1000' >= '500'  //FAIL <-- Supposed to pass

It is for a customizable "condition" object:

class Condition {
    static def compareClosure = [
            '==' : { a, b -> a == b},
            '!=' : { a, b -> a != b},
            '<'  : { a, b -> a <  b},
            '<=' : { a, b -> a <= b},
            '>'  : { a, b -> a >  b},
            '>=' : { a, b -> a >= b}
    ]

    String comparator
    def value

    Condition(String comparator, String value) {
        this.value = value
        this.comparator = comparator
    }

    boolean isSatisfiedBy(def value) {
        compareClosure[comparator](value, this.value)
    }
}

So

assert new Condition('<=', '1000').isSatisfiedBy('500') //FAIL

Is there a way to do this without converting value to a numeric type ?

Thermech
  • 4,371
  • 2
  • 39
  • 60

1 Answers1

0

The short answer to your question is no.

However, I have a feeling this is for sorting purposes. If that is the case. Here is the sort function I use for this purpose.

Example in action: Groovy Web Console

    Closure customSort = { String a, String b ->
      def c = a.isBigDecimal() ? new BigDecimal(a) : a
      def d = b.isBigDecimal() ? new BigDecimal(b) : b


      if (c.class == d.class) {
        return c <=> d
      } else if (c instanceof BigDecimal) {
        return -1
      } else {
        return 1
      }

    }

['foo','500','1000', '999', 'abc'].sort(customSort)
James Kleeh
  • 12,094
  • 5
  • 34
  • 61