All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.squirrelgrip.extension.collection.DrainerCompiler.kt Maven / Gradle / Ivy

There is a newer version: 1.5.5
Show newest version
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)
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy