2022-12-19 20:06:23 +00:00
|
|
|
package lib;
|
2021-12-20 00:55:30 +00:00
|
|
|
|
|
|
|
import haxe.Exception;
|
|
|
|
|
|
|
|
class LambdaExtender {
|
|
|
|
/**
|
|
|
|
Returns the first element if there are exectly one element present.
|
|
|
|
Throws exception if not.
|
|
|
|
**/
|
2022-02-21 14:35:37 +00:00
|
|
|
static public function single<T>(it:Iterable<T>):T {
|
|
|
|
var elem:T = null;
|
2021-12-20 00:55:30 +00:00
|
|
|
for (t in it) {
|
2022-02-21 14:35:37 +00:00
|
|
|
if (elem != null) {
|
2021-12-20 00:55:30 +00:00
|
|
|
throw new Exception("Multiple elements found");
|
|
|
|
}
|
|
|
|
elem = t;
|
|
|
|
}
|
|
|
|
|
2022-02-21 14:35:37 +00:00
|
|
|
if (elem == null) {
|
2021-12-20 00:55:30 +00:00
|
|
|
throw new Exception("No element found");
|
|
|
|
}
|
|
|
|
|
|
|
|
return elem;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
Like `single` but when no element was found return the default value.
|
|
|
|
**/
|
2022-02-21 14:35:37 +00:00
|
|
|
static public function singleOrDefault<T>(it:Iterable<T>, defaultValue:T):T {
|
|
|
|
var elem:T = null;
|
2021-12-20 00:55:30 +00:00
|
|
|
for (t in it) {
|
2022-02-21 14:35:37 +00:00
|
|
|
if (elem != null) {
|
2021-12-20 00:55:30 +00:00
|
|
|
throw new Exception("Multiple elements found");
|
|
|
|
}
|
|
|
|
elem = t;
|
|
|
|
}
|
|
|
|
|
2022-02-21 14:35:37 +00:00
|
|
|
if (elem == null) {
|
2021-12-20 00:55:30 +00:00
|
|
|
return defaultValue;
|
|
|
|
}
|
|
|
|
|
|
|
|
return elem;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
Returns the first element.
|
|
|
|
Throws execption if no first element found.
|
|
|
|
**/
|
2022-02-21 14:35:37 +00:00
|
|
|
static public function first<T>(it:Iterable<T>):T {
|
2021-12-20 00:55:30 +00:00
|
|
|
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.
|
|
|
|
**/
|
2022-02-21 14:35:37 +00:00
|
|
|
static public function firstOrDefault<T>(it:Iterable<T>, defaultValue:T):T {
|
2021-12-20 00:55:30 +00:00
|
|
|
var iter = it.iterator();
|
|
|
|
|
2022-02-21 14:35:37 +00:00
|
|
|
if (iter.hasNext()) {
|
2021-12-20 00:55:30 +00:00
|
|
|
return iter.next();
|
|
|
|
}
|
|
|
|
|
|
|
|
return defaultValue;
|
|
|
|
}
|
|
|
|
}
|