JSFiddle - React, Tailwind, and code Playground
epg intesection test
by Csaba Hellinger
JavaScript
function intersection(a, b) {
if (a.end < b.begin || b.end < a.begin) {
return 0;
}
const values = [a.begin, a.end, b.begin, b.end].sort();
return values[2] - values[1];
}
function maxIntersection(programs, withProgram) {
const intersections = programs.map(program => intersection(program, withProgram)),
max = Math.max(...intersections),
maxIndex = intersections.indexOf(max);
return maxIndex;
}
function test(desc, value, expected) {
console.log(value === expected ? 'pass' : 'fail', ':', desc);
}
console.clear();
test('A in B', intersection({ begin: 6, end: 7 }, { begin: 1, end: 8 }), 1);
test('B in A', intersection({ begin: 1, end: 5 }, { begin: 2, end: 4 }), 2);
test('A then B', intersection({ begin: 1, end: 6 }, { begin: 3, end: 8 }), 3);
test('B then A', intersection({ begin: 5, end: 9 }, { begin: 1, end: 6 }), 1);
test('A before B', intersection({ begin: 1, end: 3 }, { begin: 3, end: 6 }), 0);
test('B before A', intersection({ begin: 5, end: 7 }, { begin: 2, end: 4 }), 0);
const prgs = [
{ begin: 1, end: 2 }, // 0: 0
{ begin: 1, end: 4 }, // 1: 1
{ begin: 2, end: 8 }, // 2: 4 (max)
{ begin: 4, end: 8 }, // 3: 3
{ begin: 5, end: 9 } // 4: 2
]
test('max', maxIntersection(prgs, { begin: 3, end: 7 }), 2);