/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.apache.jackrabbit.utils;

/**
 * Utility class for handling {@link Predicate}s.
 */
public final class Predicates {
    /** Predicate which always evaluates {@code true} */
    public static final Predicate<?> TRUE = constant(true);

    /** Predicate which always evaluates {@code false} */
    public static final Predicate<?> FALSE = constant(false);

    private Predicates() { }

    /**
     * Predicate which checks whether some element satisfy a predicate.
     * @param elements
     * @param predicate
     * @param <T>
     * @return {@code true} iff {@code elements} contains an element for which
     * {@code predicate} evaluates to {@code true}.
     */
    public static <T> boolean exists(Iterable<T> elements, Predicate<T> predicate) {
        for (T e : elements) {
            if (predicate.evaluate(e)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Predicate which always evaluates to the same truth value.
     * @param value
     * @param <T>
     * @return a predicate which always evaluates to {@code value}.
     */
    public static <T> Predicate<T> constant(final boolean value) {
        return new Predicate<T>() {
            @Override
            public boolean evaluate(T any) {
                return value;
            }
        };
    }

}
