فهرست منبع

Add first, single, and default functions

Billy Barrow 2 سال پیش
والد
کامیت
d326996057
3فایلهای تغییر یافته به همراه53 افزوده شده و 0 حذف شده
  1. 46 0
      src/lib/Enumerable.vala
  2. 6 0
      src/lib/SequenceError.vala
  3. 1 0
      src/lib/meson.build

+ 46 - 0
src/lib/Enumerable.vala

@@ -132,6 +132,52 @@ namespace Invercargill {
             return pair(other).all(p => equals(p.value1, p.value2));
         }
 
+        public virtual Enumerable<T> with(T item) {
+            var seq = new Sequence<T>();
+            seq.add(item);
+            return concat(seq);
+        }
+
+        public virtual T first() throws SequenceError {
+            var tracker = get_tracker();
+            if(tracker.has_next()) {
+                return tracker.get_next();
+            }
+            throw new SequenceError.NO_ELEMENTS("The sequence contains no elements");
+        }
+
+        public virtual T first_or_default() throws SequenceError {
+            var tracker = get_tracker();
+            if(tracker.has_next()) {
+                return tracker.get_next();
+            }
+            return null;
+        }
+
+        public virtual T single() throws SequenceError {
+            var tracker = get_tracker();
+            if(tracker.has_next()) {
+                var item = tracker.get_next();
+                if(tracker.has_next()) {
+                    throw new SequenceError.MULTUPLE_ELEMENTS("The sequence contains more than one element");
+                }
+                return item;
+            }
+            throw new SequenceError.NO_ELEMENTS("The sequence contains no elements");
+        }
+
+        public virtual T single_or_default() throws SequenceError {
+            var tracker = get_tracker();
+            if(tracker.has_next()) {
+                var item = tracker.get_next();
+                if(tracker.has_next()) {
+                    throw new SequenceError.MULTUPLE_ELEMENTS("The sequence contains more than one element");
+                }
+                return item;
+            }
+            return null;
+        }
+
     }
 
 }

+ 6 - 0
src/lib/SequenceError.vala

@@ -0,0 +1,6 @@
+namespace Invercargill {
+    public errordomain SequenceError {
+        NO_ELEMENTS,
+        MULTUPLE_ELEMENTS
+    }
+}

+ 1 - 0
src/lib/meson.build

@@ -12,6 +12,7 @@ sources += files('GeeIterable.vala')
 sources += files('Delegates.vala')
 sources += files('Pair.vala')
 sources += files('Tracker.vala')
+sources += files('SequenceError.vala')
 
 sources += files('Queries/Query.vala')
 sources += files('Queries/Transform.vala')