From 6effff7d706d5eff6362ffdafb9232c6691ea0ea Mon Sep 17 00:00:00 2001 From: Patrick Hodel Date: Mon, 29 Nov 2021 20:20:41 +0100 Subject: [PATCH 1/2] Map function that accepts two mappers, one for the value and one for the exception. --- src/Optional/Option_Either.cs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/Optional/Option_Either.cs b/src/Optional/Option_Either.cs index b2179d7..ffa0412 100644 --- a/src/Optional/Option_Either.cs +++ b/src/Optional/Option_Either.cs @@ -403,6 +403,23 @@ public Option Map(Func mapping) ); } + /// + /// Transforms both, the inner value or the exceptional value in an optional. + /// + /// The transformation function for the inner value. + /// The transformation function for the exceptional value. + /// The transformed optional. + public Option Map(Func valueMapping, Func exceptionMapping) + { + if (valueMapping == null) throw new ArgumentNullException(nameof(valueMapping)); + if (exceptionMapping == null) throw new ArgumentNullException(nameof(exceptionMapping)); + + return Match( + some: value => Option.Some(valueMapping(value)), + none: exception => Option.None(exceptionMapping(exception)) + ); + } + /// /// Transforms the exceptional value in an optional. /// If the instance is not empty, no transformation is carried out. From 94830dede0e91268ebe29dcc6bfd0059a2c4d05d Mon Sep 17 00:00:00 2001 From: Patrick Hodel Date: Mon, 29 Nov 2021 21:02:57 +0100 Subject: [PATCH 2/2] Test for new Map method --- src/Optional.Tests/EitherTests.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/Optional.Tests/EitherTests.cs b/src/Optional.Tests/EitherTests.cs index a025602..a09892a 100644 --- a/src/Optional.Tests/EitherTests.cs +++ b/src/Optional.Tests/EitherTests.cs @@ -653,6 +653,9 @@ public void Either_Transformation() var noneExUpper = none.MapException(x => x.ToUpper()); var someExUpper = some.MapException(x => x.ToUpper()); + + var noneBothUpper = none.Map(x => string.Concat(x.Reverse()), x => x.ToUpper()); + var someBothReverse = some.Map(x => string.Concat(x.Reverse()), x => x.ToUpper()); Assert.IsFalse(noneUpper.HasValue); Assert.IsTrue(someUpper.HasValue); @@ -660,6 +663,8 @@ public void Either_Transformation() Assert.AreEqual(someUpper.ValueOr("ex"), "VAL"); Assert.AreEqual(noneExUpper.Match(val => val, ex => ex), "EX"); Assert.AreEqual(someExUpper.Match(val => val, ex => ex), "val"); + Assert.AreEqual(noneBothUpper.Match(val => val, ex => ex), "EX"); + Assert.AreEqual(someBothReverse.Match(val => val, ex => ex), "lav"); var noneNotNull = none.FlatMap(x => x.SomeNotNull("ex1")); var someNotNull = some.FlatMap(x => x.SomeNotNull("ex1"));