namespace Zinnia.Extension { using System.Collections.Generic; using UnityEngine; /// /// Extended methods for . /// public static class IReadOnlyCollectionExtensions { /// /// Returns a clamped collection index to prevent an index being out of bounds. /// /// /// An index less than zero will return the element based on that index value starting from the end of the collection. /// /// /// ReadOnlyCollection[] { A, B, C, D, E } /// > ReadOnlyCollection[1] -> 1 (B) /// > ReadOnlyCollection[-1] -> 4 (E) /// > ReadOnlyCollection[-2] -> 3 (D) /// > ReadOnlyCollection[7] -> 4 (E) /// > ReadOnlyCollection[-7] -> 0 (A) /// > ReadOnlyCollection[-2, false] -> 0 (A) /// /// The type of the source. /// The source . /// The index of the collection to clamp. /// Whether to treat a negative index to walk backwards through the collection from the upper bounds. /// The clamped index to be within the bounds of the collection. public static int ClampIndex(this IReadOnlyCollection source, int index, bool negativeIndexWalksFromEnd = true) { index = index >= 0 || !negativeIndexWalksFromEnd ? index : source.Count + index; return Mathf.Clamp(index, 0, source.Count - 1); } } }