-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: reduce size of node positions in url
- Loading branch information
1 parent
99e0da7
commit f9505d7
Showing
4 changed files
with
58 additions
and
28 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
import { Vector2D } from './vector-2d.js'; | ||
import { encode, decode } from '@msgpack/msgpack'; | ||
|
||
/** | ||
* Data type for storing node positions. | ||
*/ | ||
export class NodePositions extends Map<number, Vector2D> { | ||
/** | ||
* Converts a NodePositions object to a string. | ||
*/ | ||
toString(): string { | ||
const flatPositions: number[] = []; | ||
|
||
for (const [id, { x, y }] of this) { | ||
flatPositions.push(id, x, y); | ||
} | ||
|
||
const encoded = encode(flatPositions); | ||
|
||
console.log(JSON.stringify(flatPositions)); | ||
|
||
return btoa(String.fromCharCode(...encoded)); | ||
} | ||
|
||
/** | ||
* Converts a string to a NodePositions object. | ||
*/ | ||
static fromString(str: string): NodePositions { | ||
const decoded = decode( | ||
Uint8Array.from(atob(str), (c) => c.charCodeAt(0)), | ||
) as number[]; | ||
|
||
const positions = new NodePositions(); | ||
|
||
for (let i = 0; i < decoded.length; i += 3) { | ||
positions.set(decoded[i], new Vector2D(decoded[i + 1], decoded[i + 2])); | ||
} | ||
|
||
return positions; | ||
} | ||
} |