[libgee] Add Iterator.concat function



commit 39a52fcb3035215352dfd2d10fbfcf597dfd5265
Author: Maciej Piechotka <uzytkownik2 gmail com>
Date:   Sat Apr 30 12:43:19 2011 +0200

    Add Iterator.concat function

 gee/iterator.vala        |   27 +++++++++++++++++++++++++++
 tests/testfunctions.vala |   27 +++++++++++++++++++++++++++
 2 files changed, 54 insertions(+), 0 deletions(-)
---
diff --git a/gee/iterator.vala b/gee/iterator.vala
index 14a5f1f..e9b4a73 100644
--- a/gee/iterator.vala
+++ b/gee/iterator.vala
@@ -123,5 +123,32 @@ public interface Gee.Iterator<G> : Object {
 	public static Iterator<A> unfold<A> (owned UnfoldFunc<A> f, owned Lazy<G>? current = null) {
 		return new UnfoldIterator<A> ((owned) f, (owned) current);
 	}
+
+	/**
+	 * Concatinate iterators.
+	 *
+	 * @param iters Iterators of iterators
+	 * @return Iterator containg values of each iterator
+	 */
+	public static Iterator<G> concat<G> (Iterator<Iterator<G>> iters) {
+		Iterator<G>? current = null;
+		if (iters.valid)
+			current = iters.get ();
+		return unfold<G> (() => {
+			while (true) {
+				if (current == null) {
+					if (iters.next ()) {
+						current = iters.get ();
+					} else {
+						return null;
+					}
+				} else if (current.next ()) {
+					return new Lazy<G>.from_value (current.get ());
+				} else {
+					current = null;
+				}
+			}
+		});
+	}
 }
 
diff --git a/tests/testfunctions.vala b/tests/testfunctions.vala
index a76b1d3..c46f7b8 100644
--- a/tests/testfunctions.vala
+++ b/tests/testfunctions.vala
@@ -28,6 +28,7 @@ public class FunctionsTests : Gee.TestCase {
 		add_test ("[Functions] comparing instances of Comparable", test_compare_func);
 		add_test ("[Functions] comparing and hashing instances of Hashable", test_hash_func);
 		add_test ("[Iterator] unfold", test_unfold);
+		add_test ("[Iterator] concat", test_concat);
 	}
 
 	public void test_string_func () {
@@ -164,6 +165,32 @@ public class FunctionsTests : Gee.TestCase {
 		assert (k == 10);
 	}
 
+	public void test_concat () {
+		int i = 0;
+		var iter_ = Gee.Iterator.unfold<Gee.Iterator<int>> (() => {
+			if (i >= 3)
+				return null;
+			int j = i++*3;
+			int start = j;
+			var iter = Gee.Iterator.unfold<int> (() => {
+				if (j == start + 3)
+					return null;
+				return new Gee.Lazy<int>.from_value (j++);
+			});
+			return new Gee.Lazy<Gee.Iterator<int>>.from_value (iter);
+		});
+
+		int j = 0;
+		var iter = Gee.Iterator.concat<int> (iter_);
+		while (iter.next()) {
+			assert (j == iter.get ());
+			assert (j == iter.get ());
+			j++;
+		}
+		assert (i == 3);
+		assert (j == 9);
+	}
+
 	private class MyComparable : GLib.Object, Gee.Comparable<MyComparable> {
 		public MyComparable (int i) {
 			this.i = i;



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]