From dd66fb9a2b2476f3d4e4d5c3b504a9ceb76a5cee Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Sun, 17 Jan 2021 13:31:59 +0000 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Add=20IComparable.Clamp?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implements #24 --- .../ComparableExtensions.cs | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/X10D/src/ComparableExtensions/ComparableExtensions.cs b/X10D/src/ComparableExtensions/ComparableExtensions.cs index 7948775..4861484 100644 --- a/X10D/src/ComparableExtensions/ComparableExtensions.cs +++ b/X10D/src/ComparableExtensions/ComparableExtensions.cs @@ -50,6 +50,43 @@ namespace X10D.ComparableExtensions { return actual.CompareTo(lower) > 0 && actual.CompareTo(upper) < 0; } + + /// + /// Returns the current value clamped to the inclusive range of and . + /// + /// The value to be clamped. + /// The lower bound of the result. + /// The upper bound of the result. + /// An type. + /// + /// if . + /// -or- + /// if < . + /// -or- + /// if < . + /// + /// is greater than . + /// + /// + /// int value = 42; + /// int lower = 0; + /// int upper = 20; + /// + /// int clamped = value.Clamp(lower, upper); + /// // clamped will be 20 + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T Clamp(this T value, T lower, T upper) + where T : IComparable + { + if (lower.GreaterThan(upper)) + { + throw new ArgumentException($@"{lower} cannot be greater than {upper}", nameof(lower)); + } + + return value.Max(lower).Min(upper); + } /// /// Determines if the current value is greater than another value.