package org.forks.jsonrpc;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;

final class IterHelper {
    private IterHelper() {
    }

    public static <T> ArrayList<T> toList(Iterable<T> iter) {
        ArrayList<T> result = new ArrayList<T>();
        for (T item : iter) {
            result.add(item);
        }
        return result;
    }

    public static <T> ArrayList<T> toList(T... items) {
        ArrayList<T> result = new ArrayList<T>(items.length);
        for (T item : items) {
            result.add(item);
        }
        return result;
    }

    public static <T> int count(Iterable<T> iter) {
        int result = 0;
        for (@SuppressWarnings("unused")
        T item : iter) {
            result++;
        }
        return result;
    }

    public static <T> Iterable<T> skip(final int n, final Iterable<T> iter) {
        return new Iterable<T>() {

            public Iterator<T> iterator() {

                return new Iterator<T>() {

                    Iterator<T> mIter = iter.iterator();
                    {
                        try {
                            for (int i = 0; i < n; i++) {
                                mIter.next();
                            }
                        } catch (NoSuchElementException e) {
                        }
                    }

                    public boolean hasNext() {
                        return mIter.hasNext();
                    }

                    public T next() {
                        return mIter.next();
                    }

                    public void remove() {
                        mIter.remove();
                    }
                };
            }
        };
    }

}
