using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using Random = UnityEngine.Random; public static class ArrayExtensions { public static T First(this IList list) { if (list.IsEmpty()) throw new ArgumentOutOfRangeException(); return list[0]; } public static bool Contains([JetBrains.Annotations.NotNull] this IList list, Func predicate) { if (list == null) throw new ArgumentNullException(nameof(list)); for (int i = list.Count - 1; i >= 0; i--) if (predicate.Invoke(list[i])) return true; return false; } public static int GetNextLoopedIndex(this IList list, int current) { return list.GetLoopedIndex(current + 1); } public static int GetLoopedIndex(this IList list, int index) { return (int) Mathf.Repeat(index, list.Count); } public static bool HasIndex(this IList list, int index) { return index >= 0 && list.Count > index; } public static bool HasOnlyNulls(this IList list) { for (int i = list.Count - 1; i >= 0; i--) if (list[i] != null) return false; return true; } public static bool IsEmpty(this IList list) { return list.Count == 0; } public static void ForEach(this IEnumerable list, Action action) { foreach (T element in list) action(element); } public static void ForEach(this IList list, Func action) { for (int i = 0; i < list.Count(); i++) { list[i] = action(); } } public static T Last(this IList list) { if (list.IsEmpty()) throw new ArgumentOutOfRangeException(); return list[list.Count - 1]; } public static T RandomValue(this IList list) { if (list.IsEmpty()) throw new ArgumentOutOfRangeException(); return list[Random.Range(0, list.Count)]; } public static IList Swap(this IList list, int a, int b) { T tmp = list[a]; list[a] = list[b]; list[b] = tmp; return list; } public static void Shuffle(this IList list, int seed = -1) { var old = Random.state; if (seed >= 0) Random.InitState(seed); int n = list.Count; while (n > 1) { --n; int k = Random.Range(0, n); T value = list[k]; list[k] = list[n]; list[n] = value; } Random.state = old; } public static void AddRange(this IList self, IList list) { for (int i = 0; i < list.Count; ++i) self.Add(list[i]); } public static void Assign(ref List dst, IEnumerable src) { if (src == null) return; if (dst == null) { dst = new List(src); } else { dst.Clear(); dst.AddRange(src); } } public static bool AddUnique(this IList dst, T o) { if (dst.Contains(o)) return false; dst.Add(o); return true; } public static void AddUnique(this IList dst, IList src) { for (int i = 0; i < src.Count; ++i) dst.AddUnique(src[i]); } public static bool ContainsAnyOf(this IList list, IList other) { for (int i = 0; i < other.Count; ++i) { if (list.Contains(other[i])) return true; } return false; } public static T GetOr(this IList list, int idx, T defaultValue) { return idx >= 0 && idx < list.Count ? list[idx] : defaultValue; } }