oakscriptjs 0.15.1 → 0.15.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/dist/cjs/callsite/index.d.ts.map +1 -1
  2. package/dist/cjs/callsite/index.js +61 -7
  3. package/dist/cjs/callsite/index.js.map +2 -2
  4. package/dist/cjs/drawing/registry.d.ts +28 -3
  5. package/dist/cjs/drawing/registry.d.ts.map +1 -1
  6. package/dist/cjs/drawing/registry.js +109 -42
  7. package/dist/cjs/drawing/registry.js.map +2 -2
  8. package/dist/cjs/index.d.ts +1 -1
  9. package/dist/cjs/index.js +1 -1
  10. package/dist/cjs/index.js.map +1 -1
  11. package/dist/cjs/linefill/index.d.ts.map +1 -1
  12. package/dist/cjs/linefill/index.js +14 -5
  13. package/dist/cjs/linefill/index.js.map +2 -2
  14. package/dist/cjs/str/floatingdecimal.d.ts +3 -0
  15. package/dist/cjs/str/floatingdecimal.d.ts.map +1 -1
  16. package/dist/cjs/str/floatingdecimal.js +25 -12
  17. package/dist/cjs/str/floatingdecimal.js.map +2 -2
  18. package/dist/cjs/str/messageformat.d.ts.map +1 -1
  19. package/dist/cjs/str/messageformat.js +27 -8
  20. package/dist/cjs/str/messageformat.js.map +2 -2
  21. package/dist/cjs/str/numberformat.d.ts.map +1 -1
  22. package/dist/cjs/str/numberformat.js +9 -16
  23. package/dist/cjs/str/numberformat.js.map +3 -3
  24. package/dist/cjs/ta/index.d.ts.map +1 -1
  25. package/dist/cjs/ta/index.js +27 -0
  26. package/dist/cjs/ta/index.js.map +2 -2
  27. package/dist/cjs/ta/running-sum.d.ts +8 -1
  28. package/dist/cjs/ta/running-sum.d.ts.map +1 -1
  29. package/dist/cjs/ta/running-sum.js +13 -1
  30. package/dist/cjs/ta/running-sum.js.map +2 -2
  31. package/dist/cjs/time/timezone.d.ts.map +1 -1
  32. package/dist/cjs/time/timezone.js +14 -1
  33. package/dist/cjs/time/timezone.js.map +2 -2
  34. package/dist/esm/callsite/index.d.ts.map +1 -1
  35. package/dist/esm/callsite/index.js +76 -7
  36. package/dist/esm/callsite/index.js.map +1 -1
  37. package/dist/esm/drawing/registry.d.ts +28 -3
  38. package/dist/esm/drawing/registry.d.ts.map +1 -1
  39. package/dist/esm/drawing/registry.js +147 -54
  40. package/dist/esm/drawing/registry.js.map +1 -1
  41. package/dist/esm/index.d.ts +1 -1
  42. package/dist/esm/index.js +1 -1
  43. package/dist/esm/linefill/index.d.ts.map +1 -1
  44. package/dist/esm/linefill/index.js +17 -7
  45. package/dist/esm/linefill/index.js.map +1 -1
  46. package/dist/esm/str/floatingdecimal.d.ts +3 -0
  47. package/dist/esm/str/floatingdecimal.d.ts.map +1 -1
  48. package/dist/esm/str/floatingdecimal.js +27 -11
  49. package/dist/esm/str/floatingdecimal.js.map +1 -1
  50. package/dist/esm/str/messageformat.d.ts.map +1 -1
  51. package/dist/esm/str/messageformat.js +35 -9
  52. package/dist/esm/str/messageformat.js.map +1 -1
  53. package/dist/esm/str/numberformat.d.ts.map +1 -1
  54. package/dist/esm/str/numberformat.js +12 -18
  55. package/dist/esm/str/numberformat.js.map +1 -1
  56. package/dist/esm/ta/index.d.ts.map +1 -1
  57. package/dist/esm/ta/index.js +35 -0
  58. package/dist/esm/ta/index.js.map +1 -1
  59. package/dist/esm/ta/running-sum.d.ts +8 -1
  60. package/dist/esm/ta/running-sum.d.ts.map +1 -1
  61. package/dist/esm/ta/running-sum.js +16 -1
  62. package/dist/esm/ta/running-sum.js.map +1 -1
  63. package/dist/esm/time/timezone.d.ts.map +1 -1
  64. package/dist/esm/time/timezone.js +23 -3
  65. package/dist/esm/time/timezone.js.map +1 -1
  66. package/package.json +1 -1
  67. package/src/callsite/index.ts +65 -7
  68. package/src/drawing/registry.ts +149 -50
  69. package/src/index.ts +1 -1
  70. package/src/linefill/index.ts +16 -7
  71. package/src/str/floatingdecimal.ts +27 -11
  72. package/src/str/messageformat.ts +40 -9
  73. package/src/str/numberformat.ts +13 -17
  74. package/src/ta/index.ts +41 -0
  75. package/src/ta/running-sum.ts +13 -1
  76. package/src/time/timezone.ts +26 -4
@@ -190,10 +190,22 @@ export function cross(): (a: number, b: number) => boolean {
190
190
  };
191
191
  }
192
192
 
193
+ /** Windows up to this length are scanned; longer ones are read from the tree of {@link KeptCalls}. */
194
+ const SCANNED_WINDOW = 32;
195
+
193
196
  /** The values a ta.highest / ta.lowest / ta.pivothigh call site keeps: the non-na values of its calls, one per bar. */
194
197
  class KeptCalls {
195
198
  readonly values: number[] = [];
196
199
  readonly bars: number[] = [];
200
+ /**
201
+ * Segment tree of the best position of each range of kept values (node 1 is the root, leaf `leaves + k` is value
202
+ * `k`, -1 for no value), built on the first long window: a call site whose length grows with the bars (the bars
203
+ * since a session start) would otherwise scan the whole history on every call.
204
+ */
205
+ private tree: Int32Array | null = null;
206
+ private leaves = 0;
207
+
208
+ constructor(private readonly isLowest: boolean) {}
197
209
 
198
210
  /**
199
211
  * Keeps a non-na value (+/-Infinity is skipped like na, #183); a later call on the same bar (a loop) replaces the
@@ -207,18 +219,63 @@ class KeptCalls {
207
219
  this.values.push(value);
208
220
  this.bars.push(barIndex);
209
221
  }
222
+ if (this.tree) this.update(this.values.length - 1);
210
223
  }
211
224
 
212
225
  /** Position of the best of the last `count` kept values (the newest one on ties), -1 when there is none. */
213
- best(count: number, isLowest: boolean): number {
226
+ best(count: number): number {
214
227
  const last = this.values.length - 1;
215
228
  if (last < 0 || !(count >= 1)) return -1;
229
+ if (count > SCANNED_WINDOW) return this.bestOf(Math.max(0, Math.floor(last - count) + 1), last);
216
230
  let best = last;
217
231
  for (let k = last - 1; k >= 0 && k > last - count; k--) {
218
- if (isLowest ? this.values[k]! < this.values[best]! : this.values[k]! > this.values[best]!) best = k;
232
+ if (this.isLowest ? this.values[k]! < this.values[best]! : this.values[k]! > this.values[best]!) best = k;
233
+ }
234
+ return best;
235
+ }
236
+
237
+ /** The better of two positions (-1: none): the lower (higher) value, the newest one on equal values. */
238
+ private better(a: number, b: number): number {
239
+ if (a < 0) return b;
240
+ if (b < 0) return a;
241
+ const va = this.values[a]!;
242
+ const vb = this.values[b]!;
243
+ if (this.isLowest ? va < vb : va > vb) return a;
244
+ if (this.isLowest ? vb < va : vb > va) return b;
245
+ return a > b ? a : b;
246
+ }
247
+
248
+ /** Best position of the kept values `first` to `last`, from the tree. */
249
+ private bestOf(first: number, last: number): number {
250
+ if (!this.tree) this.build();
251
+ const tree = this.tree!;
252
+ let best = -1;
253
+ for (let l = first + this.leaves, r = last + this.leaves + 1; l < r; l >>= 1, r >>= 1) {
254
+ if (l & 1) best = this.better(best, tree[l++]!);
255
+ if (r & 1) best = this.better(best, tree[--r]!);
219
256
  }
220
257
  return best;
221
258
  }
259
+
260
+ /** (Re)builds the tree, with room for as many values again. */
261
+ private build(): void {
262
+ const n = this.values.length;
263
+ let leaves = 1;
264
+ while (leaves < 2 * n) leaves *= 2;
265
+ const tree = new Int32Array(2 * leaves).fill(-1);
266
+ for (let k = 0; k < n; k++) tree[leaves + k] = k;
267
+ for (let i = leaves - 1; i >= 1; i--) tree[i] = this.better(tree[2 * i]!, tree[2 * i + 1]!);
268
+ this.tree = tree;
269
+ this.leaves = leaves;
270
+ }
271
+
272
+ /** Value `k` was added or replaced. */
273
+ private update(k: number): void {
274
+ if (k >= this.leaves) return this.build();
275
+ const tree = this.tree!;
276
+ tree[this.leaves + k] = k;
277
+ for (let i = (this.leaves + k) >> 1; i >= 1; i >>= 1) tree[i] = this.better(tree[2 * i]!, tree[2 * i + 1]!);
278
+ }
222
279
  }
223
280
 
224
281
  /** One `ta.lowest` / `ta.highest` / `ta.lowestbars` / `ta.highestbars` call site; rules in {@link lowestByBar}. */
@@ -226,14 +283,14 @@ function extremeByBarSite(
226
283
  isLowest: boolean,
227
284
  offsets: boolean
228
285
  ): (barIndex: number, value: number, length: number) => number {
229
- const kept = new KeptCalls();
286
+ const kept = new KeptCalls(isLowest);
230
287
  const name = (isLowest ? 'lowest' : 'highest') + (offsets ? 'bars' : '');
231
288
  return (barIndex, value, length) => {
232
289
  checkWindowLength(name, length, barIndex);
233
290
  kept.add(barIndex, value);
234
291
  const len = Math.trunc(length);
235
292
  if (barIndex < len - 1) return NaN;
236
- const best = kept.best(len, isLowest);
293
+ const best = kept.best(len);
237
294
  if (best < 0) return NaN;
238
295
  return offsets ? -(barIndex - kept.bars[best]!) : kept.values[best]!;
239
296
  };
@@ -333,13 +390,13 @@ export function highestbars(): (barIndex: number, value: number, length: number)
333
390
 
334
391
  /** One `ta.pivothigh` / `ta.pivotlow` call site; rules in {@link pivothigh}. */
335
392
  function pivotSite(isLowest: boolean): (barIndex: number, value: number, leftbars: number, rightbars: number) => number {
336
- const kept = new KeptCalls();
393
+ const kept = new KeptCalls(isLowest);
337
394
  return (barIndex, value, leftbars, rightbars) => {
338
395
  kept.add(barIndex, value);
339
396
  const left = Math.trunc(leftbars);
340
397
  const right = Math.trunc(rightbars);
341
398
  if (!(barIndex >= left + right)) return NaN;
342
- const best = kept.best(left + right + 1, isLowest);
399
+ const best = kept.best(left + right + 1);
343
400
  return best >= 0 && kept.bars[best] === barIndex - right ? kept.values[best]! : NaN;
344
401
  };
345
402
  }
@@ -418,11 +475,12 @@ function loopSumSite(
418
475
  ): (barIndex: number, value: number, length: number) => [number, number] {
419
476
  const running = new RunningSum();
420
477
  const runningSq = new RunningSum();
478
+ const fn = name === 'sum' ? 'math.sum' : `ta.${name}`;
421
479
  let lastBar = NaN;
422
480
  let pending = false;
423
481
  return (barIndex, value, length) => {
424
482
  const len = Math.floor(length);
425
- checkSumLength(name === 'sum' ? 'math.sum' : `ta.${name}`, len, barIndex);
483
+ checkSumLength(fn, len, barIndex);
426
484
  if (!(len >= 1)) throw new Error(`callsite.${name}: length must be at least 1 (got ${length})`);
427
485
  if (barIndex !== lastBar) {
428
486
  if (pending) {
@@ -85,16 +85,73 @@ let limits: Required<DrawingLimits> = {
85
85
  box: DEFAULT_MAX_COUNT,
86
86
  polyline: DEFAULT_MAX_COUNT,
87
87
  };
88
- const deleted = new WeakSet<object>();
89
- /** Objects held by a `var` variable, with the number of variables that hold them. */
90
- let held = new WeakMap<object, number>();
91
- /** Bar on which the last `var` variable released an object (linefill rule). */
92
- let releasedAt = new WeakMap<object, number>();
88
+ /**
89
+ * Base of the classes that add a private field to an existing object (their constructor returns the object they are
90
+ * given). Such a field replaces a WeakMap entry: a study that creates hundreds of thousands of objects spends most of
91
+ * its drawing time adding WeakMap keys. The field is invisible (not a key, not copied by a spread) and stays for the
92
+ * life of the object, as the entry did.
93
+ */
94
+ export class Stamped {
95
+ constructor(obj: object) {
96
+ return obj;
97
+ }
98
+ }
99
+
100
+ /** The deleted objects. */
101
+ class Deleted extends Stamped {
102
+ #deleted = true;
103
+ static mark(obj: object): void {
104
+ if (!Deleted.has(obj)) new Deleted(obj);
105
+ }
106
+ static has(obj: object): boolean {
107
+ return #deleted in obj;
108
+ }
109
+ }
110
+
111
+ /** The `var` records of a run: a reset starts new ones, a nested run saves and puts back those of its run. */
112
+ interface Holds {
113
+ /** The records of the objects whose private record belongs to another run */
114
+ readonly others: WeakMap<object, HoldRecord>;
115
+ }
116
+
117
+ /** What the `var` variables of a run did with an object. */
118
+ interface HoldRecord {
119
+ readonly run: Holds;
120
+ /** Number of `var` variables that hold the object (0: not held) */
121
+ count: number;
122
+ /** Bar on which a `var` variable got the object: on that bar the maximum count deletes it only when no other object
123
+ * can go; from the next bar on, never. Undefined outside a bar loop */
124
+ heldAt: number | undefined;
125
+ /** Bar on which the last `var` variable released the object (linefill rule) */
126
+ releasedAt: number | undefined;
127
+ }
128
+ let holds: Holds = { others: new WeakMap() };
129
+
130
+ /**
131
+ * The record of the first run that holds an object, on the object itself (a study holding a new object on every bar
132
+ * would otherwise add a WeakMap key per bar); the records of other runs go to their {@link Holds.others}.
133
+ */
134
+ class Held extends Stamped {
135
+ #record: HoldRecord;
136
+ private constructor(obj: object, record: HoldRecord) {
137
+ super(obj);
138
+ this.#record = record;
139
+ }
140
+ /** The record of `obj` in the current run, if any. */
141
+ static get(obj: object): HoldRecord | undefined {
142
+ const own = #record in obj ? (obj as Held).#record : undefined;
143
+ return own?.run === holds ? own : holds.others.get(obj);
144
+ }
145
+ /** A new record of `obj` in the current run (it has none). */
146
+ static create(obj: object): HoldRecord {
147
+ const record: HoldRecord = { run: holds, count: 0, heldAt: undefined, releasedAt: undefined };
148
+ if (#record in obj) holds.others.set(obj, record);
149
+ else new Held(obj, record);
150
+ return record;
151
+ }
152
+ }
93
153
  /** Bars during which a released linefill is still skipped by the maximum count. */
94
154
  const LINEFILL_RELEASE_BARS = 5000;
95
- /** Bar on which a `var` variable got an object: on that bar the maximum count deletes it only when no other object can
96
- * go; from the next bar on, never. */
97
- let heldAt = new WeakMap<object, number>();
98
155
  /** Kinds with a maximum count of their own. */
99
156
  type CountedKind = 'line' | 'label' | 'box' | 'polyline';
100
157
  const COUNTED_KINDS: readonly CountedKind[] = ['line', 'label', 'box', 'polyline'];
@@ -109,26 +166,26 @@ const PENDING_RESET: Record<CountedKind, number> = { line: 5, label: 5, box: 5,
109
166
  * variable): the maximum count never deletes it, and it still counts. Returns the object.
110
167
  */
111
168
  export function holdDrawing<T extends object>(obj: T): T {
112
- if (!held.has(obj)) {
113
- if (currentBar === null) heldAt.delete(obj);
114
- else heldAt.set(obj, currentBar);
115
- }
116
- held.set(obj, (held.get(obj) ?? 0) + 1);
169
+ const record = Held.get(obj) ?? Held.create(obj);
170
+ if (record.count === 0) record.heldAt = currentBar ?? undefined;
171
+ record.count++;
117
172
  return obj;
118
173
  }
119
174
 
120
175
  /** The `var` variable no longer refers to the object (it got another object or `na`). */
121
176
  export function releaseDrawing(obj: object | null | undefined): void {
122
177
  if (!obj) return;
123
- const count = held.get(obj) ?? 0;
124
- if (count > 1) held.set(obj, count - 1);
125
- else if (held.delete(obj) && currentBar !== null) releasedAt.set(obj, currentBar);
178
+ const record = Held.get(obj);
179
+ if (!record || record.count === 0) return;
180
+ record.count--;
181
+ if (record.count === 0 && currentBar !== null) record.releasedAt = currentBar;
126
182
  }
127
183
 
128
184
  /** Held by a `var` variable since a bar before the current one (or outside a bar loop). */
129
185
  function heldBefore(obj: object): boolean {
130
- if (!held.has(obj)) return false;
131
- const bar = heldAt.get(obj);
186
+ const record = Held.get(obj);
187
+ if (!record || record.count === 0) return false;
188
+ const bar = record.heldAt;
132
189
  return bar === undefined || currentBar === null || bar < currentBar;
133
190
  }
134
191
 
@@ -139,13 +196,17 @@ function heldBefore(obj: object): boolean {
139
196
  */
140
197
  function heldOnThisBar(obj: object): boolean {
141
198
  if (currentBar === null) return false;
142
- return held.has(obj) ? heldAt.get(obj) === currentBar : releasedAt.get(obj) === currentBar;
199
+ const record = Held.get(obj);
200
+ if (!record) return false;
201
+ return record.count > 0 ? record.heldAt === currentBar : record.releasedAt === currentBar;
143
202
  }
144
203
 
145
204
  /** Linefill rule: held, or released less than 5,000 bars ago. */
146
205
  function fillProtected(obj: object): boolean {
147
- if (held.has(obj)) return true;
148
- const bar = releasedAt.get(obj);
206
+ const record = Held.get(obj);
207
+ if (!record) return false;
208
+ if (record.count > 0) return true;
209
+ const bar = record.releasedAt;
149
210
  return bar !== undefined && currentBar !== null && currentBar - bar < LINEFILL_RELEASE_BARS;
150
211
  }
151
212
 
@@ -271,11 +332,38 @@ const COORDINATES: { [K in DrawingKind]: Array<keyof DrawingTypes[K]> } = {
271
332
  table: [],
272
333
  };
273
334
 
335
+ /** The live linefills of each line, in creation order: deleting a line or making a fill does not scan all the fills. */
336
+ let fillsOfLine = new Map<Line, Linefill[]>();
337
+
338
+ function trackFill(fill: Linefill): void {
339
+ for (const l of fill.line1 === fill.line2 ? [fill.line1] : [fill.line1, fill.line2]) {
340
+ const fills = fillsOfLine.get(l);
341
+ if (fills) fills.push(fill);
342
+ else fillsOfLine.set(l, [fill]);
343
+ }
344
+ }
345
+
346
+ function untrackFill(fill: Linefill): void {
347
+ for (const l of fill.line1 === fill.line2 ? [fill.line1] : [fill.line1, fill.line2]) {
348
+ const fills = fillsOfLine.get(l);
349
+ if (!fills) continue;
350
+ const k = fills.indexOf(fill);
351
+ if (k !== -1) fills.splice(k, 1);
352
+ if (fills.length === 0) fillsOfLine.delete(l);
353
+ }
354
+ }
355
+
356
+ /** The live linefills that use `line`, in creation order (do not modify). */
357
+ export function liveFillsOf(line: Line): readonly Linefill[] {
358
+ return fillsOfLine.get(line) ?? [];
359
+ }
360
+
274
361
  function markDeleted<K extends DrawingKind>(kind: K, obj: DrawingTypes[K], explicit: boolean): void {
275
- deleted.add(obj);
362
+ Deleted.mark(obj);
276
363
  for (const field of COORDINATES[kind]) (obj as unknown as Record<string, unknown>)[field as string] = NaN;
277
364
  if (kind === 'line' && explicit) {
278
- for (const fill of live.linefill.filter((f) => f.line1 === obj || f.line2 === obj)) remove('linefill', fill);
365
+ const fills = fillsOfLine.get(obj as Line);
366
+ if (fills) for (const fill of [...fills]) remove('linefill', fill);
279
367
  }
280
368
  }
281
369
 
@@ -298,26 +386,36 @@ function cutOldest<K extends DrawingKind>(
298
386
  if (kind === 'table') return []; // tables have no maximum count
299
387
  const max = limits[kind === 'linefill' ? 'line' : (kind as keyof DrawingLimits)] + allowance(kind);
300
388
  if (list.length <= max + SLACK) return [];
301
- const gone = new Set<object>();
302
389
  let excess = list.length - max;
303
390
  const candidate = (old: DrawingTypes[K]): boolean =>
304
391
  old !== obj && (!only || only(old)) && !(kind === 'linefill' ? fillProtected(old) : heldBefore(old));
305
- // the oldest first; the objects a `var` variable got (or released) on this bar only when the others are not enough
392
+ // positions of the objects to delete. The oldest first; the objects a `var` variable got (or released) on this bar
393
+ // only when the others are not enough (the two passes pick different objects)
394
+ const gone: number[] = [];
306
395
  for (const weak of kind === 'linefill' ? [false] : [false, true]) {
307
- for (const old of list) {
308
- if (excess <= 0) break;
309
- if (!gone.has(old) && candidate(old) && (kind === 'linefill' || heldOnThisBar(old) === weak)) {
396
+ const before = gone.length;
397
+ for (let k = 0; k < list.length && excess > 0; k++) {
398
+ const old = list[k]!;
399
+ if (candidate(old) && (kind === 'linefill' || heldOnThisBar(old) === weak)) {
310
400
  excess--;
311
- gone.add(old);
401
+ gone.push(k);
312
402
  }
313
403
  }
404
+ if (before > 0 && gone.length > before) gone.sort((a, b) => a - b);
405
+ }
406
+ const cut = gone.map((k) => list[k]!);
407
+ // the others keep their order; usually the cut is the oldest run of objects, removed at once
408
+ if (gone.length > 0 && gone[gone.length - 1]! - gone[0]! === gone.length - 1) list.splice(gone[0]!, gone.length);
409
+ else if (gone.length > 0) {
410
+ let to = gone[0]!;
411
+ for (let from = to, g = 0; from < list.length; from++) {
412
+ if (from === gone[g]) g++;
413
+ else list[to++] = list[from]!;
414
+ }
415
+ list.length = to;
314
416
  }
315
- const kept = list.filter((old) => !gone.has(old));
316
- const cut = list.filter((old) => gone.has(old));
317
417
  // linefills: still above the maximum + 5, the oldest go, the held ones too
318
- if (kind === 'linefill' && kept.length > max + SLACK) cut.push(...kept.splice(0, kept.length - max));
319
- list.length = 0;
320
- list.push(...kept);
418
+ if (kind === 'linefill' && list.length > max + SLACK) cut.push(...list.splice(0, list.length - max));
321
419
  return cut;
322
420
  }
323
421
 
@@ -336,9 +434,13 @@ export function register<K extends DrawingKind>(kind: K, obj: DrawingTypes[K]):
336
434
  if (lastBar && isCounted(kind)) return registerLast(lastBar, kind, obj);
337
435
  if (isCounted(kind) && pending[kind] >= PENDING_RESET[kind]) pending[kind] = 0;
338
436
  list.push(obj);
437
+ if (kind === 'linefill') trackFill(obj as Linefill);
339
438
  const cut = cutOldest(kind, list, obj);
340
439
  if (kind === 'polyline') pending.polyline += cut.length;
341
- for (const old of cut) markDeleted(kind, old, false);
440
+ for (const old of cut) {
441
+ if (kind === 'linefill') untrackFill(old as Linefill);
442
+ markDeleted(kind, old, false);
443
+ }
342
444
  return obj;
343
445
  }
344
446
 
@@ -373,18 +475,20 @@ function registerLast<K extends DrawingKind>(bar: LastBar, kind: K, obj: Drawing
373
475
  /** Deletes an object (no effect when it is already deleted). */
374
476
  export function remove<K extends DrawingKind>(kind: K, obj: DrawingTypes[K]): void {
375
477
  const list = live[kind];
376
- const index = list.indexOf(obj);
478
+ // from the end: an object is in the list once, and scripts mostly delete their newest objects
479
+ const index = list.lastIndexOf(obj);
377
480
  if (index !== -1) {
378
481
  list.splice(index, 1);
482
+ if (kind === 'linefill') untrackFill(obj as Linefill);
379
483
  if (isCounted(kind)) pending[kind]++;
380
484
  if (kind === 'polyline' && lastBar?.old.has(obj)) lastBar.oldPolylinesGone++;
381
485
  }
382
- if (!deleted.has(obj)) markDeleted(kind, obj, true);
486
+ if (!Deleted.has(obj)) markDeleted(kind, obj, true);
383
487
  }
384
488
 
385
489
  /** True when the object was deleted (by `delete` or by the maximum count). */
386
490
  export function isDeleted(obj: unknown): boolean {
387
- return typeof obj === 'object' && obj !== null && deleted.has(obj);
491
+ return typeof obj === 'object' && obj !== null && Deleted.has(obj);
388
492
  }
389
493
 
390
494
  /** The live objects of a kind, in creation order (a new array). */
@@ -395,10 +499,9 @@ export function all<K extends DrawingKind>(kind: K): Array<DrawingTypes[K]> {
395
499
  /** Forgets all objects (without deleting them) and sets the maximum counts (default 50). */
396
500
  export function resetDrawings(newLimits: DrawingLimits = {}): void {
397
501
  for (const kind of Object.keys(live) as DrawingKind[]) live[kind].length = 0;
502
+ fillsOfLine = new Map();
398
503
  created.clear();
399
- held = new WeakMap();
400
- releasedAt = new WeakMap();
401
- heldAt = new WeakMap();
504
+ holds = { others: new WeakMap() };
402
505
  pending = { line: 0, label: 0, box: 0, polyline: 0 };
403
506
  currentBar = null;
404
507
  lastBarIndex = null;
@@ -420,9 +523,7 @@ export function setDrawingLimits(newLimits: DrawingLimits): void {
420
523
  export interface DrawingState {
421
524
  live: { [K in DrawingKind]: Array<DrawingTypes[K]> };
422
525
  created: DrawingKind[];
423
- held: WeakMap<object, number>;
424
- releasedAt: WeakMap<object, number>;
425
- heldAt: WeakMap<object, number>;
526
+ holds: Holds;
426
527
  pending: Record<CountedKind, number>;
427
528
  currentBar: number | null;
428
529
  lastBarIndex: number | null;
@@ -442,9 +543,7 @@ export function saveDrawingState(): DrawingState {
442
543
  table: [...live.table],
443
544
  },
444
545
  created: [...created],
445
- held,
446
- releasedAt,
447
- heldAt,
546
+ holds,
448
547
  pending: { ...pending },
449
548
  currentBar,
450
549
  lastBarIndex,
@@ -460,11 +559,11 @@ export function restoreDrawingState(s: DrawingState): void {
460
559
  list.length = 0;
461
560
  list.push(...(s.live[kind] as object[]));
462
561
  }
562
+ fillsOfLine = new Map();
563
+ for (const fill of live.linefill) trackFill(fill);
463
564
  created.clear();
464
565
  for (const kind of s.created) created.add(kind);
465
- held = s.held;
466
- releasedAt = s.releasedAt;
467
- heldAt = s.heldAt;
566
+ holds = s.holds;
468
567
  pending = { ...s.pending };
469
568
  currentBar = s.currentBar;
470
569
  lastBarIndex = s.lastBarIndex;
package/src/index.ts CHANGED
@@ -225,7 +225,7 @@ export type { LightweightSeriesDefinitions } from './runtime/adapters/Lightweigh
225
225
  export { SimpleInputAdapter } from './runtime/adapters/SimpleInputAdapter.js';
226
226
 
227
227
  // Version
228
- export const VERSION = '0.15.1';
228
+ export const VERSION = '0.15.2';
229
229
 
230
230
  /**
231
231
  * Library information
@@ -10,7 +10,7 @@
10
10
  * @version 6
11
11
  */
12
12
 
13
- import { all as allDrawings, isDeleted, register, remove } from '../drawing/registry.js';
13
+ import { Stamped, all as allDrawings, isDeleted, liveFillsOf, register, remove } from '../drawing/registry.js';
14
14
  import type { Linefill, Line, color } from '../types/index.js';
15
15
 
16
16
  /**
@@ -46,13 +46,13 @@ export function new_linefill(line1: Line, line2: Line, fillColor?: color): Linef
46
46
  // PineScript: an na line gives an na linefill
47
47
  if (line1 === null || line1 === undefined || line2 === null || line2 === undefined) return null as unknown as Linefill;
48
48
  let found: Linefill | undefined;
49
- for (const fill of allDrawings('linefill')) {
49
+ for (const fill of liveFillsOf(line1)) {
50
50
  const has = (l: Line): boolean => fill.line1 === l || fill.line2 === l;
51
- if (has(line1) && has(line2) && (!found || (touched.get(fill) ?? 0) > (touched.get(found) ?? 0))) found = fill;
51
+ if (has(line2) && (!found || Touched.get(fill) > Touched.get(found))) found = fill;
52
52
  }
53
53
  if (found) {
54
54
  found.color = fillColor;
55
- touched.set(found, ++touchCount);
55
+ Touched.set(found, ++touchCount);
56
56
  return found;
57
57
  }
58
58
  const fill = register('linefill', {
@@ -60,12 +60,21 @@ export function new_linefill(line1: Line, line2: Line, fillColor?: color): Linef
60
60
  line2,
61
61
  color: fillColor
62
62
  });
63
- touched.set(fill, ++touchCount);
63
+ Touched.set(fill, ++touchCount);
64
64
  return fill;
65
65
  }
66
66
 
67
- /** Order in which the linefills were created or returned by `linefill.new` (the last one wins a lookup). */
68
- const touched = new WeakMap<Linefill, number>();
67
+ /** Order in which the linefills were created or returned by `linefill.new` (the last one wins a lookup); 0 before. */
68
+ class Touched extends Stamped {
69
+ #touch = 0;
70
+ static get(fill: Linefill): number {
71
+ return #touch in fill ? fill.#touch : 0;
72
+ }
73
+ static set(fill: Linefill, order: number): void {
74
+ if (!(#touch in fill)) new Touched(fill);
75
+ (fill as unknown as Touched).#touch = order;
76
+ }
77
+ }
69
78
  let touchCount = 0;
70
79
 
71
80
  /**
@@ -35,10 +35,26 @@ const view = new DataView(new ArrayBuffer(8));
35
35
  const int32 = (v: bigint): bigint => BigInt.asIntN(32, v);
36
36
  const int64 = (v: bigint): bigint => BigInt.asIntN(64, v);
37
37
 
38
+ /** 5^k, made once (k up to 1074, the binary exponents of the doubles). */
39
+ const powersOf5: bigint[] = [1n];
40
+ export function pow5(k: number): bigint {
41
+ while (powersOf5.length <= k) powersOf5.push(powersOf5[powersOf5.length - 1]! * 5n);
42
+ return powersOf5[k]!;
43
+ }
44
+
45
+ /** `s` without its trailing '0' characters. */
46
+ export function trimZeros(s: string): string {
47
+ let end = s.length;
48
+ while (end > 0 && s.charCodeAt(end - 1) === 48) end--;
49
+ return s.slice(0, end);
50
+ }
51
+
52
+ /** Trailing zero bits of a significand (not 0, below 2^53: exact as a double). */
38
53
  function trailingZeros(v: bigint): number {
54
+ let x = Number(v);
39
55
  let n = 0;
40
- while ((v & 1n) === 0n) {
41
- v >>= 1n;
56
+ while (x % 2 === 0) {
57
+ x /= 2;
42
58
  n++;
43
59
  }
44
60
  return n;
@@ -96,7 +112,7 @@ export function convertDouble(x: number): ConvertedDigits {
96
112
  if (residue >= pow10 >> 1n) lvalue++;
97
113
  }
98
114
  const s = lvalue.toString();
99
- return { digits: s.replace(/0+$/, ''), decExponent: insignificant + s.length, roundedUp: false, exact: false };
115
+ return { digits: trimZeros(s), decExponent: insignificant + s.length, roundedUp: false, exact: false };
100
116
  }
101
117
 
102
118
  let decExp = estimateDecExp(fractBits, binExp);
@@ -134,9 +150,9 @@ export function convertDouble(x: number): ConvertedDigits {
134
150
  if (Bbits < 64 && tenSbits < 64) {
135
151
  // int or long arithmetic, with its overflows
136
152
  const wrap = Bbits < 32 && tenSbits < 32 ? int32 : int64;
137
- let b = wrap((fractBits * 5n ** BigInt(B5)) << BigInt(B2));
138
- const s = wrap(5n ** BigInt(S5) << BigInt(S2));
139
- let m = wrap(5n ** BigInt(M5) << BigInt(M2));
153
+ let b = wrap((fractBits * pow5(B5)) << BigInt(B2));
154
+ const s = wrap(pow5(S5) << BigInt(S2));
155
+ let m = wrap(pow5(M5) << BigInt(M2));
140
156
  const tens = wrap(s * 10n);
141
157
  let q = Number(b / s);
142
158
  b = wrap(10n * (b % s));
@@ -162,9 +178,9 @@ export function convertDouble(x: number): ConvertedDigits {
162
178
  lowDigitDifference = wrap((b << 1n) - tens);
163
179
  exact = b === 0n;
164
180
  } else {
165
- let b = (fractBits * 5n ** BigInt(B5)) << BigInt(B2);
166
- const s = 5n ** BigInt(S5) << BigInt(S2);
167
- let m = 5n ** BigInt(M5 + 1) << BigInt(M2 + 1);
181
+ let b = (fractBits * pow5(B5)) << BigInt(B2);
182
+ const s = pow5(S5) << BigInt(S2);
183
+ let m = pow5(M5 + 1) << BigInt(M2 + 1);
168
184
  const tens = s * 10n;
169
185
  let q = Number(b / s);
170
186
  b = (b % s) * 10n;
@@ -204,7 +220,7 @@ export function convertDouble(x: number): ConvertedDigits {
204
220
  if (digits[digits.length - 1]! % 2 !== 0) roundup();
205
221
  } else if (lowDigitDifference > 0n) roundup();
206
222
  }
207
- const text = digits.join('').replace(/0+$/, '');
223
+ const text = trimZeros(digits.join(''));
208
224
  return { digits: text || '0', decExponent, roundedUp, exact };
209
225
  }
210
226
 
@@ -263,6 +279,6 @@ export function javaFixedDigits(x: number, maxFrac: number): { digits: string; i
263
279
  count = keep;
264
280
  while (count > 1 && digits[count - 1] === 0) count--;
265
281
  }
266
- const text = digits.slice(0, count).join('').replace(/0+$/, '');
282
+ const text = trimZeros(digits.slice(0, count).join(''));
267
283
  return { digits: text, intLen: text ? decimalAt : 0 };
268
284
  }
@@ -72,24 +72,39 @@ function formatArgument(
72
72
  }
73
73
  }
74
74
 
75
- /** Formats `pattern` with `args` like PineScript `str.format`; dates use `timezone` (read only when a date is formatted). */
76
- export function formatMessage(pattern: string, args: unknown[], timezone: string | (() => string)): string {
77
- let out = '';
75
+ /** A `{index[,type[,style]]}` element of a pattern; `inner` is the text between the braces. */
76
+ interface Placeholder {
77
+ inner: string;
78
+ index: number;
79
+ type: string | undefined;
80
+ style: string | undefined;
81
+ }
82
+
83
+ /** Parsed patterns (literal text and placeholders): a script formats the same pattern on every bar. */
84
+ const templates = new Map<string, Array<string | Placeholder>>();
85
+ /** Cached patterns before the cache restarts. */
86
+ const MAX_TEMPLATES = 1000;
87
+
88
+ function parseTemplate(pattern: string): Array<string | Placeholder> {
89
+ const cached = templates.get(pattern);
90
+ if (cached) return cached;
91
+ const parts: Array<string | Placeholder> = [];
92
+ let text = '';
78
93
  for (let i = 0; i < pattern.length; ) {
79
94
  const ch = pattern[i]!;
80
95
  if (ch === "'") {
81
96
  if (pattern[i + 1] === "'") {
82
- out += "'";
97
+ text += "'";
83
98
  i += 2;
84
99
  continue;
85
100
  }
86
101
  const end = pattern.indexOf("'", i + 1);
87
- out += pattern.slice(i + 1, end === -1 ? undefined : end);
102
+ text += pattern.slice(i + 1, end === -1 ? undefined : end);
88
103
  i = end === -1 ? pattern.length : end + 1;
89
104
  continue;
90
105
  }
91
106
  if (ch !== '{') {
92
- out += ch;
107
+ text += ch;
93
108
  i++;
94
109
  continue;
95
110
  }
@@ -105,10 +120,26 @@ export function formatMessage(pattern: string, args: unknown[], timezone: string
105
120
  }
106
121
  const inner = pattern.slice(i + 1, j - 1);
107
122
  const [index = '', type, ...rest] = inner.split(',');
108
- const style = rest.length ? rest.join(',') : undefined;
109
- const n = Number(index.trim());
110
- out += n < args.length ? formatArgument(args[n], type, style, timezone) : `{${inner}}`;
123
+ if (text) parts.push(text);
124
+ text = '';
125
+ parts.push({ inner, index: Number(index.trim()), type, style: rest.length ? rest.join(',') : undefined });
111
126
  i = j;
112
127
  }
128
+ if (text) parts.push(text);
129
+ if (templates.size >= MAX_TEMPLATES) templates.clear();
130
+ templates.set(pattern, parts);
131
+ return parts;
132
+ }
133
+
134
+ /** Formats `pattern` with `args` like PineScript `str.format`; dates use `timezone` (read only when a date is formatted). */
135
+ export function formatMessage(pattern: string, args: unknown[], timezone: string | (() => string)): string {
136
+ let out = '';
137
+ for (const part of parseTemplate(pattern)) {
138
+ if (typeof part === 'string') out += part;
139
+ else {
140
+ const n = part.index;
141
+ out += n < args.length ? formatArgument(args[n], part.type, part.style, timezone) : `{${part.inner}}`;
142
+ }
143
+ }
113
144
  return out;
114
145
  }