﻿using System;
using System.Collections.Generic;
using System.Linq;


namespace PlugToolkit.Collections.Extensions
{
    public static class ICollectionExtensions
    {
        // http://stackoverflow.com/a/594528/2279177
        /// <summary>
        /// Returns index of element using binary search algorithm
        /// </summary>
        public static int BinarySearch<T>(this ICollection<T> list, T value)
        {
            if (list == null)
            {
                throw new ArgumentNullException(nameof(list));
            }

            if (!list.Any())
            {
                return -1;
            }

            var comparer = Comparer<T>.Default;
            int min = 0, max = list.Count - 1;

            while (min < max)
            {
                int mid = (max + min) / 2;

                if (comparer.Compare(list.ElementAt(mid), value) < 0)
                {
                    min = mid + 1;
                }
                else
                {
                    max = mid - 1;
                }
            }

            if (comparer.Compare(list.ElementAt(min), value) < 0)
            {
                min++;
            }

            return min;
        }
    }
}
