Typescript calculate gaps in ranges

Date: 2019-06-18
interface IRange { min: number, max: number }
const range = (min:number, max: number) => ({min, max});

function findGaps(parent: IRange, children: IRange[]): IRange[] {
    children.sort((a, b) => a.min - b.min); // sort for deduce range values
    let currentMin = parent.min; // absolute minimum
    return children.reduce((gaps, curr, index, arr) => {            
        const min = Math.max(currentMin, parent.min);
        const max = Math.min(curr.min, parent.max);
        if (max > min) {
            gaps.push(range(min, max));
        }            
        currentMin = curr.max;
        if  (index + 1 == arr.length && currentMin < parent.max) {
            gaps.push(range(currentMin + 1, parent.max));
        }
        return gaps;
    }, []);
}

const gaps = findGaps(
    range(0, 10), [
        range(2,4),
        range(6,9)
    ]);
console.log("gaps", gaps);
// 0: {min: 0, max: 2}
// 1: {min: 4, max: 6}
// 2: {min: 10, max: 10}

C# (Integer) version

void Main()
{
	var parent = GapsHelper.GetRange(0, 50);

	var children = new List<IRange>() {
		GapsHelper.GetRange(5, 9),
		GapsHelper.GetRange(11, 15),
		GapsHelper.GetRange(15, 30),
		GapsHelper.GetRange(32, 40),
	};
	var gaps2 = GapsHelper.FindGaps(parent, children);
	Console.WriteLine(gaps2);
/*
0 - 4 
10 - 10 
31 - 31 
41 - 50 
*/
}

public interface IRange
{
    int Min { get; set; }
    int Max { get; set; }
}

public class Range : IRange
{
    public int Min { get; set; }
    public int Max { get; set; }
}

public class GapsHelper
{
    public static IRange GetRange(int min, int max) => new Range { Min = min, Max = max };

    public static IEnumerable<IRange> FindGaps(IRange parent, List<IRange> children)
    {
        children.Sort((a, b) => a.Min - b.Min); // sort for deduce range values
        var currentMin = parent.Min - 1; // absolute minimum
        var index = 0;
        return children.Aggregate(new List<IRange>(), (gaps, curr) => // List<IRange> , Range
        {
            index++;

            var min = Math.Max(currentMin + 1, parent.Min);
            var max = Math.Min(curr.Min - 1, parent.Max);
            if (max >= min)
		gaps.Add(GetRange(min, max));
            
            currentMin = curr.Max;
            if (index == children.Count && currentMin < parent.Max)
                gaps.Add(GetRange(currentMin + 1, parent.Max));
            return gaps;
        });
    }
}
22220cookie-checkTypescript calculate gaps in ranges