introduce Functions

This commit is contained in:
Gregory.Shrago
2015-05-26 05:05:19 +03:00
parent 2aa70ff44c
commit 5f63aed263
2 changed files with 86 additions and 0 deletions
@@ -18,6 +18,7 @@ package com.intellij.openapi.util;
import com.intellij.reference.SoftReference;
import com.intellij.util.ArrayUtilRt;
import com.intellij.util.Function;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
@@ -48,6 +49,15 @@ public class Conditions {
};
}
public static Condition<Class> assignableTo(final Class clazz) {
return new Condition<Class>() {
@Override
public boolean value(Class t) {
return clazz.isAssignableFrom(t);
}
};
}
public static <T> Condition<T> instanceOf(final Class<?>... clazz) {
return new Condition<T>() {
@Override
@@ -114,6 +124,15 @@ public class Conditions {
return new Or<T>(c1, c2);
}
public static <A, B> Condition<A> compose(final Function<? super A, B> fun, final Condition<? super B> condition) {
return new Condition<A>() {
@Override
public boolean value(A o) {
return condition.value(fun.fun(o));
}
};
}
public static <T> Condition<T> cached(Condition<T> c) {
return new SoftRefCache<T>(c);
}
@@ -0,0 +1,67 @@
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed 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 com.intellij.util;
import com.intellij.openapi.util.Pair;
import java.util.Map;
/**
* @author gregsh
*/
public class Functions {
public static <A, B> Function<A, B> identity() {
return Function.ID;
}
public static <A> Function<A, String> toString() {
return Function.TO_STRING;
}
public static <A, B> Function<A, B> fromMap(final Map<A, B> map) {
return new Function<A, B>() {
@Override
public B fun(A a) {
return map.get(a);
}
};
}
private static final Function PAIR_FIRST = new Function<Pair<?, ?>, Object>() {
@Override
public Object fun(Pair<?, ?> pair) {
return Pair.getFirst(pair);
}
};
private static final Function PAIR_SECOND = new Function<Pair<?, ?>, Object>() {
@Override
public Object fun(Pair<?, ?> pair) {
return Pair.getSecond(pair);
}
};
public static <A> Function<Pair<A, ?>, A> pairFirst() {
//noinspection unchecked
return (Function<Pair<A, ?>, A>)PAIR_FIRST;
}
public static <B> Function<Pair<?, B>, B> pairSecond() {
//noinspection unchecked
return (Function<Pair<?, B>, B>)PAIR_SECOND;
}
}