Skip to content

Commit

Permalink
add map extension #9
Browse files Browse the repository at this point in the history
  • Loading branch information
Nness committed Dec 12, 2023
1 parent 96b26b6 commit ac142ba
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions src/Optional/OptionalExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Linq;

namespace DeskDirector.Text.Json
{
public static class OptionalExtensions
{
public static Optional<TTarget> Map<T, TTarget>(this Optional<T> input, Func<T, TTarget> map)
{
ArgumentNullException.ThrowIfNull(map);

if (!input.IsSet(out T? value)) {
return Optional<TTarget>.Undefined;
}

if (input.IsNull() || value is null) {
return Optional<TTarget>.Null;
}

TTarget target = map(value);
if (target is null) {
throw new InvalidOperationException(
$"Map function converted {typeof(T).Name} to {typeof(TTarget).Name} as NULL."
);
}

return new Optional<TTarget>(target);
}

public static OptionalCollection<TTarget> Map<T, TTarget>(this OptionalCollection<T> input,
Func<T, TTarget> map)
{
ArgumentNullException.ThrowIfNull(map);

if (!input.IsSet(out ICollection<T>? value)) {
return OptionalCollection<TTarget>.Undefined;
}

if (input.IsNull() || value is null) {
return OptionalCollection<TTarget>.Null;
}

TTarget[] targets = value.Select(map).ToArray();

return new OptionalCollection<TTarget>(targets);
}
}
}

0 comments on commit ac142ba

Please sign in to comment.