2022-12-23 12:38:51 -05:00
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
2022-12-23 12:35:10 -05:00
|
|
|
|
using System.Linq;
|
2022-12-23 12:38:51 -05:00
|
|
|
|
|
|
|
|
|
namespace FruityFoundation.Base.Structures;
|
2021-11-19 00:12:02 -05:00
|
|
|
|
|
|
|
|
|
public static class MaybeExtensions
|
|
|
|
|
{
|
2022-09-23 21:08:48 -04:00
|
|
|
|
public static Maybe<T> FirstOrEmpty<T>(this IEnumerable<T> collection)
|
|
|
|
|
{
|
|
|
|
|
using var enumerator = collection.GetEnumerator();
|
|
|
|
|
|
|
|
|
|
return !enumerator.MoveNext() ? Maybe<T>.Empty() : enumerator.Current;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static Maybe<T> FirstOrEmpty<T>(this IEnumerable<T> collection, Func<T, bool> pred)
|
|
|
|
|
{
|
|
|
|
|
foreach (var item in collection)
|
|
|
|
|
if (pred(item))
|
|
|
|
|
return item;
|
|
|
|
|
|
|
|
|
|
return Maybe<T>.Empty();
|
|
|
|
|
}
|
2021-11-19 00:12:02 -05:00
|
|
|
|
|
|
|
|
|
public static T? ToNullable<T>(this Maybe<T> item) where T : struct =>
|
|
|
|
|
item.HasValue ? item.Value : null;
|
2022-12-23 12:35:10 -05:00
|
|
|
|
|
|
|
|
|
public static IEnumerable<TOutput> Choose<TInput, TOutput>(this IEnumerable<TInput> enumerable, Func<TInput, Maybe<TOutput>> mapper) =>
|
|
|
|
|
enumerable
|
|
|
|
|
.Select(mapper)
|
|
|
|
|
.Where(x => x.HasValue)
|
|
|
|
|
.Select(x => x.Value);
|
2021-11-19 00:12:02 -05:00
|
|
|
|
}
|