Browse Source

Added Lambda.findIndex() (#9071)

* Add unit tests to Lambda.find

* Add Lambda.findIndex

* Use short lambdas for new codes
kaikoga 5 years ago
parent
commit
452cfec4b4
2 changed files with 38 additions and 0 deletions
  1. 20 0
      std/Lambda.hx
  2. 18 0
      tests/unit/src/unitstd/Lambda.unit.hx

+ 20 - 0
std/Lambda.hx

@@ -260,6 +260,26 @@ class Lambda {
 		return null;
 		return null;
 	}
 	}
 
 
+	/**
+		Returns the index of the first element of `it` for which `f` is true.
+
+		This function returns as soon as an element is found for which a call to
+		`f` returns true.
+
+		If no such element is found, the result is -1.
+
+		If `f` is null, the result is unspecified.
+	**/
+	public static function findIndex<T>(it:Iterable<T>, f:(item:T) -> Bool):Int {
+		var i = 0;
+		for (v in it) {
+			if (f(v))
+				return i;
+			i++;
+		}
+		return -1;
+	}
+
 	/**
 	/**
 		Returns a new Array containing all elements of Iterable `a` followed by
 		Returns a new Array containing all elements of Iterable `a` followed by
 		all elements of Iterable `b`.
 		all elements of Iterable `b`.

+ 18 - 0
tests/unit/src/unitstd/Lambda.unit.hx

@@ -115,6 +115,24 @@ Lambda.indexOf([1,2,3,3],3) == 2;
 Lambda.indexOf([1,2,3],4) == -1;
 Lambda.indexOf([1,2,3],4) == -1;
 Lambda.indexOf([],1) == -1;
 Lambda.indexOf([],1) == -1;
 
 
+// find
+Lambda.find([1,2,3,4,5],i -> i % 2 == 0) == 2;
+Lambda.find([1,2,3,4,5],i -> i % 4 == 0) == 4;
+Lambda.find([1,2,3,4,5],i -> i % 8 == 0) == null;
+Lambda.find([1,2,3,4,5],i -> true) == 1;
+Lambda.find([1,2,3,4,5],i -> false) == null;
+Lambda.find([],i -> true) == null;
+Lambda.find([],i -> false) == null;
+
+// findIndex
+Lambda.findIndex([1,2,3,4,5],i -> i % 2 == 0) == 1;
+Lambda.findIndex([1,2,3,4,5],i -> i % 4 == 0) == 3;
+Lambda.findIndex([1,2,3,4,5],i -> i % 8 == 0) == -1;
+Lambda.findIndex([1,2,3,4,5],i -> true) == 0;
+Lambda.findIndex([1,2,3,4,5],i -> false) == -1;
+Lambda.findIndex([],i -> true) == -1;
+Lambda.findIndex([],i -> false) == -1;
+
 // concat
 // concat
 Lambda.array(Lambda.concat([1,2,3],[3,4,5])) == [1,2,3,3,4,5];
 Lambda.array(Lambda.concat([1,2,3],[3,4,5])) == [1,2,3,3,4,5];
 Lambda.array(Lambda.concat([1,2,3],[])) == [1,2,3];
 Lambda.array(Lambda.concat([1,2,3],[])) == [1,2,3];