DarkRewar/BaseTool

Add Array and Range extensions

Closed this issue · 0 comments

Add array extension to use ForEach((value, index) => {}) callback

    public static class ArrayExtensions
    {
        public static void ForEach<T>(this T[] array, Action<T> callback)
        {
            for (int i = 0; i < array.Length; i++) { callback.Invoke(array[i]); }
        }

        public static void ForEach<T>(this T[] array, Action<T, int> callback)
        {
            for (int i = 0; i < array.Length; i++) { callback.Invoke(array[i], i); }
        }
    }

It will allow to do :

Button[] buttons = new Buttons[5];
buttons.ForEach((button, index) =>
{
    button.onClick.AddListener(() => DoSomething(index));
});

Add Range extension to use range int in foreach loops

public static class RangeExtensions
{
    public static RangeEnumerator GetEnumerator(this Range range)
    {
        if (range.Start.IsFromEnd || range.End.IsFromEnd)
        {
            throw new ArgumentException(nameof(range));
        }

        return new RangeEnumerator(range.Start.Value, range.End.Value);
    }

    public struct RangeEnumerator : IEnumerator<int>
    {
        private readonly int _end;
        private int _current;

        public RangeEnumerator(int start, int end)
        {
            _current = start - 1; // - 1 fixes a bug in the original code
            _end = end;
        }

        public int Current => _current;
        object IEnumerator.Current => Current;

        public bool MoveNext() => ++_current < _end;

        public void Dispose() { }
        public void Reset()
        {
            throw new NotImplementedException();
        }
    }
}

It will allow to do :

foreach(var i in 0..5)
{
    // Do something
}