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

dev.marksman.collectionviews.EmptyVectorBuilder Maven / Gradle / Ivy

There is a newer version: 1.2.3
Show newest version
package dev.marksman.collectionviews;

import com.jnape.palatable.lambda.adt.Maybe;
import dev.marksman.enhancediterables.FiniteIterable;
import dev.marksman.enhancediterables.NonEmptyFiniteIterable;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Objects;

import static dev.marksman.collectionviews.ConcreteVectorBuilder.concreteVectorBuilder;

final class EmptyVectorBuilder implements VectorBuilder {
    private final Maybe initialCapacity;

    private EmptyVectorBuilder(Maybe initialCapacity) {
        this.initialCapacity = initialCapacity;
    }

    @Override
    public NonEmptyVectorBuilder add(A element) {
        ArrayList underlying = createNewUnderlying();
        underlying.add(element);

        return concreteVectorBuilder(underlying.size(), initialCapacity, underlying);
    }

    @Override
    public VectorBuilder addAll(Collection elements) {
        Objects.requireNonNull(elements);
        if (elements.isEmpty()) {
            return this;
        } else {
            ArrayList underlying = createNewUnderlying();
            underlying.addAll(elements);

            return concreteVectorBuilder(underlying.size(), initialCapacity, underlying);
        }
    }

    @Override
    public VectorBuilder addAll(FiniteIterable elements) {
        Objects.requireNonNull(elements);
        if (elements.isEmpty()) {
            return this;
        } else {
            return addAllImpl(elements);
        }
    }

    @Override
    public NonEmptyVectorBuilder addAll(NonEmptyFiniteIterable elements) {
        return addAllImpl(elements);
    }

    @Override
    public ImmutableVector build() {
        return Vector.empty();
    }

    private NonEmptyVectorBuilder addAllImpl(FiniteIterable elements) {
        ArrayList underlying = createNewUnderlying();
        for (A element : elements) {
            underlying.add(element);
        }

        return concreteVectorBuilder(underlying.size(), initialCapacity, underlying);
    }

    private ArrayList createNewUnderlying() {
        return initialCapacity.match(__ -> new ArrayList<>(), ArrayList::new);
    }

    static  EmptyVectorBuilder emptyVectorBuilder(Maybe initialCapacity) {
        return new EmptyVectorBuilder<>(initialCapacity.filter(n -> n >= 0));
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy