@icgio/icg-utils 1.9.54 → 1.9.56

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.
package/index.js CHANGED
@@ -10,5 +10,7 @@ module.exports = {
10
10
  observable: require('./lib/observable.js'),
11
11
  ohlcv: require('./lib/ohlcv'),
12
12
  rate_limiter: require('./lib/rate-limiter.js'),
13
+ ordered_dict: require('./lib/ordered-dict.js').ordered_dict,
14
+ sorted_book: require('./lib/sorted-book.js'),
13
15
  utils: require('./lib/utils.js'),
14
16
  }
@@ -0,0 +1,111 @@
1
+ // Sorted order book using a binary-searched array.
2
+ //
3
+ // O(log n) lookup, O(n) insert/delete (array splice). Efficient for small books
4
+ // (n < 5,000) where V8's optimized memcpy outperforms pointer-based structures.
5
+ // For larger books (n > 10,000), use sorted_book (RBTree) instead.
6
+ //
7
+ // Usage:
8
+ // const ordered_dict = require('@icgio/icg-utils').utils.ordered_dict
9
+ // const bids = ordered_dict(false) // descending (highest first)
10
+ // const asks = ordered_dict(true) // ascending (lowest first)
11
+
12
+ function binary_find(search_element, is_ask, keys) {
13
+ let min_index = 0
14
+ let max_index = keys.length - 1
15
+ let current_index = 0
16
+ let current_element
17
+ while (min_index <= max_index) {
18
+ current_index = ((min_index + max_index) / 2) | 0
19
+ current_element = keys[current_index]
20
+ if ((current_element < search_element && is_ask) || (current_element > search_element && !is_ask)) {
21
+ min_index = current_index + 1
22
+ } else if ((current_element > search_element && is_ask) || (current_element < search_element && !is_ask)) {
23
+ max_index = current_index - 1
24
+ } else {
25
+ return { found: true, index: current_index }
26
+ }
27
+ }
28
+ // Not found — return the insertion point
29
+ if (keys.length === 0) return { found: false, index: 0 }
30
+ return {
31
+ found: false,
32
+ index: (current_element < search_element && is_ask) || (current_element > search_element && !is_ask) ? current_index + 1 : current_index,
33
+ }
34
+ }
35
+
36
+ function ordered_dict(is_ask) {
37
+ let keys = [],
38
+ vals = {}
39
+ return {
40
+ init: function (kvs) {
41
+ for (let [k, v] of kvs) {
42
+ this.insert(k, v)
43
+ }
44
+ },
45
+ push: function (k, v) {
46
+ // Append without sort — only safe if caller guarantees order.
47
+ // Prefer insert() for correctness.
48
+ k = parseFloat(k)
49
+ if (!vals[k]) {
50
+ keys.push(k)
51
+ }
52
+ vals[k] = v
53
+ },
54
+ insert: function (k, v) {
55
+ if (v != 0) {
56
+ k = parseFloat(k)
57
+ let search = binary_find(k, is_ask, keys)
58
+ let pos = search.index
59
+ if (!vals[k]) {
60
+ keys.splice(pos, 0, k)
61
+ vals[k] = v
62
+ } else {
63
+ vals[k] = v
64
+ }
65
+ }
66
+ },
67
+ del: function (k) {
68
+ k = parseFloat(k)
69
+ let search = binary_find(k, is_ask, keys)
70
+ if (search.found) {
71
+ keys.splice(search.index, 1)
72
+ delete vals[k]
73
+ }
74
+ },
75
+ // Remove all entries before k in sort order (exclusive — k itself is kept if present)
76
+ del_before: function (k) {
77
+ k = parseFloat(k)
78
+ let search = binary_find(k, is_ask, keys)
79
+ let cut = search.found ? search.index : search.index
80
+ if (cut <= 0) return
81
+ let removed = keys.splice(0, cut)
82
+ for (let r of removed) delete vals[r]
83
+ },
84
+ // Remove all entries after k in sort order (exclusive — k itself is kept if present)
85
+ del_after: function (k) {
86
+ k = parseFloat(k)
87
+ let search = binary_find(k, is_ask, keys)
88
+ let keep = search.found ? search.index + 1 : search.index
89
+ if (keep >= keys.length) return
90
+ let removed = keys.splice(keep)
91
+ for (let r of removed) delete vals[r]
92
+ },
93
+ val: function (k) {
94
+ return vals[k]
95
+ },
96
+ length: function () {
97
+ return keys.length
98
+ },
99
+ keys: function () {
100
+ return keys
101
+ },
102
+ values: function () {
103
+ return vals
104
+ },
105
+ entries: function () {
106
+ return keys.map((key) => [key, vals[key]])
107
+ },
108
+ }
109
+ }
110
+
111
+ module.exports = { ordered_dict, binary_find }
@@ -0,0 +1,78 @@
1
+ // Sorted order book using a Red-Black tree (bintrees).
2
+ //
3
+ // Drop-in replacement for ordered_dict with O(log n) insert/delete instead of O(n)
4
+ // array splice. At n=20,000 price levels (full unwindowed L3 book), insert/delete
5
+ // is ~350× faster than ordered_dict.
6
+ //
7
+ // API is compatible with ordered_dict: insert(k,v), del(k), val(k), keys(), entries(),
8
+ // length(), init(kvs). Plus top() for O(log n) best-price access.
9
+ //
10
+ // Usage:
11
+ // const sorted_book = require('@icgio/icg-utils').sorted_book
12
+ // const bids = sorted_book(false) // descending (highest = best bid = first)
13
+ // const asks = sorted_book(true) // ascending (lowest = best ask = first)
14
+ // bids.insert(71200, 0.5)
15
+ // bids.top() // → 71200 (O(log n))
16
+ // bids.val(71200) // → 0.5 (O(1))
17
+ // bids.keys() // → [71200, ...] (O(n), sorted)
18
+
19
+ const { RBTree } = require('bintrees')
20
+
21
+ function sorted_book(is_ask) {
22
+ // Comparator determines iteration/top() order:
23
+ // asks (is_ask=true): ascending → top() = best ask (lowest price)
24
+ // bids (is_ask=false): descending → top() = best bid (highest price)
25
+ const cmp = is_ask ? (a, b) => a - b : (a, b) => b - a
26
+ const tree = new RBTree(cmp)
27
+ const vals = new Map()
28
+
29
+ return {
30
+ insert(k, v) {
31
+ if (v == 0) return
32
+ k = parseFloat(k)
33
+ if (!vals.has(k)) tree.insert(k)
34
+ vals.set(k, v)
35
+ },
36
+
37
+ del(k) {
38
+ k = parseFloat(k)
39
+ if (vals.has(k)) {
40
+ tree.remove(k)
41
+ vals.delete(k)
42
+ }
43
+ },
44
+
45
+ val(k) {
46
+ return vals.get(parseFloat(k))
47
+ },
48
+
49
+ // O(log n) — best price (top of book)
50
+ top() {
51
+ return tree.min()
52
+ },
53
+
54
+ // O(n) — full sorted key list. Use top() when you only need the best price.
55
+ keys() {
56
+ const result = []
57
+ tree.each((k) => result.push(k))
58
+ return result
59
+ },
60
+
61
+ // O(n) — full sorted [key, value] pairs
62
+ entries() {
63
+ const result = []
64
+ tree.each((k) => result.push([k, vals.get(k)]))
65
+ return result
66
+ },
67
+
68
+ length() {
69
+ return vals.size
70
+ },
71
+
72
+ init(kvs) {
73
+ for (const [k, v] of kvs) this.insert(k, v)
74
+ },
75
+ }
76
+ }
77
+
78
+ module.exports = sorted_book
package/lib/utils.js CHANGED
@@ -93,154 +93,7 @@ String.prototype.replaceAt = function (index, replacement) {
93
93
  return this.substr(0, index) + replacement + this.substr(index + replacement.length)
94
94
  }
95
95
 
96
- function binary_find(search_element, is_ask, keys) {
97
- let min_index = 0
98
- let max_index = keys.length - 1
99
- let current_index
100
- let current_element
101
- while (min_index <= max_index) {
102
- current_index = ((min_index + max_index) / 2) | 0
103
- current_element = keys[current_index]
104
- if ((current_element < search_element && is_ask) || (current_element > search_element && !is_ask)) {
105
- min_index = current_index + 1
106
- } else if ((current_element > search_element && is_ask) || (current_element < search_element && !is_ask)) {
107
- max_index = current_index - 1
108
- } else {
109
- return {
110
- found: true,
111
- index: current_index,
112
- }
113
- }
114
- }
115
- return {
116
- found: false,
117
- index: (current_element < search_element && is_ask) || (current_element > search_element && !is_ask) ? current_index + 1 : current_index,
118
- }
119
- }
120
-
121
- function ordered_dict(is_ask) {
122
- let keys = [],
123
- vals = {}
124
- return {
125
- init: function (kvs) {
126
- for (let [k, v] of kvs) {
127
- this.insert(k, v)
128
- }
129
- },
130
- push: function (k, v) {
131
- k = parseFloat(k)
132
- if (!vals[k]) {
133
- keys.push(k)
134
- }
135
- vals[k] = v
136
- },
137
- insert: function (k, v) {
138
- if (v != 0) {
139
- k = parseFloat(k)
140
- let search = binary_find(k, is_ask, keys)
141
- let pos = search.index
142
- if (!vals[k]) {
143
- keys.splice(pos, 0, k)
144
- vals[k] = v
145
- } else {
146
- vals[k] = v
147
- }
148
- }
149
- },
150
- del: function (k) {
151
- k = parseFloat(k)
152
- let search = binary_find(k, is_ask, keys)
153
- let pos = search.index
154
- if (search.found) {
155
- keys = keys.slice(0, pos).concat(keys.slice(pos + 1, keys.length))
156
- delete vals[k]
157
- }
158
- },
159
- del_before: function (k) {
160
- k = parseFloat(k)
161
- let search = binary_find(k, is_ask, keys)
162
- let pos = search.index
163
- if (search.found) {
164
- let keys_to_del = keys.slice(0, pos)
165
- keys = keys.slice(pos + 1, keys.length)
166
- for (let k_to_del of keys_to_del) {
167
- delete vals[k_to_del]
168
- }
169
- } else if (pos > 1) {
170
- let keys_to_del = keys.slice(0, pos - 1)
171
- keys = keys.slice(pos, keys.length)
172
- for (let k_to_del of keys_to_del) {
173
- delete vals[k_to_del]
174
- }
175
- }
176
- },
177
- del_after: function (k) {
178
- k = parseFloat(k)
179
- let search = binary_find(k, is_ask, keys)
180
- let pos = search.index
181
- if (search.found) {
182
- let keys_to_del = keys.slice(pos + 1, keys.length)
183
- keys = keys.slice(0, pos)
184
- for (let k_to_del of keys_to_del) {
185
- delete vals[k_to_del]
186
- }
187
- } else {
188
- let keys_to_del = keys.slice(pos + 1, keys.length)
189
- keys = keys.slice(0, pos)
190
- for (let k_to_del of keys_to_del) {
191
- delete vals[k_to_del]
192
- }
193
- }
194
- },
195
- val: function (k) {
196
- return vals[k]
197
- },
198
- length: function () {
199
- return keys.length
200
- },
201
- keys: function () {
202
- return keys
203
- },
204
- values: function () {
205
- return vals
206
- },
207
- entries: function () {
208
- return keys.map((key) => [key, vals[key]])
209
- },
210
- }
211
- }
212
-
213
- // let asks = [
214
- // [1, 1],
215
- // [2, 2],
216
- // [3, 3],
217
- // [4, 4],
218
- // [5, 3],
219
- // [6, 2],
220
- // [7, 1],
221
- // ]
222
- // let asks_dict = ordered_dict(true)
223
- // asks_dict.init(asks)
224
- // // asks_dict.del_before(3.333)
225
- // // asks_dict.del_after(5)
226
- // // asks_dict = ordered_dict(true)
227
-
228
- // console.log(asks_dict.entries())
229
-
230
- // let bids = [
231
- // [7, 1],
232
- // [6, 2],
233
- // [5, 3],
234
- // [4, 4],
235
- // [3, 3],
236
- // [2, 2],
237
- // [1, 1],
238
- // ]
239
- // let bids_dict = ordered_dict(false)
240
- // bids_dict.init(bids)
241
- // bids_dict.del_before(8)
242
- // // bids_dict.del_after(7)
243
- // console.log(bids_dict.entries())
96
+ const { ordered_dict, binary_find } = require('./ordered-dict.js')
244
97
 
245
98
  function random_id() {
246
99
  return _.random(100000000, 999999999)
@@ -451,51 +304,62 @@ function vol_position_orderbook(input_array, vol_target) {
451
304
  // )
452
305
 
453
306
  function combine_orderbooks(orderbooks_dict, length = undefined) {
454
- function merge_sorted(type) {
455
- let count = {}
456
- for (let exchange in orderbooks_dict) {
457
- count[exchange] = 0
458
- }
459
- let result = []
460
- // * -1 check if all exchanges are done
461
- while (_.sum(_.values(count)) !== _.keys(orderbooks_dict).length * -1) {
462
- let picked
463
- for (let exchange in orderbooks_dict) {
464
- if (_.get(orderbooks_dict, [exchange, type], []).length === 0) {
465
- count[exchange] = -1 // -1 means finished
466
- }
467
- if (count[exchange] === -1) {
468
- continue
469
- }
470
- if (_.get(orderbooks_dict, [exchange, type, count[exchange], 'length']) === 2) {
471
- orderbooks_dict[exchange][type][count[exchange]].push(exchange)
472
- }
473
- if (!picked) {
474
- picked = orderbooks_dict[exchange][type][count[exchange]]
475
- } else if (type === 'asks' && picked[0] > orderbooks_dict[exchange][type][count[exchange]][0]) {
476
- picked = orderbooks_dict[exchange][type][count[exchange]]
477
- } else if (type === 'bids' && picked[0] < orderbooks_dict[exchange][type][count[exchange]][0]) {
478
- picked = orderbooks_dict[exchange][type][count[exchange]]
479
- }
307
+ const exchanges = Object.keys(orderbooks_dict)
308
+ const numExchanges = exchanges.length
309
+ const limit = length === undefined ? Infinity : length
310
+
311
+ function merge_sorted(type, direction) {
312
+ const lists = new Array(numExchanges)
313
+ const indexes = new Array(numExchanges)
314
+ let activeCount = 0
315
+
316
+ for (let i = 0; i < numExchanges; i++) {
317
+ const list = orderbooks_dict[exchanges[i]][type]
318
+ if (list && list.length > 0) {
319
+ lists[i] = list
320
+ indexes[i] = 0
321
+ activeCount++
322
+ } else {
323
+ lists[i] = null
480
324
  }
481
- if (picked) {
482
- result.push(picked)
483
- let picked_exchange = picked[2]
484
- if (count[picked_exchange] < orderbooks_dict[picked_exchange][type].length - 1) {
485
- count[picked_exchange] += 1
486
- } else {
487
- count[picked_exchange] = -1 // -1 means finished
325
+ }
326
+
327
+ const result = []
328
+
329
+ while (activeCount > 0 && result.length < limit) {
330
+ let bestIdx = -1
331
+ let bestPrice = 0
332
+
333
+ for (let i = 0; i < numExchanges; i++) {
334
+ const list = lists[i]
335
+ if (list === null) continue
336
+ const price = list[indexes[i]][0]
337
+ if (bestIdx === -1 || (direction === 1 ? price < bestPrice : price > bestPrice)) {
338
+ bestPrice = price
339
+ bestIdx = i
488
340
  }
489
341
  }
490
- if (result.length === length) {
491
- break
342
+
343
+ if (bestIdx === -1) break
344
+
345
+ result.push(lists[bestIdx][indexes[bestIdx]])
346
+
347
+ const next = indexes[bestIdx] + 1
348
+ if (next < lists[bestIdx].length) {
349
+ indexes[bestIdx] = next
350
+ } else {
351
+ lists[bestIdx] = null
352
+ activeCount--
492
353
  }
493
354
  }
355
+
494
356
  return result
495
357
  }
496
- let asks = merge_sorted('asks')
497
- let bids = merge_sorted('bids')
498
- return { asks, bids }
358
+
359
+ return {
360
+ asks: merge_sorted('asks', 1),
361
+ bids: merge_sorted('bids', -1),
362
+ }
499
363
  }
500
364
 
501
365
  // console.log(
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@icgio/icg-utils",
3
- "version": "1.9.54",
3
+ "version": "1.9.56",
4
4
  "description": "Utils package.",
5
5
  "main": "index.js",
6
6
  "directories": {
7
7
  "lib": "lib"
8
8
  },
9
9
  "scripts": {
10
- "test": "node test/rate-limiter.test.js"
10
+ "test": "node test/rate-limiter.test.js && node test/combine-orderbooks.test.js && node test/ordered-dict.test.js && node test/sorted-book.test.js"
11
11
  },
12
12
  "repository": {
13
13
  "type": "git",
@@ -22,6 +22,7 @@
22
22
  "dependencies": {
23
23
  "@influxdata/influxdb-client": "^1.35.0",
24
24
  "@influxdata/influxdb-client-apis": "^1.35.0",
25
+ "bintrees": "^1.0.2",
25
26
  "csv-parse": "^5.6.0",
26
27
  "lodash": "^4.17.21",
27
28
  "needle": "^3.3.1",
@@ -0,0 +1,226 @@
1
+ const assert = require('node:assert/strict')
2
+ const { combine_orderbooks } = require('../lib/utils')
3
+
4
+ /*
5
+ * Tests for combine_orderbooks.
6
+ *
7
+ * The function does a k-way merge across per-exchange orderbooks. Three
8
+ * properties matter for the icg-exchanges-wrapper hot path:
9
+ * 1. Correctness — asks ascend, bids descend, limit is honoured.
10
+ * 2. Non-mutation — the input dict and its tuples are never touched.
11
+ * 3. Reference sharing — result tuples are the same objects as the inputs
12
+ * (Flavor 2). Callers rely on this to skip a deep clone upstream.
13
+ */
14
+
15
+ function testBasicMergeAscDesc() {
16
+ const input = {
17
+ binance: { asks: [[100, 1], [102, 2], [105, 3]], bids: [[99, 1], [97, 2], [95, 3]] },
18
+ bybit: { asks: [[101, 1], [103, 2], [104, 3]], bids: [[98, 1], [96, 2], [94, 3]] },
19
+ }
20
+ const r = combine_orderbooks(input, 4)
21
+ assert.deepStrictEqual(
22
+ r.asks.map((t) => t[0]),
23
+ [100, 101, 102, 103],
24
+ 'asks should merge ascending',
25
+ )
26
+ assert.deepStrictEqual(
27
+ r.bids.map((t) => t[0]),
28
+ [99, 98, 97, 96],
29
+ 'bids should merge descending',
30
+ )
31
+ assert.equal(r.asks.length, 4, 'asks should respect length limit')
32
+ assert.equal(r.bids.length, 4, 'bids should respect length limit')
33
+ }
34
+
35
+ function testTuplesAreLengthTwo() {
36
+ const input = {
37
+ binance: { asks: [[100, 1]], bids: [[99, 1]] },
38
+ bybit: { asks: [[101, 2]], bids: [[98, 2]] },
39
+ }
40
+ const r = combine_orderbooks(input, 10)
41
+ for (const t of r.asks) {
42
+ assert.equal(t.length, 2, 'result asks tuples should remain [price, amount] (no [2] augmentation)')
43
+ }
44
+ for (const t of r.bids) {
45
+ assert.equal(t.length, 2, 'result bids tuples should remain [price, amount] (no [2] augmentation)')
46
+ }
47
+ }
48
+
49
+ function testInputNeverMutated() {
50
+ const input = {
51
+ binance: { asks: [[100, 1], [102, 2]], bids: [[99, 1], [97, 2]] },
52
+ bybit: { asks: [[101, 1], [103, 2]], bids: [[98, 1], [96, 2]] },
53
+ }
54
+ // Snapshot input shape so we can detect any mutation
55
+ const snapshot = JSON.parse(JSON.stringify(input))
56
+ combine_orderbooks(input, 10)
57
+ assert.deepStrictEqual(input, snapshot, 'input dict should be byte-equal to its pre-call snapshot')
58
+ for (const ex of Object.keys(input)) {
59
+ for (const side of ['asks', 'bids']) {
60
+ for (const t of input[ex][side]) {
61
+ assert.equal(t.length, 2, `input ${ex}.${side} tuples should still be length 2 (no exchange tag pushed)`)
62
+ }
63
+ }
64
+ }
65
+ }
66
+
67
+ function testIdempotentOnRepeatedCalls() {
68
+ // Calling twice on the same input must produce identical output and still
69
+ // not mutate. This is the regression guard against the old behaviour where
70
+ // combine_orderbooks pushed exchange names onto input tuples.
71
+ const input = {
72
+ binance: { asks: [[100, 1], [102, 2]], bids: [[99, 1], [97, 2]] },
73
+ bybit: { asks: [[101, 1], [103, 2]], bids: [[98, 1], [96, 2]] },
74
+ }
75
+ const r1 = combine_orderbooks(input, 4)
76
+ const r2 = combine_orderbooks(input, 4)
77
+ assert.deepStrictEqual(
78
+ r1.asks.map((t) => [t[0], t[1]]),
79
+ r2.asks.map((t) => [t[0], t[1]]),
80
+ 'repeated calls should return identical asks',
81
+ )
82
+ assert.deepStrictEqual(
83
+ r1.bids.map((t) => [t[0], t[1]]),
84
+ r2.bids.map((t) => [t[0], t[1]]),
85
+ 'repeated calls should return identical bids',
86
+ )
87
+ }
88
+
89
+ function testResultAliasesInput() {
90
+ // Flavor 2: result tuples must be the SAME object refs as input tuples.
91
+ // This is the contract orders.js relies on to skip cloneDeep.
92
+ const input = {
93
+ binance: { asks: [[100, 1], [102, 2]], bids: [[99, 1]] },
94
+ bybit: { asks: [[101, 1]], bids: [[98, 1], [96, 2]] },
95
+ }
96
+ const r = combine_orderbooks(input, 10)
97
+ assert.equal(r.asks[0], input.binance.asks[0], 'asks[0] should be a ref to binance.asks[0]')
98
+ assert.equal(r.asks[1], input.bybit.asks[0], 'asks[1] should be a ref to bybit.asks[0]')
99
+ assert.equal(r.asks[2], input.binance.asks[1], 'asks[2] should be a ref to binance.asks[1]')
100
+ assert.equal(r.bids[0], input.binance.bids[0], 'bids[0] should be a ref to binance.bids[0]')
101
+ assert.equal(r.bids[1], input.bybit.bids[0], 'bids[1] should be a ref to bybit.bids[0]')
102
+ assert.equal(r.bids[2], input.bybit.bids[1], 'bids[2] should be a ref to bybit.bids[1]')
103
+ }
104
+
105
+ function testEmptyDict() {
106
+ const r = combine_orderbooks({}, 10)
107
+ assert.deepStrictEqual(r.asks, [], 'empty dict asks should be []')
108
+ assert.deepStrictEqual(r.bids, [], 'empty dict bids should be []')
109
+ }
110
+
111
+ function testEmptySidePerExchange() {
112
+ // One exchange has only asks, the other has only bids. Each side should
113
+ // be drawn from whichever exchange supplies it.
114
+ const input = {
115
+ binance: { asks: [[100, 1], [101, 2]], bids: [] },
116
+ bybit: { asks: [], bids: [[99, 1], [97, 2]] },
117
+ }
118
+ const r = combine_orderbooks(input, 5)
119
+ assert.deepStrictEqual(r.asks.map((t) => t[0]), [100, 101], 'asks should come from binance only')
120
+ assert.deepStrictEqual(r.bids.map((t) => t[0]), [99, 97], 'bids should come from bybit only')
121
+ }
122
+
123
+ function testSingleExchange() {
124
+ const input = {
125
+ binance: { asks: [[100, 1], [101, 2], [102, 3]], bids: [[99, 1], [98, 2]] },
126
+ }
127
+ const r = combine_orderbooks(input, 10)
128
+ assert.deepStrictEqual(r.asks.map((t) => t[0]), [100, 101, 102])
129
+ assert.deepStrictEqual(r.bids.map((t) => t[0]), [99, 98])
130
+ }
131
+
132
+ function testLengthLargerThanAvailable() {
133
+ // Asking for 100 levels when only 4 exist total per side should return
134
+ // exactly the 4 available, not pad or loop forever.
135
+ const input = {
136
+ binance: { asks: [[100, 1], [102, 2]], bids: [[99, 1], [97, 2]] },
137
+ bybit: { asks: [[101, 1], [103, 2]], bids: [[98, 1], [96, 2]] },
138
+ }
139
+ const r = combine_orderbooks(input, 100)
140
+ assert.equal(r.asks.length, 4)
141
+ assert.equal(r.bids.length, 4)
142
+ assert.deepStrictEqual(r.asks.map((t) => t[0]), [100, 101, 102, 103])
143
+ assert.deepStrictEqual(r.bids.map((t) => t[0]), [99, 98, 97, 96])
144
+ }
145
+
146
+ function testNoLengthLimit() {
147
+ const input = {
148
+ binance: { asks: [[100, 1], [102, 2]], bids: [[99, 1]] },
149
+ bybit: { asks: [[101, 1]], bids: [[98, 1], [96, 2]] },
150
+ }
151
+ const r = combine_orderbooks(input)
152
+ assert.deepStrictEqual(r.asks.map((t) => t[0]), [100, 101, 102], 'asks unbounded')
153
+ assert.deepStrictEqual(r.bids.map((t) => t[0]), [99, 98, 96], 'bids unbounded')
154
+ }
155
+
156
+ function testThreeExchangesInterleaving() {
157
+ const input = {
158
+ a: { asks: [[100, 1], [104, 1], [107, 1]], bids: [[99, 1], [95, 1], [92, 1]] },
159
+ b: { asks: [[101, 1], [103, 1], [108, 1]], bids: [[98, 1], [96, 1], [91, 1]] },
160
+ c: { asks: [[102, 1], [105, 1], [106, 1]], bids: [[97, 1], [94, 1], [93, 1]] },
161
+ }
162
+ const r = combine_orderbooks(input, 9)
163
+ assert.deepStrictEqual(
164
+ r.asks.map((t) => t[0]),
165
+ [100, 101, 102, 103, 104, 105, 106, 107, 108],
166
+ '3-way ask merge should produce sorted ascending',
167
+ )
168
+ assert.deepStrictEqual(
169
+ r.bids.map((t) => t[0]),
170
+ [99, 98, 97, 96, 95, 94, 93, 92, 91],
171
+ '3-way bid merge should produce sorted descending',
172
+ )
173
+ }
174
+
175
+ function testTiedPricesDeterministic() {
176
+ // Two exchanges quote the same top price. The result is implementation-
177
+ // defined but must be deterministic and must include both tuples.
178
+ const input = {
179
+ binance: { asks: [[100, 1], [102, 2]], bids: [[99, 1]] },
180
+ bybit: { asks: [[100, 5], [101, 5]], bids: [[99, 5]] },
181
+ }
182
+ const r1 = combine_orderbooks(input, 4)
183
+ const r2 = combine_orderbooks(input, 4)
184
+ assert.deepStrictEqual(
185
+ r1.asks.map((t) => [t[0], t[1]]),
186
+ r2.asks.map((t) => [t[0], t[1]]),
187
+ 'tied-price merge should be deterministic across calls',
188
+ )
189
+ // Both 100s should be present somewhere in the first two slots
190
+ const top_two = r1.asks.slice(0, 2).map((t) => t[0])
191
+ assert.deepStrictEqual(top_two, [100, 100], 'both tied tuples at price 100 should appear in the first two slots')
192
+ }
193
+
194
+ function testFractionalPrices() {
195
+ const input = {
196
+ binance: { asks: [[0.0001234, 1], [0.0001236, 2]], bids: [[0.0001233, 1]] },
197
+ bybit: { asks: [[0.0001235, 1]], bids: [[0.0001232, 1], [0.0001230, 2]] },
198
+ }
199
+ const r = combine_orderbooks(input, 5)
200
+ assert.deepStrictEqual(r.asks.map((t) => t[0]), [0.0001234, 0.0001235, 0.0001236])
201
+ assert.deepStrictEqual(r.bids.map((t) => t[0]), [0.0001233, 0.0001232, 0.000123])
202
+ }
203
+
204
+ function main() {
205
+ testBasicMergeAscDesc()
206
+ testTuplesAreLengthTwo()
207
+ testInputNeverMutated()
208
+ testIdempotentOnRepeatedCalls()
209
+ testResultAliasesInput()
210
+ testEmptyDict()
211
+ testEmptySidePerExchange()
212
+ testSingleExchange()
213
+ testLengthLargerThanAvailable()
214
+ testNoLengthLimit()
215
+ testThreeExchangesInterleaving()
216
+ testTiedPricesDeterministic()
217
+ testFractionalPrices()
218
+ console.log('combine_orderbooks tests passed')
219
+ }
220
+
221
+ try {
222
+ main()
223
+ } catch (err) {
224
+ console.error(err)
225
+ process.exit(1)
226
+ }
@@ -0,0 +1,343 @@
1
+ #!/usr/bin/env node
2
+ const { ordered_dict, binary_find } = require('../lib/ordered-dict.js')
3
+
4
+ let pass = 0, fail = 0
5
+ function assert(condition, msg) {
6
+ if (condition) { pass++ }
7
+ else { fail++; console.log(' FAIL:', msg) }
8
+ }
9
+ function eq(a, b, msg) {
10
+ const as = JSON.stringify(a), bs = JSON.stringify(b)
11
+ if (as === bs) { pass++ }
12
+ else { fail++; console.log(' FAIL:', msg, '— got', as, 'expected', bs) }
13
+ }
14
+
15
+ // ============================================================
16
+ console.log('--- binary_find ---')
17
+ // ============================================================
18
+
19
+ // Empty array
20
+ eq(binary_find(5, true, []), { found: false, index: 0 }, 'empty array ascending')
21
+ eq(binary_find(5, false, []), { found: false, index: 0 }, 'empty array descending')
22
+
23
+ // Single element - found
24
+ eq(binary_find(5, true, [5]).found, true, 'single element found asc')
25
+ eq(binary_find(5, false, [5]).found, true, 'single element found desc')
26
+
27
+ // Single element - not found
28
+ let r = binary_find(3, true, [5])
29
+ eq(r.found, false, 'single element not found asc')
30
+ eq(r.index, 0, 'insert before 5 in ascending')
31
+ r = binary_find(7, true, [5])
32
+ eq(r.index, 1, 'insert after 5 in ascending')
33
+
34
+ // Descending
35
+ r = binary_find(3, false, [5])
36
+ eq(r.index, 1, 'insert after 5 in descending (3 < 5 → goes after)')
37
+ r = binary_find(7, false, [5])
38
+ eq(r.index, 0, 'insert before 5 in descending (7 > 5 → goes before)')
39
+
40
+ // Multiple elements ascending
41
+ const asc = [10, 20, 30, 40, 50]
42
+ eq(binary_find(30, true, asc).found, true, 'find 30 in ascending')
43
+ eq(binary_find(30, true, asc).index, 2, 'find 30 at index 2')
44
+ eq(binary_find(25, true, asc).found, false, 'miss 25 in ascending')
45
+ eq(binary_find(25, true, asc).index, 2, '25 inserts at index 2 (between 20 and 30)')
46
+ eq(binary_find(5, true, asc).index, 0, '5 inserts at index 0 (before all)')
47
+ eq(binary_find(55, true, asc).index, 5, '55 inserts at index 5 (after all)')
48
+
49
+ // Multiple elements descending
50
+ const desc = [50, 40, 30, 20, 10]
51
+ eq(binary_find(30, false, desc).found, true, 'find 30 in descending')
52
+ eq(binary_find(30, false, desc).index, 2, 'find 30 at index 2 in desc')
53
+ eq(binary_find(25, false, desc).index, 3, '25 inserts at index 3 in desc (between 30 and 20)')
54
+ eq(binary_find(55, false, desc).index, 0, '55 inserts at index 0 in desc (before all)')
55
+ eq(binary_find(5, false, desc).index, 5, '5 inserts at index 5 in desc (after all)')
56
+
57
+ // ============================================================
58
+ console.log('--- ordered_dict: basic insert/val/del ---')
59
+ // ============================================================
60
+
61
+ // Ascending (asks)
62
+ const asks = ordered_dict(true)
63
+ asks.insert(30, 0.3)
64
+ asks.insert(10, 0.1)
65
+ asks.insert(20, 0.2)
66
+ eq(asks.keys(), [10, 20, 30], 'ascending insert order')
67
+ eq(asks.val(10), 0.1, 'val(10)')
68
+ eq(asks.val(20), 0.2, 'val(20)')
69
+ eq(asks.val(30), 0.3, 'val(30)')
70
+ eq(asks.val(99), undefined, 'val(99) missing')
71
+ eq(asks.length(), 3, 'length 3')
72
+ eq(asks.entries(), [[10, 0.1], [20, 0.2], [30, 0.3]], 'entries ascending')
73
+
74
+ // Descending (bids)
75
+ const bids = ordered_dict(false)
76
+ bids.insert(10, 0.1)
77
+ bids.insert(30, 0.3)
78
+ bids.insert(20, 0.2)
79
+ eq(bids.keys(), [30, 20, 10], 'descending insert order')
80
+ eq(bids.entries(), [[30, 0.3], [20, 0.2], [10, 0.1]], 'entries descending')
81
+
82
+ // Update existing key
83
+ bids.insert(20, 0.5)
84
+ eq(bids.val(20), 0.5, 'update existing key')
85
+ eq(bids.keys(), [30, 20, 10], 'keys unchanged after update')
86
+ eq(bids.length(), 3, 'length unchanged after update')
87
+
88
+ // Delete
89
+ bids.del(20)
90
+ eq(bids.keys(), [30, 10], 'after del(20)')
91
+ eq(bids.val(20), undefined, 'val(20) after delete')
92
+ eq(bids.length(), 2, 'length after delete')
93
+
94
+ // Delete non-existent
95
+ bids.del(999)
96
+ eq(bids.keys(), [30, 10], 'del non-existent is no-op')
97
+
98
+ // Delete last element
99
+ bids.del(30)
100
+ bids.del(10)
101
+ eq(bids.keys(), [], 'empty after deleting all')
102
+ eq(bids.length(), 0, 'length 0')
103
+
104
+ // Re-insert after emptying
105
+ bids.insert(50, 0.5)
106
+ eq(bids.keys(), [50], 'insert after empty')
107
+
108
+ // ============================================================
109
+ console.log('--- ordered_dict: insert edge cases ---')
110
+ // ============================================================
111
+
112
+ // Insert with v=0 should be no-op
113
+ const d = ordered_dict(true)
114
+ d.insert(10, 0)
115
+ eq(d.keys(), [], 'insert(k, 0) is no-op')
116
+ eq(d.length(), 0, 'length 0 after insert(k, 0)')
117
+
118
+ // Insert with v=null (loose == 0 is false for null)
119
+ d.insert(10, null)
120
+ eq(d.keys(), [10], 'insert(k, null) inserts (null != 0)')
121
+
122
+ // Insert with string key
123
+ const d2 = ordered_dict(true)
124
+ d2.insert('20.5', 1)
125
+ d2.insert('10.5', 2)
126
+ eq(d2.keys(), [10.5, 20.5], 'string keys parsed to float')
127
+
128
+ // Insert duplicate key — update value, don't duplicate in keys
129
+ const d3 = ordered_dict(true)
130
+ d3.insert(5, 1)
131
+ d3.insert(5, 2)
132
+ d3.insert(5, 3)
133
+ eq(d3.keys(), [5], 'no duplicate keys')
134
+ eq(d3.val(5), 3, 'last value wins')
135
+
136
+ // ============================================================
137
+ console.log('--- ordered_dict: del edge cases ---')
138
+ // ============================================================
139
+
140
+ // Delete from single-element
141
+ const d4 = ordered_dict(true)
142
+ d4.insert(10, 1)
143
+ d4.del(10)
144
+ eq(d4.keys(), [], 'del single element')
145
+ eq(d4.val(10), undefined, 'val gone after del')
146
+
147
+ // Delete then re-insert same key
148
+ d4.insert(10, 2)
149
+ eq(d4.keys(), [10], 're-insert after del')
150
+ eq(d4.val(10), 2, 'val correct after re-insert')
151
+
152
+ // Delete first element in ascending
153
+ const d5 = ordered_dict(true)
154
+ d5.insert(1, 0.1); d5.insert(2, 0.2); d5.insert(3, 0.3)
155
+ d5.del(1)
156
+ eq(d5.keys(), [2, 3], 'del first in ascending')
157
+
158
+ // Delete last element in ascending
159
+ d5.del(3)
160
+ eq(d5.keys(), [2], 'del last in ascending')
161
+
162
+ // Delete first element in descending
163
+ const d6 = ordered_dict(false)
164
+ d6.insert(1, 0.1); d6.insert(2, 0.2); d6.insert(3, 0.3)
165
+ d6.del(3) // first in desc order
166
+ eq(d6.keys(), [2, 1], 'del first in descending')
167
+
168
+ // ============================================================
169
+ console.log('--- ordered_dict: del_before / del_after ---')
170
+ // ============================================================
171
+
172
+ // del_before ascending — found key
173
+ const db1 = ordered_dict(true)
174
+ for (let i = 1; i <= 7; i++) db1.insert(i, i * 0.1)
175
+ db1.del_before(4)
176
+ eq(db1.keys(), [4, 5, 6, 7], 'del_before(4) ascending keeps 4,5,6,7')
177
+ eq(db1.val(3), undefined, 'val(3) gone')
178
+ eq(db1.val(4), 0.4, 'val(4) kept')
179
+
180
+ // del_before ascending — not found key (between 3 and 4)
181
+ const db2 = ordered_dict(true)
182
+ for (let i = 1; i <= 7; i++) db2.insert(i, i * 0.1)
183
+ db2.del_before(3.5)
184
+ eq(db2.keys(), [4, 5, 6, 7], 'del_before(3.5) removes 1,2,3')
185
+
186
+ // del_before ascending — key smaller than all
187
+ const db3 = ordered_dict(true)
188
+ db3.insert(5, 1); db3.insert(10, 2)
189
+ db3.del_before(3)
190
+ eq(db3.keys(), [5, 10], 'del_before(3) on [5,10] — nothing to delete')
191
+
192
+ // del_before ascending — key between first and second
193
+ const db3b = ordered_dict(true)
194
+ db3b.insert(5, 1); db3b.insert(10, 2); db3b.insert(15, 3)
195
+ db3b.del_before(7)
196
+ eq(db3b.keys(), [10, 15], 'del_before(7) on [5,10,15] removes 5')
197
+
198
+ // del_before ascending — key larger than all
199
+ const db4 = ordered_dict(true)
200
+ db4.insert(1, 1); db4.insert(2, 2); db4.insert(3, 3)
201
+ db4.del_before(10)
202
+ eq(db4.keys(), [], 'del_before(10) removes all (10 > all keys)')
203
+
204
+ // del_after ascending — found key
205
+ const da1 = ordered_dict(true)
206
+ for (let i = 1; i <= 7; i++) da1.insert(i, i * 0.1)
207
+ da1.del_after(4)
208
+ eq(da1.keys(), [1, 2, 3, 4], 'del_after(4) ascending keeps 1,2,3,4')
209
+ eq(da1.val(5), undefined, 'val(5) gone')
210
+ eq(da1.val(4), 0.4, 'val(4) kept')
211
+
212
+ // del_after ascending — not found key
213
+ const da2 = ordered_dict(true)
214
+ for (let i = 1; i <= 7; i++) da2.insert(i, i * 0.1)
215
+ da2.del_after(4.5)
216
+ eq(da2.keys(), [1, 2, 3, 4], 'del_after(4.5) keeps 1,2,3,4')
217
+
218
+ // del_after ascending — key larger than all
219
+ const da3 = ordered_dict(true)
220
+ da3.insert(1, 1); da3.insert(2, 2)
221
+ da3.del_after(10)
222
+ eq(da3.keys(), [1, 2], 'del_after(10) — nothing to delete')
223
+
224
+ // del_after ascending — key smaller than all
225
+ const da4 = ordered_dict(true)
226
+ da4.insert(1, 1); da4.insert(2, 2); da4.insert(3, 3)
227
+ da4.del_after(0)
228
+ eq(da4.keys(), [], 'del_after(0) removes all')
229
+
230
+ // del_before descending
231
+ const db5 = ordered_dict(false)
232
+ for (let i = 1; i <= 5; i++) db5.insert(i, i)
233
+ // desc order: [5, 4, 3, 2, 1]
234
+ db5.del_before(3)
235
+ eq(db5.keys(), [3, 2, 1], 'del_before(3) descending keeps 3,2,1 (removes 5,4)')
236
+
237
+ // del_after descending
238
+ const da5 = ordered_dict(false)
239
+ for (let i = 1; i <= 5; i++) da5.insert(i, i)
240
+ // desc order: [5, 4, 3, 2, 1]
241
+ da5.del_after(3)
242
+ eq(da5.keys(), [5, 4, 3], 'del_after(3) descending keeps 5,4,3 (removes 2,1)')
243
+
244
+ // ============================================================
245
+ console.log('--- ordered_dict: init ---')
246
+ // ============================================================
247
+
248
+ const di = ordered_dict(true)
249
+ di.init([[3, 0.3], [1, 0.1], [2, 0.2]])
250
+ eq(di.keys(), [1, 2, 3], 'init from unsorted pairs')
251
+ eq(di.val(2), 0.2, 'init val correct')
252
+
253
+ // ============================================================
254
+ console.log('--- ordered_dict: push (unsorted append) ---')
255
+ // ============================================================
256
+
257
+ const dp = ordered_dict(true)
258
+ dp.push(3, 0.3)
259
+ dp.push(1, 0.1)
260
+ dp.push(2, 0.2)
261
+ eq(dp.keys(), [3, 1, 2], 'push preserves insertion order (NOT sorted)')
262
+ eq(dp.val(1), 0.1, 'push val correct')
263
+
264
+ // push duplicate key — update value, don't add key
265
+ dp.push(3, 0.9)
266
+ eq(dp.keys(), [3, 1, 2], 'push dup — no extra key')
267
+ eq(dp.val(3), 0.9, 'push dup — value updated')
268
+
269
+ // ============================================================
270
+ console.log('--- ordered_dict: large book stress ---')
271
+ // ============================================================
272
+
273
+ const big = ordered_dict(true)
274
+ const N = 5000
275
+ for (let i = 0; i < N; i++) big.insert(Math.random() * 100000, Math.random())
276
+ eq(big.length(), N, 'large book has N entries')
277
+
278
+ // Verify sorted order
279
+ const k = big.keys()
280
+ let sorted = true
281
+ for (let i = 1; i < k.length; i++) {
282
+ if (k[i] < k[i - 1]) { sorted = false; break }
283
+ }
284
+ assert(sorted, 'large book is sorted ascending')
285
+
286
+ // Delete half
287
+ for (let i = 0; i < N / 2; i++) big.del(k[i])
288
+ eq(big.length(), N / 2, 'half deleted')
289
+
290
+ // Verify still sorted
291
+ const k2 = big.keys()
292
+ sorted = true
293
+ for (let i = 1; i < k2.length; i++) {
294
+ if (k2[i] < k2[i - 1]) { sorted = false; break }
295
+ }
296
+ assert(sorted, 'still sorted after deletes')
297
+
298
+ // ============================================================
299
+ console.log('--- ordered_dict: float precision edge cases ---')
300
+ // ============================================================
301
+
302
+ const fp = ordered_dict(true)
303
+ fp.insert(0.1, 1)
304
+ fp.insert(0.2, 2)
305
+ fp.insert(0.3, 3)
306
+ eq(fp.val(0.1), 1, 'float key 0.1')
307
+ eq(fp.val(0.3), 3, 'float key 0.3')
308
+
309
+ // parseFloat edge
310
+ fp.insert('71234.56', 0.5)
311
+ eq(fp.val(71234.56), 0.5, 'string→float key')
312
+
313
+ // ============================================================
314
+ console.log('--- ordered_dict: interleaved insert/del sequence ---')
315
+ // ============================================================
316
+
317
+ // Simulates real orderbook churn
318
+ const ob = ordered_dict(true)
319
+ ob.insert(100, 1.0)
320
+ ob.insert(101, 0.5)
321
+ ob.insert(102, 0.3)
322
+ eq(ob.keys(), [100, 101, 102], 'initial asks')
323
+
324
+ ob.del(101)
325
+ ob.insert(100.5, 0.2)
326
+ eq(ob.keys(), [100, 100.5, 102], 'after del(101) + insert(100.5)')
327
+
328
+ ob.insert(100, 1.5) // update existing
329
+ eq(ob.val(100), 1.5, 'update 100')
330
+ eq(ob.keys(), [100, 100.5, 102], 'keys unchanged on update')
331
+
332
+ ob.del(100)
333
+ ob.del(100.5)
334
+ ob.del(102)
335
+ eq(ob.keys(), [], 'empty after clearing all')
336
+
337
+ ob.insert(99, 0.1)
338
+ eq(ob.keys(), [99], 'insert after empty')
339
+
340
+ // ============================================================
341
+ console.log('')
342
+ console.log('=== ordered_dict tests: %d passed, %d failed ===', pass, fail)
343
+ if (fail > 0) process.exit(1)
@@ -0,0 +1,257 @@
1
+ #!/usr/bin/env node
2
+ const sorted_book = require('../lib/sorted-book.js')
3
+
4
+ let pass = 0, fail = 0
5
+ function assert(condition, msg) {
6
+ if (condition) { pass++ }
7
+ else { fail++; console.log(' FAIL:', msg) }
8
+ }
9
+ function eq(a, b, msg) {
10
+ const as = JSON.stringify(a), bs = JSON.stringify(b)
11
+ if (as === bs) { pass++ }
12
+ else { fail++; console.log(' FAIL:', msg, '— got', as, 'expected', bs) }
13
+ }
14
+
15
+ // ============================================================
16
+ console.log('--- sorted_book: basic insert/val/del ---')
17
+ // ============================================================
18
+
19
+ // Ascending (asks)
20
+ const asks = sorted_book(true)
21
+ asks.insert(30, 0.3)
22
+ asks.insert(10, 0.1)
23
+ asks.insert(20, 0.2)
24
+ eq(asks.keys(), [10, 20, 30], 'ascending insert order')
25
+ eq(asks.top(), 10, 'top = lowest ask')
26
+ eq(asks.val(10), 0.1, 'val(10)')
27
+ eq(asks.val(20), 0.2, 'val(20)')
28
+ eq(asks.val(30), 0.3, 'val(30)')
29
+ eq(asks.val(99), undefined, 'val(99) missing')
30
+ eq(asks.length(), 3, 'length 3')
31
+ eq(asks.entries(), [[10, 0.1], [20, 0.2], [30, 0.3]], 'entries ascending')
32
+
33
+ // Descending (bids)
34
+ const bids = sorted_book(false)
35
+ bids.insert(10, 0.1)
36
+ bids.insert(30, 0.3)
37
+ bids.insert(20, 0.2)
38
+ eq(bids.keys(), [30, 20, 10], 'descending insert order')
39
+ eq(bids.top(), 30, 'top = highest bid')
40
+ eq(bids.entries(), [[30, 0.3], [20, 0.2], [10, 0.1]], 'entries descending')
41
+
42
+ // Update existing key
43
+ bids.insert(20, 0.5)
44
+ eq(bids.val(20), 0.5, 'update existing key')
45
+ eq(bids.keys(), [30, 20, 10], 'keys unchanged after update')
46
+ eq(bids.length(), 3, 'length unchanged after update')
47
+
48
+ // Delete
49
+ bids.del(20)
50
+ eq(bids.keys(), [30, 10], 'after del(20)')
51
+ eq(bids.val(20), undefined, 'val(20) after delete')
52
+ eq(bids.length(), 2, 'length after delete')
53
+ eq(bids.top(), 30, 'top after del(20)')
54
+
55
+ // Delete top
56
+ bids.del(30)
57
+ eq(bids.top(), 10, 'top after del(30)')
58
+
59
+ // Delete non-existent
60
+ bids.del(999)
61
+ eq(bids.keys(), [10], 'del non-existent is no-op')
62
+
63
+ // Delete last element
64
+ bids.del(10)
65
+ eq(bids.keys(), [], 'empty after deleting all')
66
+ eq(bids.length(), 0, 'length 0')
67
+ eq(bids.top(), null, 'top on empty = null')
68
+
69
+ // Re-insert after emptying
70
+ bids.insert(50, 0.5)
71
+ eq(bids.keys(), [50], 'insert after empty')
72
+ eq(bids.top(), 50, 'top after re-insert')
73
+
74
+ // ============================================================
75
+ console.log('--- sorted_book: insert edge cases ---')
76
+ // ============================================================
77
+
78
+ // Insert with v=0 should be no-op
79
+ const d = sorted_book(true)
80
+ d.insert(10, 0)
81
+ eq(d.keys(), [], 'insert(k, 0) is no-op')
82
+
83
+ // Insert with string key
84
+ const d2 = sorted_book(true)
85
+ d2.insert('20.5', 1)
86
+ d2.insert('10.5', 2)
87
+ eq(d2.keys(), [10.5, 20.5], 'string keys parsed to float')
88
+
89
+ // Insert duplicate key — update value
90
+ const d3 = sorted_book(true)
91
+ d3.insert(5, 1)
92
+ d3.insert(5, 2)
93
+ d3.insert(5, 3)
94
+ eq(d3.keys(), [5], 'no duplicate keys')
95
+ eq(d3.val(5), 3, 'last value wins')
96
+ eq(d3.length(), 1, 'length stays 1')
97
+
98
+ // ============================================================
99
+ console.log('--- sorted_book: del edge cases ---')
100
+ // ============================================================
101
+
102
+ // Delete from single-element
103
+ const d4 = sorted_book(true)
104
+ d4.insert(10, 1)
105
+ d4.del(10)
106
+ eq(d4.keys(), [], 'del single element')
107
+ eq(d4.val(10), undefined, 'val gone after del')
108
+ eq(d4.top(), null, 'top null after del')
109
+
110
+ // Delete then re-insert same key
111
+ d4.insert(10, 2)
112
+ eq(d4.keys(), [10], 're-insert after del')
113
+ eq(d4.val(10), 2, 'val correct after re-insert')
114
+
115
+ // Delete first in ascending
116
+ const d5 = sorted_book(true)
117
+ d5.insert(1, 0.1); d5.insert(2, 0.2); d5.insert(3, 0.3)
118
+ d5.del(1)
119
+ eq(d5.keys(), [2, 3], 'del first in ascending')
120
+ eq(d5.top(), 2, 'top updated')
121
+
122
+ // Delete last in ascending
123
+ d5.del(3)
124
+ eq(d5.keys(), [2], 'del last in ascending')
125
+
126
+ // ============================================================
127
+ console.log('--- sorted_book: init ---')
128
+ // ============================================================
129
+
130
+ const di = sorted_book(true)
131
+ di.init([[3, 0.3], [1, 0.1], [2, 0.2]])
132
+ eq(di.keys(), [1, 2, 3], 'init from unsorted pairs')
133
+ eq(di.val(2), 0.2, 'init val correct')
134
+ eq(di.top(), 1, 'top after init')
135
+
136
+ // ============================================================
137
+ console.log('--- sorted_book: large book stress ---')
138
+ // ============================================================
139
+
140
+ const big = sorted_book(true)
141
+ const N = 10000
142
+ const inserted_keys = []
143
+ for (let i = 0; i < N; i++) {
144
+ const k = Math.random() * 100000
145
+ big.insert(k, Math.random())
146
+ inserted_keys.push(k)
147
+ }
148
+ eq(big.length(), N, 'large book has N entries')
149
+
150
+ // Verify sorted ascending
151
+ const k = big.keys()
152
+ let sorted = true
153
+ for (let i = 1; i < k.length; i++) {
154
+ if (k[i] < k[i - 1]) { sorted = false; break }
155
+ }
156
+ assert(sorted, 'large book is sorted ascending')
157
+
158
+ // top is the minimum
159
+ eq(big.top(), k[0], 'top matches keys()[0]')
160
+
161
+ // Delete half by key
162
+ for (let i = 0; i < N / 2; i++) big.del(inserted_keys[i])
163
+ eq(big.length(), N / 2, 'half deleted')
164
+
165
+ // Verify still sorted
166
+ const k2 = big.keys()
167
+ sorted = true
168
+ for (let i = 1; i < k2.length; i++) {
169
+ if (k2[i] < k2[i - 1]) { sorted = false; break }
170
+ }
171
+ assert(sorted, 'still sorted after deletes')
172
+
173
+ // top is still correct
174
+ eq(big.top(), k2[0], 'top still matches after deletes')
175
+
176
+ // ============================================================
177
+ console.log('--- sorted_book: descending large stress ---')
178
+ // ============================================================
179
+
180
+ const big_desc = sorted_book(false)
181
+ for (let i = 0; i < N; i++) big_desc.insert(Math.random() * 100000, Math.random())
182
+ const kd = big_desc.keys()
183
+ let desc_sorted = true
184
+ for (let i = 1; i < kd.length; i++) {
185
+ if (kd[i] > kd[i - 1]) { desc_sorted = false; break }
186
+ }
187
+ assert(desc_sorted, 'large desc book is sorted descending')
188
+ eq(big_desc.top(), kd[0], 'desc top = highest = keys()[0]')
189
+
190
+ // ============================================================
191
+ console.log('--- sorted_book: interleaved churn ---')
192
+ // ============================================================
193
+
194
+ const ob = sorted_book(true)
195
+ ob.insert(100, 1.0)
196
+ ob.insert(101, 0.5)
197
+ ob.insert(102, 0.3)
198
+ eq(ob.keys(), [100, 101, 102], 'initial asks')
199
+ eq(ob.top(), 100, 'initial top')
200
+
201
+ ob.del(101)
202
+ ob.insert(100.5, 0.2)
203
+ eq(ob.keys(), [100, 100.5, 102], 'after churn')
204
+ eq(ob.top(), 100, 'top unchanged')
205
+
206
+ ob.del(100)
207
+ eq(ob.top(), 100.5, 'top updated after del(100)')
208
+
209
+ ob.insert(99, 0.05)
210
+ eq(ob.top(), 99, 'new best ask')
211
+
212
+ ob.del(99)
213
+ ob.del(100.5)
214
+ ob.del(102)
215
+ eq(ob.keys(), [], 'empty after clearing')
216
+ eq(ob.top(), null, 'top null when empty')
217
+
218
+ ob.insert(200, 0.1)
219
+ eq(ob.top(), 200, 'first insert after empty')
220
+
221
+ // ============================================================
222
+ console.log('--- sorted_book: API compatibility with ordered_dict ---')
223
+ // ============================================================
224
+
225
+ // Both should produce the same results for the same sequence of operations
226
+ const { ordered_dict } = require('../lib/ordered-dict.js')
227
+ const od = ordered_dict(true)
228
+ const sb = sorted_book(true)
229
+
230
+ const ops = [
231
+ ['insert', 50, 0.5],
232
+ ['insert', 30, 0.3],
233
+ ['insert', 70, 0.7],
234
+ ['insert', 10, 0.1],
235
+ ['insert', 90, 0.9],
236
+ ['insert', 50, 0.55], // update
237
+ ['del', 30],
238
+ ['insert', 40, 0.4],
239
+ ['del', 10],
240
+ ['insert', 60, 0.6],
241
+ ]
242
+
243
+ for (const [op, ...args] of ops) {
244
+ od[op](...args)
245
+ sb[op](...args)
246
+ }
247
+
248
+ eq(sb.keys(), od.keys(), 'keys match ordered_dict')
249
+ eq(sb.entries(), od.entries(), 'entries match ordered_dict')
250
+ eq(sb.length(), od.length(), 'length matches ordered_dict')
251
+ eq(sb.val(50), od.val(50), 'val(50) matches')
252
+ eq(sb.val(30), od.val(30), 'val(30) deleted in both')
253
+
254
+ // ============================================================
255
+ console.log('')
256
+ console.log('=== sorted_book tests: %d passed, %d failed ===', pass, fail)
257
+ if (fail > 0) process.exit(1)