| [e4c61dd] | 1 | // Simple caching for constant-radius points.
|
|---|
| 2 | let cacheDigits, cacheAppend, cacheRadius, cacheCircle;
|
|---|
| 3 |
|
|---|
| 4 | export default class PathString {
|
|---|
| 5 | constructor(digits) {
|
|---|
| 6 | this._append = digits == null ? append : appendRound(digits);
|
|---|
| 7 | this._radius = 4.5;
|
|---|
| 8 | this._ = "";
|
|---|
| 9 | }
|
|---|
| 10 | pointRadius(_) {
|
|---|
| 11 | this._radius = +_;
|
|---|
| 12 | return this;
|
|---|
| 13 | }
|
|---|
| 14 | polygonStart() {
|
|---|
| 15 | this._line = 0;
|
|---|
| 16 | }
|
|---|
| 17 | polygonEnd() {
|
|---|
| 18 | this._line = NaN;
|
|---|
| 19 | }
|
|---|
| 20 | lineStart() {
|
|---|
| 21 | this._point = 0;
|
|---|
| 22 | }
|
|---|
| 23 | lineEnd() {
|
|---|
| 24 | if (this._line === 0) this._ += "Z";
|
|---|
| 25 | this._point = NaN;
|
|---|
| 26 | }
|
|---|
| 27 | point(x, y) {
|
|---|
| 28 | switch (this._point) {
|
|---|
| 29 | case 0: {
|
|---|
| 30 | this._append`M${x},${y}`;
|
|---|
| 31 | this._point = 1;
|
|---|
| 32 | break;
|
|---|
| 33 | }
|
|---|
| 34 | case 1: {
|
|---|
| 35 | this._append`L${x},${y}`;
|
|---|
| 36 | break;
|
|---|
| 37 | }
|
|---|
| 38 | default: {
|
|---|
| 39 | this._append`M${x},${y}`;
|
|---|
| 40 | if (this._radius !== cacheRadius || this._append !== cacheAppend) {
|
|---|
| 41 | const r = this._radius;
|
|---|
| 42 | const s = this._;
|
|---|
| 43 | this._ = ""; // stash the old string so we can cache the circle path fragment
|
|---|
| 44 | this._append`m0,${r}a${r},${r} 0 1,1 0,${-2 * r}a${r},${r} 0 1,1 0,${2 * r}z`;
|
|---|
| 45 | cacheRadius = r;
|
|---|
| 46 | cacheAppend = this._append;
|
|---|
| 47 | cacheCircle = this._;
|
|---|
| 48 | this._ = s;
|
|---|
| 49 | }
|
|---|
| 50 | this._ += cacheCircle;
|
|---|
| 51 | break;
|
|---|
| 52 | }
|
|---|
| 53 | }
|
|---|
| 54 | }
|
|---|
| 55 | result() {
|
|---|
| 56 | const result = this._;
|
|---|
| 57 | this._ = "";
|
|---|
| 58 | return result.length ? result : null;
|
|---|
| 59 | }
|
|---|
| 60 | }
|
|---|
| 61 |
|
|---|
| 62 | function append(strings) {
|
|---|
| 63 | let i = 1;
|
|---|
| 64 | this._ += strings[0];
|
|---|
| 65 | for (const j = strings.length; i < j; ++i) {
|
|---|
| 66 | this._ += arguments[i] + strings[i];
|
|---|
| 67 | }
|
|---|
| 68 | }
|
|---|
| 69 |
|
|---|
| 70 | function appendRound(digits) {
|
|---|
| 71 | const d = Math.floor(digits);
|
|---|
| 72 | if (!(d >= 0)) throw new RangeError(`invalid digits: ${digits}`);
|
|---|
| 73 | if (d > 15) return append;
|
|---|
| 74 | if (d !== cacheDigits) {
|
|---|
| 75 | const k = 10 ** d;
|
|---|
| 76 | cacheDigits = d;
|
|---|
| 77 | cacheAppend = function append(strings) {
|
|---|
| 78 | let i = 1;
|
|---|
| 79 | this._ += strings[0];
|
|---|
| 80 | for (const j = strings.length; i < j; ++i) {
|
|---|
| 81 | this._ += Math.round(arguments[i] * k) / k + strings[i];
|
|---|
| 82 | }
|
|---|
| 83 | };
|
|---|
| 84 | }
|
|---|
| 85 | return cacheAppend;
|
|---|
| 86 | }
|
|---|