using System.Security.Cryptography; namespace Nadeko.Common; // made for expressions because they almost never get added // and they get looped through constantly public static class ArrayExtensions { /// /// Create a new array from the old array + new element at the end /// /// Input array /// Item to add to the end of the output array /// Type of the array /// A new array with the new element at the end public static T[] With(this T[] input, T added) { var newExprs = new T[input.Length + 1]; Array.Copy(input, 0, newExprs, 0, input.Length); newExprs[input.Length] = added; return newExprs; } /// /// Creates a new array by applying the specified function to every element in the input array /// /// Array to modify /// Function to apply /// Orignal type of the elements in the array /// Output type of the elements of the array /// New array with updated elements public static TOut[] Map(this TIn[] arr, Func f) => Array.ConvertAll(arr, x => f(x)); /// /// Creates a new array by applying the specified function to every element in the input array /// /// Array to modify /// Function to apply /// Orignal type of the elements in the array /// Output type of the elements of the array /// New array with updated elements public static TOut[] Map(this IReadOnlyCollection col, Func f) { var toReturn = new TOut[col.Count]; var i = 0; foreach (var item in col) toReturn[i++] = f(item); return toReturn; } public static T? RandomOrDefault(this T[] data) { if (data.Length == 0) return default; var index = RandomNumberGenerator.GetInt32(0, data.Length); return data[index]; } }