com.github.squirrelgrip.extension.collection.DrainerCompiler.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of kotlin-extensions Show documentation
Show all versions of kotlin-extensions Show documentation
A collection of useful kotlin extensions
package com.github.squirrelgrip.extension.collection
import org.antlr.v4.runtime.CharStreams
import org.antlr.v4.runtime.CommonTokenStream
class DrainerCompiler {
companion object {
val visitor: DrainerBaseVisitor<(Collection) -> Boolean> = object : DrainerBaseVisitor<(Collection) -> Boolean>() {
override fun visitAndExpression(ctx: DrainerParser.AndExpressionContext): (Collection) -> Boolean = {
visit(ctx.expression(0)).invoke(it) && visit(ctx.expression(1)).invoke(it)
}
override fun visitOrExpression(ctx: DrainerParser.OrExpressionContext): (Collection) -> Boolean = {
visit(ctx.expression(0)).invoke(it) || visit(ctx.expression(1)).invoke(it)
}
override fun visitNotExpression(ctx: DrainerParser.NotExpressionContext): (Collection) -> Boolean = {
!visit(ctx.expression()).invoke(it)
}
override fun visitVariableExpression(ctx: DrainerParser.VariableExpressionContext): (Collection) -> Boolean = {
ctx.variable().text in it
}
override fun visitParenExpression(ctx: DrainerParser.ParenExpressionContext): (Collection) -> Boolean = {
visit(ctx.expression()).invoke(it)
}
override fun visitPredicate(ctx: DrainerParser.PredicateContext): (Collection) -> Boolean = {
visit(ctx.expression()).invoke(it)
}
}
}
fun compile(input: String): (Collection) -> Boolean =
visitor.visit(DrainerParser(CommonTokenStream(DrainerLexer(CharStreams.fromString(input)))).predicate())
}
fun Collection.filter(expression: String, extractor: (T) -> Collection): List {
val predicate = DrainerCompiler().compile(expression)
return this.filter {
predicate.invoke(extractor.invoke(it))
}
}
fun Collection>.filter(expression: String): List> {
val predicate = DrainerCompiler().compile(expression)
return this.filter {
predicate.invoke(it)
}
}