Middle
Practical task: given an array of points with fields time and value. Identify groups of points with the same value and keep only the start and end of each group (to optimize the construction of a linear graph).
sobes.tech AI
Answer from AI
To optimize the construction of a line chart, you need to group points by the same value and keep only the first and last point in each group by time. This will reduce the number of points without losing the shape of the chart.
Example solution in JavaScript:
function optimizePoints(points) {
if (points.length === 0) return [];
const result = [];
let start = points[0];
let prev = points[0];
for (let i = 1; i < points.length; i++) {
if (points[i].value !== prev.value) {
// End of group
result.push(start);
result.push(prev);
start = points[i];
}
prev = points[i];
}
// Add the last group
result.push(start);
result.push(prev);
// Remove duplicates if the group consists of one point
return result.filter((point, index, arr) => {
if (index === 0) return true;
const prevPoint = arr[index - 1];
return !(point.time === prevPoint.time && point.value === prevPoint.value);
});
}
// Example usage:
const data = [
{ time: 1, value: 10 },
{ time: 2, value: 10 },
{ time: 3, value: 15 },
{ time: 4, value: 15 },
{ time: 5, value: 15 },
{ time: 6, value: 10 },
];
console.log(optimizePoints(data));
This code iterates through the array of points, identifies groups with the same value, and keeps only the start and end points of each group.