瀏覽代碼

List key/value iterato (#7512)

* List key/value iterator

* Delete ListKeyValueIterator.hx
Mark Knol 7 年之前
父節點
當前提交
16a53dfb9a
共有 2 個文件被更改,包括 39 次插入1 次删除
  1. 27 0
      std/haxe/ds/List.hx
  2. 12 1
      tests/unit/src/unitstd/List.unit.hx

+ 27 - 0
std/haxe/ds/List.hx

@@ -162,6 +162,13 @@ class List<T> {
 		return new ListIterator<T>(h);
 	}
 
+	/**
+		Returns an iterator of the List indices and values.
+	**/
+	@:pure @:runtime public inline function keyValueIterator() : ListKeyValueIterator<T> {
+		return new ListKeyValueIterator(h);
+	}
+
 	/**
 		Returns a string representation of `this` List.
 
@@ -280,3 +287,23 @@ private class ListIterator<T> {
 		return val;
 	}
 }
+
+private class ListKeyValueIterator<T> {
+	var idx:Int;
+	var head:ListNode<T>;
+
+	public inline function new(head:ListNode<T>) {
+		this.head = head;
+		this.idx = 0;
+	}
+
+	public inline function hasNext():Bool {
+		return head != null;
+	}
+
+	public inline function next():{key:Int,value:T} {
+		var val = head.item;
+		head = head.next;
+		return {value: val, key:idx++};
+	}
+}

+ 12 - 1
tests/unit/src/unitstd/List.unit.hx

@@ -37,4 +37,15 @@ l2.pop() == "22";
 l2.pop() == "33";
 var l3 = l.filter(function(i:String) return i != "2");
 l3.pop() == "1";
-l3.pop() == "3";
+l3.pop() == "3";
+
+// keyValueIterator
+var l4 = new List();
+l4.add(1);
+l4.add(2);
+l4.add(3);
+l4.add(5);
+l4.add(8);
+[for (k=>v in l4) k] == [0,1,2,3,4];
+[for (k=>v in l4) v] == [1,2,3,5,8];
+[for (k=>v in l4) k*v] == [0,2,6,15,32];