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

de.larsgrefer.sass.embedded.functions.BiFunctionHostFunction Maven / Gradle / Ivy

There is a newer version: 4.0.0-m2
Show newest version
package de.larsgrefer.sass.embedded.functions;

import com.sass_lang.embedded_protocol.Value;

import javax.annotation.Nonnull;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.BiFunction;

/**
 * @author Lars Grefer
 */
class BiFunctionHostFunction extends HostFunction {

    private static final List args = Collections.unmodifiableList(Arrays.asList(
            new Argument("arg0", null),
            new Argument("arg1", null)
    ));

    private final BiFunction lambda;

    private final Class arg0Type;
    private final Class arg1Type;

    protected BiFunctionHostFunction(String name, Class arg0Type, Class arg1Type, BiFunction lambda) {
        super(name, args);
        this.lambda = lambda;
        this.arg0Type = arg0Type;
        this.arg1Type = arg1Type;
    }

    @Override
    @Nonnull
    public Value invoke(List arguments) {
        if (arguments.size() != 2) {
            throw new IllegalArgumentException("Invalid argument count: Expected 2 instead of " + arguments.size());
        }

        T arg0 = ConversionService.toJavaValue(arguments.get(0), arg0Type, arg0Type);
        U arg1 = ConversionService.toJavaValue(arguments.get(1), arg1Type, arg1Type);

        Object call = lambda.apply(arg0, arg1);
        return ConversionService.toSassValue(call);
    }

}