Last active
October 7, 2019 22:09
-
-
Save jeremyckahn/d745bc5cd1da96a94f4d7a2094d923d4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const points = ["v1x", "v1y", "v1z", "v2x", "v2y", "v2z", "v3x", "v3y", "v3z"]; | |
| class Trie { | |
| children = {}; | |
| insert(triangle, order = 0) { | |
| if (order === points.length) { | |
| return; | |
| } | |
| const k = triangle[order]; | |
| if (this.children[k] === undefined) { | |
| this.children[k] = new Trie(); | |
| } | |
| this.children[k].insert(triangle, order + 1); | |
| } | |
| getAllTriangles(key = null, order = 0, acc = {}, triangleStack = []) { | |
| const keys = Object.keys(this.children); | |
| if (key !== null) { | |
| acc = { ...acc, [points[order - 1]]: Number(key) }; | |
| } | |
| if (order === points.length) { | |
| triangleStack.push(acc); | |
| } | |
| keys.forEach(k => { | |
| this.children[k].getAllTriangles(k, order + 1, acc, triangleStack); | |
| }); | |
| return triangleStack; | |
| } | |
| } | |
| const flattenedTriangles = triangles.map(({ v1, v2, v3 }) => { | |
| // Ensure that vertices are "sorted" within the object | |
| [v1, v2, v3] = [v1, v2, v3].sort( | |
| (vA, vB) => vA.x - vB.x || vA.y - vB.y || vA.z - vB.z | |
| ); | |
| return [v1.x, v1.y, v1.z, v2.x, v2.y, v2.z, v3.x, v3.y, v3.z]; | |
| }); | |
| const trie = new Trie(); | |
| flattenedTriangles.forEach(triangle => trie.insert(triangle)); | |
| console.log(trie.getAllTriangles()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment