another big refactor
This commit is contained in:
69
src/lib/Extender.hx
Normal file
69
src/lib/Extender.hx
Normal file
@@ -0,0 +1,69 @@
|
||||
package lib;
|
||||
|
||||
import haxe.Exception;
|
||||
|
||||
class LambdaExtender {
|
||||
/**
|
||||
Returns the first element if there are exectly one element present.
|
||||
Throws exception if not.
|
||||
**/
|
||||
static public function single<T>(it:Iterable<T>):T {
|
||||
var elem:T = null;
|
||||
for (t in it) {
|
||||
if (elem != null) {
|
||||
throw new Exception("Multiple elements found");
|
||||
}
|
||||
elem = t;
|
||||
}
|
||||
|
||||
if (elem == null) {
|
||||
throw new Exception("No element found");
|
||||
}
|
||||
|
||||
return elem;
|
||||
}
|
||||
|
||||
/**
|
||||
Like `single` but when no element was found return the default value.
|
||||
**/
|
||||
static public function singleOrDefault<T>(it:Iterable<T>, defaultValue:T):T {
|
||||
var elem:T = null;
|
||||
for (t in it) {
|
||||
if (elem != null) {
|
||||
throw new Exception("Multiple elements found");
|
||||
}
|
||||
elem = t;
|
||||
}
|
||||
|
||||
if (elem == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
return elem;
|
||||
}
|
||||
|
||||
/**
|
||||
Returns the first element.
|
||||
Throws execption if no first element found.
|
||||
**/
|
||||
static public function first<T>(it:Iterable<T>):T {
|
||||
for (t in it) {
|
||||
return t;
|
||||
}
|
||||
|
||||
throw new Exception("No element found");
|
||||
}
|
||||
|
||||
/**
|
||||
Like `first` only if no first element was found it returns the defalt value.
|
||||
**/
|
||||
static public function firstOrDefault<T>(it:Iterable<T>, defaultValue:T):T {
|
||||
var iter = it.iterator();
|
||||
|
||||
if (iter.hasNext()) {
|
||||
return iter.next();
|
||||
}
|
||||
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user