Algorithm for finding overlapping events/times

后端 未结 3 1726
不思量自难忘°
不思量自难忘° 2021-02-04 18:24

While working on custom calendar, I can\'t figure out how to find time slots that overlaps any other time slot.

Time slots start from 0 to 720 (9am to 9pm with each

3条回答
  •  余生分开走
    2021-02-04 19:11

    Here's code that will do what you want. As others have mentioned you'd probably be better served by storing date objects, but that's a different issue.

    function getOverlaps(events) {
        // sort events
        events.sort(function (a, b) {
            return a.start - b.start;
        });
    
        var results = [];
        for (var i = 0, l = events.length; i < l; i++) {
            var oEvent = events[i];
            var nOverlaps = 0;
            for (var j = 0; j < l; j++) {
                var oCompareEvent = events[j];
                if (oCompareEvent.start <= oEvent.end && oCompareEvent.end > oEvent.start || oCompareEvent.end <= oEvent.start && oCompareEvent.start > oEvent.end) {
                    nOverlaps++;
                }
            }
            if (nOverlaps > 1) {
                results.push({
                    id: oEvent.id,
                    eventCount: nOverlaps,
                    toString: function () {
                        return "[id:" + this.id + ", events:" + this.eventCount + "]"
                    }
                });
            }
    
        }
        return results;
    }
    

提交回复
热议问题