Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 18 additions & 22 deletions lib/solvers/TraceCleanupSolver/simplifyPath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
43 changes: 43 additions & 0 deletions tests/functions/simplifyPath.test.ts
Original file line number Diff line number Diff line change
@@ -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)
})
Loading