I am trying to write a JavaScript function that removes items from an array to reach a defined length. The function should eliminate the "gaps" evenly through the array. I need this function to simplify polygon vertices for canvas drawing.
This is how it should work:
This is the code I came up with:
function simplify(array, vertices) {
// Calculate gap size
var gap = array.length - vertices;
gap = Math.floor(array.length / gap);
var count = 0;
var result = [];
// Fill a new array
for (var i = 0; i < array.length; i++) {
if (count == gap) {
count = 0;
} else {
result.push(array[i]);
count++;
}
}
// Eliminate 1 item in the middle if length is odd
if (result.length > vertices) {
result.splice(Math.floor(result.length / 2), 1);
}
return result;
}
// This gives the wrong result depending on the length of the input!
// The result should be an array with the length of 3
console.log(simplify([
{ x: 10, y: 20 },
{ x: 30, y: 40 },
{ x: 40, y: 50 },
{ x: 50, y: 60 }
], 3))
However, this only seems to work sometimes and the problem may be in the math. What's the algorithm that can achieve this or what am I doing wrong?
