I am working on restructuring year ranges with gaps and consolidating them. For example, converting [{start: 2002, end: 2020}, {start: 2020, end: null}] to {start: 2002, end: null} or [{2002, 2004},{2006, 2008}, {2008, null}] to [{2002-2004}, {2006-null}].
This task is related to tracking politicians' party memberships using an API, dealing with complications when they switch parties or rejoin previous ones.
interface YearRange{
start: number
end: number
}
function analyzeYearGaps(yearRanges: any[]) {
let startingYears: number[] = [];
let endingYears: (number | null)[] = [];
let timePeriods: (number | null)[] = [];
for (let y of yearRanges) {
startingYears.push(y.start);
endingYears.push(y.end);
}
let matchedEndingYears: (number | null)[] = [];
let unmatchedEndingYears: (number | null)[] = [];
for (let e of endingYears) {
const found = startingYears.find((s) => s == e);
if (found) {
matchedEndingYears.push(found);
} else if (!found) {
unmatchedEndingYears.push(e);
}
}
if (unmatchedEndingYears.length > 0) {
let start: number;
for (let e of unmatchedEndingYears) {
let lesser: number[] = [];
if (e == null) {
if (startingYears.length > 1) {
start = Math.min(...startingYears);
} else {
start = startingYears[0];
}
} else if (e != null) {
lesser = startingYears.filter((s) => s < e);
start = Math.max(...lesser);
}
timePeriods.push({ start: start, end: e });
}
} else if (unmatchedEndingYears.length == 0) {
let start: number = Math.min(...startingYears);
let end: number | null;
if (endingYears.includes(null)) {
end = null;
} else {
end = Math.max(...endingYears);
}
timePeriods.push({ start: start, end: end });
}
console.log(timePeriods);
return timePeriods;
}