xaviergonz / js-angusj-clipper

Polygon and line clipping and offsetting library (Javascript) - a port of Angus Johnson's clipper
MIT License
162 stars 19 forks source link

functions.scalePath is reversing the order of the path #29

Closed cmidgley closed 1 year ago

cmidgley commented 1 year ago

In functions.scalePath the following code ends up reversing the order of the path when scaling:

    scalePath(path: ReadonlyPath, scale: number): Path {
        const sol: Path = [];
        let i = path.length;
        while (i--) {
          const p = path[i];
          sol.push({
            x: Math.round(p.x * scale),
            y: Math.round(p.y * scale),
          });
        }
        return sol;
      }

This is because it starts at the end of the array (I assume for performance reasons) and walks to the front, but then it creates the new array using push which results in reversing the direction.

While not quite as performant, the following works (and is better than using sol.unshift) as does not change the order of the path array:

    scalePath(path: ReadonlyPath, scale: number): Path {
        const sol: Path = [];
        const len = path.length;
        for (let i = 0; i < len; ++i) {
          const p = path[i];
          sol.push({
            x: Math.round(p.x * scale),
            y: Math.round(p.y * scale),
          });
        }
        return sol;
      }
xaviergonz commented 1 year ago

Thanks! that was a bug, it shouldn't have been reversed in the first place. fixed in v1.3.1