using System; using System.Collections.Generic; using System.Linq; namespace FruityFoundation.Base.Structures; public static class MaybeExtensions { public static Maybe FirstOrEmpty(this IEnumerable collection) { using var enumerator = collection.GetEnumerator(); return !enumerator.MoveNext() ? Maybe.Empty() : enumerator.Current; } public static Maybe FirstOrEmpty(this IEnumerable collection, Func pred) { foreach (var item in collection) if (pred(item)) return item; return Maybe.Empty(); } public static Maybe TryGetValue(this IDictionary dict, TKey key) => dict.TryGetValue(key, out var value) ? Maybe.Just(value) : Maybe.Empty(); public static Maybe TryGet(this IReadOnlyDictionary dict, TKey key) => dict.TryGetValue(key, out var value) ? Maybe.Just(value) : Maybe.Empty(); public static T? ToNullable(this Maybe item) where T : struct => item.HasValue ? item.Value : null; }