/*
 * Copyright 2006 Takahiro Nakamura.
 *
 * 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 woolpack.fn;

import java.util.Map;

public class SwitchFn<C, R, E extends Exception> implements Fn<C, R, E> {
	private Map<? super C, ? extends R> map;
	private Fn<? super C, ? extends R, ? extends E> defaultFn;
	
	public SwitchFn(
			final Map<? super C, ? extends R> map,
			final Fn<? super C, ? extends R, ? extends E> defaultFn) {
		this.map = map;
		this.defaultFn = defaultFn;
	}

	public R exec(final C c) throws E {
		final R r = map.get(c);
		if (r == null) {
			return defaultFn.exec(c);
		} else {
			return r;
		}
	}

	public Fn<? super C, ? extends R, ? extends E> getDefaultFn() {
		return defaultFn;
	}
	public void setDefaultFn(final Fn<? super C, ? extends R, ? extends E> defaultFn) {
		this.defaultFn = defaultFn;
	}
	public Map<? super C, ? extends R> getMap() {
		return map;
	}
	public void setMap(final Map<? super C, ? extends R> map) {
		this.map = map;
	}
}
