package migl.util;

/**
 * Factory to create new lists.
 * 
 * The methods take advantage of type inference to simplify the use of the
 * methods in the user code.
 * 
 * The body of the methods must be completed by the students.
 * 
 * @author leberre
 *
 */
public final class ConsListFactory {

	private ConsListFactory() {
		// do nothing
	}

	/**
	 * Create a new empty list.
	 * 
	 * @return an empty list
	 */
	public static <T> ConsList<T> nil() {
		return new ConsEmptyList<T>();
	}

	/**
	 * Create a new list containing a single element
	 * 
	 * @param t
	 *            an object
	 * @return a list containing only t
	 */
	public static <T> ConsList<T> singleton(T t) {
		return new ConsListImpl<T>(t, new ConsEmptyList<>());
	}

	/**
	 * Create a new list containing the elements given in parameter
	 * 
	 * @param ts
	 *            a variable number of elements
	 * @return a list containing those elements
	 */
	@SafeVarargs
	public static <T> ConsList<T> asList(T... ts) {
		//Si liste vide
		if(ts.length == 0) {
			return nil();
		} 
		//Si 1 element
		else if(ts.length == 1) {
			return singleton(ts[0]);
		}
		//Si +sieurs elements
		ConsList<T> list = new ConsListImpl<>(ts[ts.length - 1], new ConsEmptyList<>());
		for(int i = ts.length - 2; i > -1; i--) {
			list = list.prepend(ts[i]);
		}
		return list;
	}
	
}
