cc-haxe/src/lib/Extender.hx
2022-12-19 21:06:23 +01:00

70 lines
1.3 KiB
Haxe

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;
}
}