diff --git a/lib/solvers/TraceCleanupSolver/simplifyPath.ts b/lib/solvers/TraceCleanupSolver/simplifyPath.ts index e17bfb52c..20bed2214 100644 --- a/lib/solvers/TraceCleanupSolver/simplifyPath.ts +++ b/lib/solvers/TraceCleanupSolver/simplifyPath.ts @@ -5,37 +5,33 @@ import { } from "lib/solvers/SchematicTraceLinesSolver/SchematicTraceSingleLineSolver2/collisions" export const simplifyPath = (path: Point[]): Point[] => { - if (path.length < 3) return path - const newPath: Point[] = [path[0]] - for (let i = 1; i < path.length - 1; i++) { - const p1 = newPath[newPath.length - 1] - const p2 = path[i] - const p3 = path[i + 1] - if ( - (isVertical(p1, p2) && isVertical(p2, p3)) || - (isHorizontal(p1, p2) && isHorizontal(p2, p3)) - ) { - continue + const dedupedPath: Point[] = [] + for (const pt of path) { + if (dedupedPath.length === 0) { + dedupedPath.push(pt) + } else { + const last = dedupedPath[dedupedPath.length - 1] + if (last.x !== pt.x || last.y !== pt.y) { + dedupedPath.push(pt) + } } - newPath.push(p2) } - newPath.push(path[path.length - 1]) - if (newPath.length < 3) return newPath - const finalPath: Point[] = [newPath[0]] - for (let i = 1; i < newPath.length - 1; i++) { - const p1 = finalPath[finalPath.length - 1] - const p2 = newPath[i] - const p3 = newPath[i + 1] + if (dedupedPath.length < 3) return dedupedPath + const newPath: Point[] = [dedupedPath[0]] + for (let i = 1; i < dedupedPath.length - 1; i++) { + const p1 = newPath[newPath.length - 1] + const p2 = dedupedPath[i] + const p3 = dedupedPath[i + 1] if ( (isVertical(p1, p2) && isVertical(p2, p3)) || (isHorizontal(p1, p2) && isHorizontal(p2, p3)) ) { continue } - finalPath.push(p2) + newPath.push(p2) } - finalPath.push(newPath[newPath.length - 1]) + newPath.push(dedupedPath[dedupedPath.length - 1]) - return finalPath + return newPath } diff --git a/tests/functions/simplifyPath.test.ts b/tests/functions/simplifyPath.test.ts new file mode 100644 index 000000000..2e8df120e --- /dev/null +++ b/tests/functions/simplifyPath.test.ts @@ -0,0 +1,43 @@ +import { simplifyPath } from "lib/solvers/TraceCleanupSolver/simplifyPath" +import { test, expect } from "bun:test" + +test("simplifyPath - collinear points", () => { + const path = [ + { x: 0, y: 0 }, + { x: 0, y: 1 }, + { x: 0, y: 2 }, + { x: 1, y: 2 }, + { x: 2, y: 2 }, + ] + const simplified = simplifyPath(path) + expect(simplified).toEqual([ + { x: 0, y: 0 }, + { x: 0, y: 2 }, + { x: 2, y: 2 }, + ]) +}) + +test("simplifyPath - duplicate consecutive points", () => { + const path = [ + { x: 0, y: 0 }, + { x: 0, y: 0 }, + { x: 1, y: 1 }, + { x: 1, y: 1 }, + { x: 2, y: 2 }, + ] + const simplified = simplifyPath(path) + expect(simplified).toEqual([ + { x: 0, y: 0 }, + { x: 1, y: 1 }, + { x: 2, y: 2 }, + ]) +}) + +test("simplifyPath - short path", () => { + const path = [ + { x: 0, y: 0 }, + { x: 1, y: 1 }, + ] + const simplified = simplifyPath(path) + expect(simplified).toEqual(path) +})