I have been working on developing a JavaScript function that can remove elements from an array to meet a specific length, ensuring that the "gaps" are evenly distributed across the array. The ultimate goal is to simplify polygon vertices for drawing on a canvas.
Here is the approach I have taken:
https://i.sstatic.net/H6oSl.png
This is the code snippet I have come 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 = [];
// Populate a new array without gaps
for (var i = 0; i < array.length; i++) {
if (count == gap) {
count = 0;
} else {
result.push(array[i]);
count++;
}
}
// Remove one item in the middle if the resulting length is odd
if (result.length > vertices) {
result.splice(Math.floor(result.length / 2), 1);
}
return result;
}
// The current implementation is giving unexpected results depending on input length!
// The expected output should be an array with a length of 3
console.log(simplify([
{ x: 10, y: 20 },
{ x: 30, y: 40 },
{ x: 40, y: 50 },
{ x: 50, y: 60 }
], 3))
Despite my efforts, it appears that this function works only intermittently, leading me to believe there may be issues within the mathematical calculations. Can someone provide insight into an improved algorithm or identify any mistakes I might be making?