Ver Fonte

Added Lambda.foldi function. (#9054)

* Added Lambda.reduce function.

* Update Lambda.hx

* Replaced spaces with tabs.

* Added unit tests.

* Fixed comment.
JaviCerveraIngram há 5 anos atrás
pai
commit
a6ae54ba35
2 ficheiros alterados com 19 adições e 0 exclusões
  1. 14 0
      std/Lambda.hx
  2. 5 0
      tests/unit/src/unitstd/Lambda.unit.hx

+ 14 - 0
std/Lambda.hx

@@ -186,6 +186,20 @@ class Lambda {
 		return first;
 		return first;
 	}
 	}
 
 
+	/**
+		Similar to fold, but also passes the index of each element to `f`.
+
+		If `it` or `f` are null, the result is unspecified.
+	**/
+	public static function foldi<A, B>(it:Iterable<A>, f:(item:A, result:B, index:Int) -> B, first:B):B {
+		var i = 0;
+		for (x in it) {
+			first = f(x, first, i);
+			++i;
+		}
+		return first;
+	}
+
 	/**
 	/**
 		Returns the number of elements in `it` for which `pred` is true, or the
 		Returns the number of elements in `it` for which `pred` is true, or the
 		total number of elements in `it` if `pred` is null.
 		total number of elements in `it` if `pred` is null.

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

@@ -91,6 +91,11 @@ Lambda.fold(["b","c","d"],function(s,acc) return s + acc,"a") == "dcba";
 Lambda.fold([],function(s:String,acc) return s + acc,"a") == "a";
 Lambda.fold([],function(s:String,acc) return s + acc,"a") == "a";
 Lambda.fold([],function(s:String,acc) return s + acc,null) == null;
 Lambda.fold([],function(s:String,acc) return s + acc,null) == null;
 
 
+// foldi
+Lambda.foldi(["b","c","d"],function(s,acc,i) return Std.string(i) + s + acc,"a") == "2d1c0ba";
+Lambda.foldi([],function(s:String,acc,i) return Std.string(i) + s + acc,"a") == "a";
+Lambda.foldi([],function(s:String,acc,i) return Std.string(i) + s + acc,null) == null;
+
 // count
 // count
 Lambda.count([1,2,3]) == 3;
 Lambda.count([1,2,3]) == 3;
 Lambda.count([1,2,3], function(x) return false) == 0;
 Lambda.count([1,2,3], function(x) return false) == 0;