Groovy web console

subscribe to the feed Subscribe
to this
site
Match (via #groovywebconsole)
tweet this snippet Tweet
this
script

Match

Published 4 months ago by si_
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
enum Comparator {
  Less('<', { Integer valueToCheck, Integer valueSample -> valueToCheck < valueSample }),
  LessOrEqual('<=', { Integer valueToCheck, Integer valueSample -> valueToCheck <= valueSample }),
  Equal('=', { Integer valueToCheck, Integer valueSample -> valueToCheck == valueSample }),

  String label
  Closure<Boolean> calculate

  Comparator(String label, Closure<Boolean> calculate) {
    this.label = label
    this.calculate = calculate
  }

  static Comparator get(final String op) {
    values().find { op == it.label }
  }
}

def m = [
  x: '<;5',
  y: '<=;6',
  z: '=;10'
]

def sample = [
  ['x': 1, 'y': 6, 'z': 10],
  ['x': 0, 'y': 7, 'z': 11],
  [x: 1, y: 6, z: 10]
]

println test(m, sample)

def test(m, x) {
  def r = x
  m.each { k, v ->
    def comp = Comparator.get(v.split(';')[0])
    def value = Integer.parseInt(v.split(';')[1])
    r = r.findAll { comp.calculate(it."$k", value) }
  }
  r
}