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(it:Iterable):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(it:Iterable, 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(it:Iterable):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(it:Iterable, defaultValue:T):T { var iter = it.iterator(); if (iter.hasNext()) { return iter.next(); } return defaultValue; } }