metanum 2.1.1 → 2.1.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 (6) hide show
  1. package/README.md +1103 -1042
  2. package/format-metanum.js +2137 -2144
  3. package/metanum.js +7204 -7164
  4. package/package.json +30 -30
  5. package/test-interface.html +83 -83
  6. package/test_mixed.js +3107 -2755
package/format-metanum.js CHANGED
@@ -1,2145 +1,2138 @@
1
- // Author: dlsdl v2.1.1
2
- // v2.1.1 Fix(format): exact token form for non-integer multi-a layers and past multiLetterLimit
3
- // Code snippets and templates from format-omeganum.js
4
- // Uses dlsdl's Letter Notation (see README.md)
5
-
6
- // Set to 1 to print debug information to console
7
- let FORMAT_DEBUG = 0
8
-
9
- // ─── Configuration Options ────────────────────────────────────────
10
- const FORMAT_OPTIONS = {
11
- smallNotationUseE: true, //true/false
12
- smallNotationThreshold: 3, //0~9
13
- decimalPlaces: 3, //0~9
14
- decimalThreshold: 3, //0~15
15
- useCommas: true, //true/false
16
- sciThreshold: 9, //0~15
17
- sciSignificantDigits: 3, //0~9
18
- sciDecimalThreshold: 3, //0~15
19
- singleLetterDigits: 3, //0~9
20
- repeatLetterThreshold: 3, //2~9
21
- multiLetterDigits: 3, //0~9
22
- multiLetterRepeatThreshold: 3,//2~9
23
- multiLetterLimit: 4, //2~9
24
- epsilonSignificantDigits: 6 //0~9
25
- }
26
-
27
- // #28: keep the exact A(a×k) token past multiLetterLimit up to this many a's;
28
- // beyond it, fall back to the historical single-letter carry approximation.
29
- const MULTI_TOKEN_CAP = 64
30
-
31
- // ─── Utility Functions ───────────────────────────────────────────
32
-
33
- function commaFormat(num) {
34
- if (!FORMAT_OPTIONS.useCommas) {
35
- let n = typeof num === 'number' ? num : (num.toNumber ? num.toNumber() : Number(num))
36
- if (isNaN(n) || !isFinite(n)) return "NaN"
37
- return String(Math.floor(n))
38
- }
39
- if (num === null || num === undefined) return "NaN"
40
- let n = typeof num === 'number' ? num : (num.toNumber ? num.toNumber() : Number(num))
41
- if (isNaN(n) || !isFinite(n)) return "NaN"
42
- if (n < 0.001) return "0"
43
- let init = n.toString()
44
- let portions = init.split(".")
45
- portions[0] = portions[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
46
- return portions[0]
47
- }
48
-
49
- function regularFormat(num, precision) {
50
- if (num === null || num === undefined) return "NaN"
51
- let n = typeof num === 'number' ? num : (num.toNumber ? num.toNumber() : Number(num))
52
- if (isNaN(n) || !isFinite(n)) return "NaN"
53
- if (n < 0.001) return (0).toFixed(precision)
54
- if (precision === 0) return commaFormat(Math.floor(n))
55
- let fmt
56
- if (Number.isInteger(n) && precision > 0) {
57
- fmt = n + "." + "0".repeat(precision)
58
- } else {
59
- fmt = n.toFixed(precision)
60
- }
61
- // Add commas to integer part if useCommas is enabled
62
- if (FORMAT_OPTIONS.useCommas && precision > 0) {
63
- let parts = fmt.split(".")
64
- parts[0] = parts[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
65
- fmt = parts.join(".")
66
- }
67
- return fmt
68
- }
69
-
70
- // ─── MetaNum-Specific Polarize ───────────────────────────────────
71
- // r0 is [base, e, f, g, ...]: r0[0] is the argument, r0[1..] count the E/F/G…
72
- // operations (levels 1, 2, 3, …). Binary form αΓβ: bottom = α (mantissa in
73
- // [1,10)), top = β, height = Γ (1=E … 22=Z), repeat = count of repeated
74
- // operations at the highest level (>1 means repeated letters).
75
- function metaPolarize(r0, num) {
76
- if (FORMAT_DEBUG >= 1) console.log("metaPolarize input:", JSON.stringify(r0))
77
- if (r0.length === 0) r0 = [0]
78
-
79
- // Find the highest non-zero index (level)
80
- let highest = 0
81
- for (let i = r0.length - 1; i >= 1; i--) {
82
- if (r0[i] > 0) { highest = i; break }
83
- }
84
-
85
- if (highest === 0) {
86
- // Simple number: just r0[0], no higher levels
87
- let bottom = r0[0]
88
- let top = 0
89
- let height = 0
90
- if (bottom >= 10) {
91
- let logVal = Math.log10(bottom)
92
- bottom = Math.pow(10, logVal - Math.floor(logVal))
93
- top = Math.floor(logVal)
94
- height = 1
95
- }
96
- if (FORMAT_DEBUG >= 1) console.log("metaPolarize simple:", {bottom, top, height, repeat: 1})
97
- return {bottom, top, height, repeat: 1}
98
- }
99
-
100
- // ── Climb through E level to compute the F-level argument ──
101
- // r0 = [v, e, f, g, ...]
102
- // For E^n (highest=1): climb E to convert to F format
103
- // For F^n or higher (highest>=2): compute the argument at the E→F boundary
104
- let value = r0[0]
105
- let eCount = r0[1] || 0
106
-
107
- // Climb the base value through E level
108
- let eClimbExtra = 0
109
- while (value >= 10) {
110
- value = Math.log10(value)
111
- eClimbExtra++
112
- }
113
- eCount += eClimbExtra
114
-
115
- // Compute the F-level argument from the climbed E value
116
- let fArg
117
- if (value >= 1) {
118
- fArg = eCount + Math.log10(value)
119
- } else {
120
- fArg = eCount + value - 1
121
- if (fArg < 1) fArg = eCount + Math.log10(Math.pow(10, value))
122
- }
123
-
124
- if (highest === 1) {
125
- // E level only: convert to F format
126
- let bottom = value
127
- let top = eCount
128
- let height = 1
129
- let repeat = eCount
130
- if (top >= 2) {
131
- height = 2
132
- if (bottom < 1) {
133
- bottom = Math.pow(10, bottom)
134
- }
135
- top = Math.floor(top)
136
- repeat = 1
137
- } else {
138
- bottom = Math.pow(10, bottom - Math.floor(bottom))
139
- top = Math.floor(top)
140
- }
141
- if (FORMAT_DEBUG >= 1) console.log("metaPolarize E level:", {bottom, top, height, repeat})
142
- return {bottom, top, height, repeat}
143
- }
144
-
145
- // ── Higher levels (F, G, H, ..., Z) ──
146
- // For mixed levels like FE20 or G10, the F argument is the value after E operations.
147
- // Try to compute it directly (E^e(base) = 10^e * base for e=1, or tower for e>1).
148
- let levelArg = fArg
149
- let eOps = r0[1] || 0
150
- let canCompute = false
151
- if (eOps > 0) {
152
- let eVal = r0[0]
153
- canCompute = true
154
- for (let i = 0; i < eOps; i++) {
155
- eVal = Math.pow(10, eVal)
156
- if (!isFinite(eVal) || eVal > 1e308) {
157
- canCompute = false
158
- break
159
- }
160
- }
161
- if (canCompute) {
162
- levelArg = eVal
163
- }
164
- // If not computable, levelArg stays as fArg (from E climbing)
165
- }
166
-
167
- let height = highest
168
- let repeat = r0[highest] || 0
169
-
170
- // ── Case 1: Directly computable (e.g., FE20) ──
171
- // Don't climb the computed value; use it directly as the top argument.
172
- if (canCompute) {
173
- let bottom = 1.0
174
- let top = levelArg
175
- if (FORMAT_DEBUG >= 1) console.log("metaPolarize computable:", {bottom, top, height, repeat})
176
- return {bottom, top, height, repeat}
177
- }
178
-
179
- // ── Case 2: Not computable ──
180
- // Check for the "all-8s" pattern: base=10^10 and all intermediate levels are 8.
181
- // This pattern arises when the original argument was 10 (e.g., Z10, G10, ZZ10).
182
- let all8 = (r0[0] === 10000000000)
183
- for (let i = 2; i < highest && all8; i++) {
184
- if ((r0[i] || 0) !== 8) all8 = false
185
- }
186
- if (all8) {
187
- // The normalization collapses one level when the argument is 10:
188
- // Z(10) → Y^8(...E^8(10^10)...) → letter level NOT in array, r0[highest]=8
189
- // ZZ(10) → Z(Y^8(...E^8(10^10)...)) → letter level IS in array, r0[highest]≠8
190
- let bottom = 1.0
191
- let top = 10
192
- if (r0[highest] === 8) {
193
- // Letter level not present (e.g., Z10, G10): go up one level, repeat=1
194
- height = highest + 1
195
- repeat = 1
196
- } else {
197
- // Letter level present (e.g., ZZ10, ZZZ10): add 1 for the base level
198
- repeat = 1 + repeat
199
- }
200
- if (FORMAT_DEBUG >= 1) console.log("metaPolarize all-8s:", {bottom, top, height, repeat})
201
- return {bottom, top, height, repeat}
202
- }
203
-
204
- // ── Case 3: General non-computable ──
205
- // Climb through intermediate levels to compute the argument at the highest level.
206
- if (eOps > 0) {
207
- for (let lv = 2; lv < highest; lv++) {
208
- let cnt = r0[lv] || 0
209
- let climbExtra = 0
210
- while (levelArg >= 10) {
211
- levelArg = Math.log10(levelArg)
212
- climbExtra++
213
- }
214
- cnt += climbExtra
215
- levelArg = cnt + Math.log10(Math.max(levelArg, 1))
216
- }
217
- }
218
-
219
- // When the F argument was not computable and the highest level is F (level 2),
220
- // the E→F conversion adds 1 to the effective F count.
221
- if (highest === 2 && eOps > 0) {
222
- repeat += 1
223
- }
224
-
225
- // Climb at the highest level to compute the total repeat count
226
- let climbExtra = 0
227
- let argVal = levelArg
228
- while (argVal >= 10) {
229
- argVal = Math.log10(argVal)
230
- climbExtra++
231
- }
232
- let totalRepeat = repeat + climbExtra
233
-
234
- // Compute bottom (mantissa) and top (argument) from the climbed argVal
235
- let bottom
236
- if (argVal < 1) {
237
- bottom = Math.pow(10, argVal)
238
- } else {
239
- bottom = argVal
240
- }
241
- let top = Math.floor(levelArg)
242
-
243
- if (FORMAT_DEBUG >= 1) console.log("metaPolarize high level:", {bottom, top, height, repeat: totalRepeat, levelArg, climbExtra})
244
- return {bottom, top, height, repeat: totalRepeat}
245
- }
246
-
247
- // ─── Letter Name: Map height index to dlsdl's letter name ────────
248
- // height 1 = E, 2 = F, ..., 22 = Z
249
- // height 23 = Aa, 24 = Ab, ..., 48 = Az, 49 = Ba, ..., 698 = Zz
250
- // height 699 = Aaa, ...
251
- function letterName(height) {
252
- if (height < 1) return "E"
253
- if (height <= 22) {
254
- // E = charCode 69, F = 70, ..., Z = 90
255
- return String.fromCharCode(68 + height)
256
- }
257
-
258
- // Multi-letter: height >= 23 maps to the bijective base-26 sequence
259
- let n = height - 23 // 0-based into multi-letter: 0=Aa, 1=Ab, ..., 25=Az, 26=Ba, ...
260
-
261
- // Determine number of letters (starts at 2: Aa-Zz is 26*26 = 676 values)
262
- let digits = 2
263
- let rangeSize = 26 * 26
264
- let offset = 0
265
- while (n >= offset + rangeSize) {
266
- offset += rangeSize
267
- digits++
268
- rangeSize *= 26
269
- }
270
-
271
- n -= offset
272
- // n is now a base-26 number with 'digits' digits
273
- // First digit is uppercase (A-Z), rest are lowercase (a-z)
274
- let result = ""
275
- let divisor = Math.pow(26, digits - 1)
276
- for (let i = 0; i < digits; i++) {
277
- let digit = Math.floor(n / divisor)
278
- n %= divisor
279
- divisor /= 26
280
- if (i === 0) {
281
- result += String.fromCharCode(65 + digit) // A-Z
282
- } else {
283
- result += String.fromCharCode(97 + digit) // a-z
284
- }
285
- }
286
- return result
287
- }
288
-
289
- // ─── Letter token with the multiLetterLimit symbol carry ──────────
290
- // A k-letter combination (Aa, Aaa, …) sits at level ω^(k-1). Past
291
- // FORMAT_OPTIONS.multiLetterLimit the notation switches to the symbol form
292
- // !αAaβ: β is the top ω-exponent (k-1), α's digits are the CNF coefficients
293
- // (the letter's own digits), keeping the diagonal mantissa inside [2,10).
294
- function letterTokenOf(height) {
295
- let plain = letterName(height)
296
- let limit = Math.max(2, FORMAT_OPTIONS.multiLetterLimit | 0)
297
- if (plain.length <= limit) return { sym: "", letter: plain, arg: 0, mant: null }
298
- // The carried form is "!" + the single-letter αΓβ: "!" adds one ω^ layer
299
- // on top of Γ, so a diagonal Aaa…a (= ω^k, too long for multiLetterLimit)
300
- // becomes !αHβ with H = the finite level k (!2.000Aa4 = !1H10 = 10{ω^4}10
301
- // vs 2.000Aa4 = 1H10 = 10{4}10); β is the argument (ω³*50/100/200 stay
302
- // apart as !1H51/!1H101/!1H201). Only when the single-letter chain is
303
- // exhausted does it fall back to the coarser !αAaβ form.
304
- let expo = plain.length - 1
305
- if (expo >= 1 && expo <= 22) {
306
- return { sym: "!", letter: letterName(expo), arg: expo, mant: 1, useBeta: true }
307
- }
308
- let mant = plain.charCodeAt(0) - 64 // coefficient of ω^(k-1)
309
- for (let i = 1; i < plain.length; i++) {
310
- mant += (plain.charCodeAt(i) - 97) * Math.pow(10, -i)
311
- }
312
- if (mant < 2) mant = 2 // diagonal [2,10) anchor
313
- if (mant >= 10) mant = 9 + (mant - 10) / 170 // keep α ∈ [2,10)
314
- return { sym: "!", letter: "Aa", arg: expo, mant: mant }
315
- }
316
-
317
- // Emit α·letter·β for a token: the plain form is αΓβ, the carried form is the
318
- // symbol-first !αAaβ whose α is the definition mantissa and β the ω-exponent.
319
- function emitLetterToken(tok, alphaStr, betaStr, precision) {
320
- if (!tok.sym) return alphaStr + tok.letter + betaStr
321
- let a = (tok.mant === null || tok.mant === undefined) ? alphaStr
322
- : regularFormat(tok.mant, precision)
323
- // the single-letter carried form keeps the caller's argument (!1H51), the
324
- // Aa form carries the ω-exponent instead
325
- if (tok.useBeta) return tok.sym + a + tok.letter + betaStr
326
- return tok.sym + a + tok.letter + formatR0Arg(tok.arg, precision)
327
- }
328
-
329
- // ─── Symbol Name: Map layer to symbol ────────────────────────────
330
- const SYMBOLS = "!@#$%&~<>?"
331
- function symbolName(layer) {
332
- if (layer <= 0) return ""
333
- if (layer <= SYMBOLS.length) return SYMBOLS[layer - 1]
334
- // For layers beyond SYMBOLS, formatLayer uses the ε format: αεβ
335
- return ""
336
- }
337
-
338
- // ─── Ordinal Letter: Extract letter name from ordinal rows ───────
339
- // Format A (3+ elements): [count, v1..vN, diag] — diag 1-26 (A-Z, uppercase),
340
- // v1..vN 0-25 (a-z, lowercase), count = repetition count.
341
- // Format B (2 elements): [count, value] — count at ω-level, value the
342
- // ordinal level number (901 means ω*901); letter is always "Aa".
343
-
344
- // Snap CNF coefficients (little-endian [a1..ak], ordinal ω^(k-1)·ak+…+a1) to
345
- // the ones the letter grid can name: 0 ≤ ai ≤ 25, top ak ≤ 26. Larger
346
- // coefficients carry UP (ω*2+96 → ω*3 (Ca), ω*99 → ω² (Aaa), ω²*100 → ω³
347
- // (Aaaa)), so an unnamed ordinal displays as the next nameable one above it.
348
- function snapCoeffsToGrid(coeffs) {
349
- let r = (coeffs || []).slice()
350
- // little-endian ORDINAL carry: index 0 is the constant term. A term above
351
- // its grid bound absorbs everything below it (ω^i·c + lower < ω^(i+1)) and
352
- // bumps the next power — ω*2+99 → ω*3 (Ca), ω*99+9 → ω² (Aaa),
353
- // ω²*100 → ω³ (Aaaa) — so the snapped ordinal is the TIGHTEST nameable
354
- // ordinal above the original one.
355
- for (let i = 0; i < r.length; i++) {
356
- let c = r[i]
357
- if (typeof c !== 'number' || !isFinite(c) || c < 0) { r[i] = 0; continue }
358
- c = Math.round(c) // integer coefficients only
359
- let bound = (i === r.length - 1) ? 26 : 25 // top may reach 26 (A-Z)
360
- if (c <= bound) { r[i] = c; continue }
361
- for (let j = 0; j <= i; j++) r[j] = 0 // the carry absorbs the tail
362
- if (i === r.length - 1) r.push(1) // ω^k·(bound+1) → ω^(k+1)
363
- else r[i + 1] = (r[i + 1] || 0) + 1 // … → ω^(i+1)·(+1)
364
- // keep scanning: the bumped slot may carry in turn
365
- }
366
- while (r.length > 1 && r[r.length - 1] === 0) r.pop()
367
- if (r.length === 0) r = [1]
368
- return r
369
- }
370
-
371
- function getOrdinalLetter(ordRows) {
372
- if (!ordRows || ordRows.length === 0) return null
373
-
374
- // Check if all rows are 2-element [count, value] format (ω-level operations)
375
- let allTwoElement = true
376
- for (let i = 0; i < ordRows.length; i++) {
377
- if (ordRows[i].length !== 2) { allTwoElement = false; break }
378
- }
379
- if (allTwoElement) {
380
- return "Aa" // Base ω-level letter; value is handled in formatOrdinal
381
- }
382
-
383
- let tokens = []
384
- // Process rows in REVERSE order (matching toString behavior)
385
- for (let i = ordRows.length - 1; i >= 0; i--) {
386
- let row = ordRows[i]
387
- if (row.length < 2) continue
388
- let diag = row[row.length - 1]
389
- let vals = row.slice(1, row.length - 1)
390
- let count = row[0] || 1
391
-
392
- // Build letter name (reverse order: last val first, matching toString)
393
- let letter = String.fromCharCode(64 + diag)
394
- for (let j = vals.length - 1; j >= 0; j--) {
395
- letter += String.fromCharCode(97 + vals[j])
396
- }
397
-
398
- for (let c = 0; c < count; c++) {
399
- tokens.push(letter)
400
- }
401
- }
402
-
403
- // Do NOT sort - rows are already in canonical order from normalize
404
- return tokens.join("")
405
- }
406
-
407
- // ─── Reference Polarize (verbatim port of PowiainaNum's myPolarize) ──
408
- // Recovers the display α ("bottom") and the diagonal level ("arrows") of an
409
- // r0 chain STRUCTURALLY, climbing log10 level by level — the only method that
410
- // stays exact at high levels where the engine's fractional-arg bisect
411
- // quantizes (level ≥ 20). Ground truth: format-powiainanum.js. Their array
412
- // [base, [level, count, 1, 1], …] maps to our r0 = [base, cnt1, cnt2, …].
413
- function refPolarizeArraySort(array) {
414
- array.sort(function (a, b) {
415
- if (typeof a == 'number') return
416
- else if (a[3] > b[3]) return -1
417
- else if (a[3] < b[3]) return 1
418
- else if (a[2] == 'x' && b[2] != 'x') return -1
419
- else if (a[2] != 'x' && b[2] == 'x') return 1
420
- else if (a[2] == 'x' && b[2] == 'x') return -1
421
- else if (a[2] > b[2]) return -1
422
- else if (a[2] < b[2]) return 1
423
- else if (a[0] == 'x' && b[0] != 'x') return -1
424
- else if (a[0] != 'x' && b[0] == 'x') return 1
425
- else if (a[0] == 'x' && b[0] == 'x') return -1
426
- else if (a[0] > b[0]) return -1
427
- else if (a[0] < b[0]) return 1
428
- else if (a[1] > b[1]) return -1
429
- else if (a[1] < b[1]) return 1
430
- return -1
431
- })
432
- }
433
- function refPolarizeArrayMerge(array) {
434
- let elemOffset = 0
435
- for (let i = 0; i < array.length - 2; ++i) {
436
- if (array[i][0] == array[i + 1][0] &&
437
- array[i][2] == array[i + 1][2] &&
438
- array[i][3] == array[i + 1][3]) {
439
- array[i][1] += array[i + 1][1]
440
- array.splice(i + 1, 1)
441
- --i
442
- elemOffset++
443
- }
444
- }
445
- return elemOffset
446
- }
447
- // our r0 + [count, level] finite rows → their [base, [level, count, 1, 1]...]
448
- // (their row level = our level verbatim: their 3{21}3 rows top at [20,1] and their polarize
449
- // returns arrows 20, displayed "…20" — no off-by-one)
450
- function refPolarizeInput(r0, finiteRows) {
451
- let arr = [r0[0]]
452
- for (let i = 1; i < r0.length; i++) {
453
- if (r0[i] > 0) arr.push([i, r0[i], 1, 1])
454
- }
455
- if (finiteRows) {
456
- for (let i = 0; i < finiteRows.length; i++) {
457
- let fr = finiteRows[i]
458
- if (fr && fr.length === 2 && fr[0] > 0) arr.push([fr[1], fr[0], 1, 1])
459
- }
460
- }
461
- return arr
462
- }
463
- function refPolarize(array, hasOperationRepeat = true) {
464
- refPolarizeArraySort(array)
465
- refPolarizeArrayMerge(array)
466
- let ptr = array.length - 2
467
- let b = () => array[array.length - 1]
468
- let c = (x) => { array[array.length - 1] = x }
469
- let repeatResult = 1000001
470
- while (--repeatResult >= 0) {
471
- if (b() >= 10) {
472
- let a = Math.log10(b())
473
- array.push([1, 1, 1, 1])
474
- ptr++
475
- refPolarizeArraySort(array)
476
- let offset = refPolarizeArrayMerge(array)
477
- ptr -= offset
478
- c(a)
479
- } else {
480
- if (ptr == 0 && typeof array[ptr + 1] == 'number' &&
481
- (hasOperationRepeat || (!hasOperationRepeat && array[ptr][1] == 1))) break
482
- if (ptr != 0 && typeof array[ptr + 1] == 'number' && typeof array[ptr][0] == 'number' &&
483
- array[ptr][1] == 1 &&
484
- (array[ptr - 1][0] == 'x' || array[ptr - 1][2] > array[ptr][2] || array[ptr - 1][3] > array[ptr][3]) &&
485
- array[ptr][0] > 2 && (ptr != 0 || array[ptr - 1][0] == 'x')) {
486
- let arrow_count = array[ptr][0]
487
- let base = b()
488
- let Jx
489
- if (arrow_count == 3) Jx = base
490
- else Jx = arrow_count - 1 + Math.log(base / 2) / Math.log(5)
491
- array[ptr][0] = 'x'
492
- c(Jx)
493
- refPolarizeArraySort(array)
494
- let offset = refPolarizeArrayMerge(array)
495
- ptr -= offset
496
- }
497
- if (typeof array[ptr + 1] == 'number' && array[ptr][0] == 'x' && b() < 10 && ptr != 0) {
498
- let base = b()
499
- let JRepeation = array[ptr][1]
500
- let Kx = JRepeation + Math.log10(base)
501
- array[ptr][1] = 1
502
- array[ptr][0] = 1
503
- array[ptr][2]++
504
- c(Kx)
505
- refPolarizeArraySort(array)
506
- let offset = refPolarizeArrayMerge(array)
507
- ptr -= offset
508
- }
509
- if (((ptr == 0 && !hasOperationRepeat && array[ptr][1] != 1) || ptr != 0) &&
510
- array[ptr][0] != 'x' && b() < 10) {
511
- if (b() == 1 && ptr > 0 && array[ptr - 1][0] > array[ptr][0] && array[ptr][1] == 1) {
512
- array[ptr][0] = array[ptr - 1][0]
513
- } else {
514
- let right = array[ptr][1] + Math.log10(b())
515
- array[ptr][0]++
516
- array[ptr][1] = 1
517
- c(right)
518
- }
519
- refPolarizeArraySort(array)
520
- let offset = refPolarizeArrayMerge(array)
521
- ptr -= offset
522
- }
523
- }
524
- }
525
- return {
526
- bottom: b(),
527
- repeation: array[ptr][1],
528
- arrows: array[ptr][0],
529
- }
530
- }
531
- // Convert a finite-chain polarize triple (bottom, repeation, arrows) into the
532
- // diagonal-letter display pair (mantissa, β). The value behaves as
533
- // 10{arrows+1}(t), t = log10(bottom)+repeation; the diagonal convention is
534
- // α = 2·5^f ∈ [2,10):
535
- // t ∈ [2,10) -> mantissa t, β = arrows (3{100}3 -> 2.376Aa99)
536
- // t ≥ 10 -> one level per smooth-log step f → 1+log10(f); the anchor
537
- // t=10 is mantissa 2 at β=arrows+1 (10{100}10 -> 2.000Aa100)
538
- // t ∈ [1,2) -> mantissa 2·5^(t-1), β = arrows-1
539
- // Truncation marker: a truncated cascade resets r0 to [10] and bumps the
540
- // lowest kept row's count by 1 over the uniform fill (xCnt) — read it as xCnt
541
- // so truncated displays match the untruncated anchor.
542
- function normalizedFiniteRows(r0, finiteRows) {
543
- if (!finiteRows || finiteRows.length === 0 || r0[0] !== 10) return finiteRows
544
- let sorted = finiteRows.slice().sort((a, b) => a[1] - b[1])
545
- let c0 = sorted[0][0] || 0
546
- let c1 = sorted.length > 1 ? (sorted[1][0] || 0) : 0
547
- if (c0 === c1 + 1) {
548
- let copy = finiteRows.slice()
549
- for (let i = 0; i < copy.length; i++) {
550
- if (copy[i][1] === sorted[0][1]) copy[i] = [c1, copy[i][1]]
551
- }
552
- return copy
553
- }
554
- return finiteRows
555
- }
556
-
557
- function aaDiagonalPair(pol) {
558
- let t = Math.log10(pol.bottom) + pol.repeation
559
- let beta = pol.arrows
560
- // discrete integer argument (10{arrows+1}(t) with integer t): climb the
561
- // raw count C=t-1 at level arrows; C ≤ 9 is the anchor band (one smooth
562
- // application 10{arrows+1}2 … through arg 9) -> mantissa 2 at β=arrows+1
563
- let discrete = Math.abs(pol.bottom - 1) < 1e-12 && pol.repeation === Math.floor(pol.repeation)
564
- if (discrete && t - 1 <= 9 + 1e-9 && t >= 2) {
565
- return { mant: 2, beta: pol.arrows + 1 }
566
- }
567
- if (t >= 9.999999999) {
568
- // v = 10{arrows+1}(t) = {arrows}^{t-1}(10): the raw level-(arrows)
569
- // application count is (t-1); run the geometric smooth-log climb
570
- // from a scalar count all the way to the diagonal band at
571
- // β = arrows+1. Integer arguments far below the next anchor land at
572
- // mantissa 2.000 (10{100}10 … 10{100}100 are all 2.000Aa100).
573
- let n = pol.arrows
574
- let s = Math.log10(Math.max(t - 1, 1))
575
- for (let level = 1; level < n + 2; level++) {
576
- s = (s >= 9.999999999) ? 2 : 1 + Math.log10(s)
577
- }
578
- let mant = s < 2 ? 1 + s : s
579
- return { mant: Math.min(mant, 10), beta: n + 1 }
580
- }
581
- if (t < 2) return { mant: 2 * Math.pow(5, t - 1), beta: beta - 1 }
582
- // t in [2,10): genuinely smooth (fractional compact row, or a non-10 base
583
- // fixed point such as 3{100}3 -> 2.376) is shown directly; the discrete
584
- // integer-argument anchor case was handled at the top of the function.
585
- return { mant: t, beta: beta }
586
- }
587
-
588
- // Structural α/diagonal recovery for a value whose finite-level chain (r0
589
- // cols + [count, level] rows) reaches the Aa diagonal region. Mirrors the
590
- // reference convention: 3{24}3 → bottom 2.375812, arrows 23 (the "2.376Aa23"
591
- // display); 3{100}3 → bottom 2.375812, arrows 99 ("Aa2.376Aa99" inner part).
592
- function polarizeFiniteChain(r0, finiteRows) {
593
- try {
594
- finiteRows = normalizedFiniteRows(r0, finiteRows)
595
- let arr = refPolarizeInput(r0.slice(0), finiteRows)
596
- if (arr.length === 1) return null
597
- return refPolarize(arr, true)
598
- } catch (e) {
599
- return null
600
- }
601
- }
602
-
603
- // ─── Main Format Function ────────────────────────────────────────
604
-
605
- // Parse an already-formatted r0 argument back to a number (e.g. "1,000"
606
- // → 1000, "1.000E1,000" → null: carries its own E structure)
607
- function formatR0ArgStr(argStr) {
608
- var s = String(argStr).replace(/,/g, "")
609
- if (/^\d+(\.\d+)?$/.test(s)) return Number(s)
610
- return null
611
- }
612
-
613
- // De-layered !Aa x instance (decision 1B): the shape [[x],[1,0×k,1]] with
614
- // k = max(1, floor(x)), x >= 1. Per the README the display is the APPROXIMATE
615
- // binary form !α'Aa'β' (β' = floor(x), α' = 2·5^(x−β') ∈ [2,10)) — the
616
- // mantissa carries only FORMAT_OPTIONS digits, so the round-trip recovers x
617
- // to that precision (issue #20: tolerance-based assertion). An INTEGER x has
618
- // α' = 2 exactly, and the binary spelling now denotes the ω^n diagonal
619
- // cascade (issue #19), so it shows the exact letter token A(a×k)x instead.
620
- // Returns null for every other shape (x < 2 included — the no-"!" binary form
621
- // comes from formatOrdinal).
622
- function formatBangAaValue(num, precision) {
623
- if (num.sign !== 1 || num.layer !== 0) return null
624
- let a = num.array
625
- if (a.length !== 2 || a[0].length !== 1) return null
626
- let x = a[0][0]
627
- if (typeof x !== 'number' || !isFinite(x) || x < 2) return null
628
- let row = a[1]
629
- if (row.length < 3 || row[0] !== 1 || row[row.length - 1] !== 1) return null
630
- for (let i = 1; i < row.length - 1; i++) if (row[i] !== 0) return null
631
- let k = row.length - 2
632
- if (k !== Math.max(1, Math.floor(x))) return null
633
- if (x === Math.floor(x)) {
634
- // integer anchor: the letter token A(a×k)x is the exact spelling
635
- return "A" + "a".repeat(k) + formatR0Arg(x, precision)
636
- }
637
- let beta = Math.floor(x)
638
- let mant = 2 * Math.pow(5, x - beta)
639
- return "!" + regularFormat(mant, precision) + "Aa" + formatR0Arg(beta, precision)
640
- }
641
-
642
- // The full rule-3 cascade of 10{ω^n}10 (n ≥ 2) — the stored form of !Aa<n>
643
- // (issue #19: "!" adds one ω^, so !Aa3 = 10{ω^3}10). A cheap shape pre-filter
644
- // (base [10], full row budget, top row [8, 9×n]) plus an exact comparison
645
- // against the engine's own cascade, so nothing else matches. Displayed as the
646
- // binary diagonal !2.000Aa<n>, which parses back to the same cascade.
647
- function formatAaCascade(num, precision) {
648
- if (num.sign !== 1 || num.layer !== 0) return null
649
- let a = num.array
650
- if (a.length !== MetaNum.maxRows || a.length < 3) return null
651
- if (a[0].length !== 1 || a[0][0] !== 10) return null
652
- let last = a[a.length - 1]
653
- let n = last.length - 1
654
- if (n < 2 || last[0] !== 8) return null
655
- for (let i = 1; i < last.length; i++) if (last[i] !== 9) return null
656
- let coeffs = []
657
- for (let i = 0; i < n; i++) coeffs.push(0)
658
- coeffs.push(1)
659
- let ref = MetaNum._hyperopFromOrdinalRaw(MetaNum.TEN, MetaNum.TEN, coeffs)
660
- if (!ref.eq(num)) return null
661
- return "!" + regularFormat(2, precision) + "Aa" + formatR0Arg(n, precision)
662
- }
663
-
664
- function format(num, precision=3, small=false) {
665
- if (MetaNum.isNaN(num)) return "NaN"
666
- let sciSigDigits = FORMAT_OPTIONS.sciSignificantDigits // for E notation
667
- let sciPrecision = Math.max(sciSigDigits, precision)
668
- let singlePrecision = FORMAT_OPTIONS.singleLetterDigits // for F, G, H, ...
669
- let multiPrecision = FORMAT_OPTIONS.multiLetterDigits // for Aa and beyond
670
- num = new MetaNum(num)
671
- let array = num.array
672
- let r0 = array[0]
673
-
674
- // Basic edge cases
675
- if (num.sign !== 2 && num.sign !== -2 && num.abs().lt(1e-308)) return (0).toFixed(precision)
676
- if (num.sign < 0) return "-" + format(num.neg(), precision, small)
677
- if (num.isInfinite()) return "Infinity"
678
-
679
- // Sub-unit values (sign 2 / -2, 0 < |v| < 1): a plain finite r0 stores the
680
- // RECIPROCAL, so the real value is 1/r0 — format that number (decimals at
681
- // or above 10^-smallNotationThreshold, αE-β below). Reading the raw r0
682
- // printed the reciprocal (MetaNum(1).div(2000) → "2.000E-3"). Structured
683
- // sign-2 forms keep the letter-law path below.
684
- if ((num.sign === 2 || num.sign === -2) && num.layer === 0 &&
685
- num.array.length === 1 && num.array[0].length === 1 &&
686
- isFinite(num.array[0][0]) && num.array[0][0] !== 0) {
687
- let realVal = 1 / num.array[0][0]
688
- if (isFinite(realVal) && realVal > 0) {
689
- let asNormal = num.clone()
690
- asNormal.sign = 1
691
- asNormal.array = [[realVal]]
692
- num = asNormal
693
- }
694
- }
695
-
696
- // Small value handling (e.g., 0.0000000001 → 1.000E-10 or 1.000E10⁻¹)
697
- let smallThreshold = Math.pow(10, -FORMAT_OPTIONS.smallNotationThreshold)
698
- if (num.lt(smallThreshold)) {
699
- if (FORMAT_OPTIONS.smallNotationUseE) {
700
- // Handle reciprocal values (sign=2/-2) that underflow to 0 in double precision
701
- if (num.sign === 2 || num.sign === -2) {
702
- var recipFmt = num.clone()
703
- recipFmt.sign = recipFmt.sign === 2 ? 1 : -1
704
- var prefix = num.sign === -2 ? "-" : ""
705
- // Compute magnitude (log10 of reciprocal)
706
- var mag = recipFmt.log10()
707
- // Tier 1: mag is a simple number → αE-β format
708
- if (mag.array.length === 1 && mag.array[0].length <= 2) {
709
- var magNum = mag.toNumber()
710
- if (isFinite(magNum) && magNum > 0) {
711
- var frac = magNum - Math.floor(magNum)
712
- var mant = Math.pow(10, frac)
713
- var expPart = Math.floor(magNum)
714
- if (mant < 1) { mant *= 10; expPart -= 1 }
715
- if (mant >= 9.999999999999999) { mant = 1; expPart += 1 }
716
- return prefix + regularFormat(mant, sciMantissaPrecision(expPart)) + "E-" + commaFormat(expPart)
717
- }
718
- }
719
- // Tier 2: mag is large → "E-" + the letter-law form of mag
720
- // (= log10 of the reciprocal base). A chain of n same-level
721
- // ops collapses to ONE next-level op with arg+n, so log10
722
- // shifts only the OUTERMOST letter (EE1000 → E1000, F500 →
723
- // F499, G200 → G200). Roundtrip exact: "E-1.000G200" parses
724
- // back to 1/G200.
725
- var recipStr = format(recipFmt, precision, small)
726
- var magStr = recipStr
727
- // leading run of E letters (e.g. "EE1.000E1,000"): strip one E
728
- var eRun = recipStr.match(/^(E+)(.*)$/)
729
- var rm = recipStr.match(/^(\d(?:\.\d+)?)([A-Z])((?:\d[\d,]*)?)$/)
730
- if (eRun && !rm) {
731
- var restStr = eRun[2]
732
- if (eRun[1].length >= 2) {
733
- // "EE…" → "E…" (log10 of an E-chain drops one E)
734
- magStr = eRun[1].slice(0, -1) + restStr
735
- } else if (eRun[1].length === 1) {
736
- // single "EαEβ" / "Eβ": log10 is the β part
737
- var betaPart = restStr.replace(/^\d(?:\.\d+)?(?=[A-Z])/, "")
738
- if (/^[A-Z]/.test(betaPart) || /^[\d,]/.test(betaPart)) magStr = betaPart
739
- }
740
- } else if (rm) {
741
- var rAlpha = rm[1], rLetter = rm[2], rArg = rm[3]
742
- if (rLetter === "E" && rArg !== "") {
743
- // E-chain with numeric arg (E200): log10 keeps E-arg
744
- magStr = rAlpha + "E" + rArg
745
- } else if (rLetter === "F" && rArg !== "") {
746
- // F-chain: arg −1
747
- magStr = rAlpha + "F" + commaFormat(Math.max(0, Number(rArg.replace(/,/g, "")) - 1))
748
- }
749
- // G and above: display unchanged
750
- }
751
- return prefix + "E-" + magStr
752
- }
753
- // Format as aE-b (e.g., 0.0000000001 → 1.000E-10)
754
- let nVal = num.toNumber()
755
- if (nVal > 0 && isFinite(nVal)) {
756
- let logVal = Math.log10(nVal)
757
- let m = Math.pow(10, logVal - Math.floor(logVal))
758
- let e = Math.abs(Math.floor(logVal))
759
- // Normalize: ensure m in [1, 10)
760
- if (m < 1) { m *= 10; e -= 1 }
761
- if (m >= 9.999999999999999) { m = 1; e += 1 }
762
- return regularFormat(m, sciMantissaPrecision(e)) + "E-" + commaFormat(e)
763
- }
764
- // Fallback for non-simple values: use ⁻¹ notation
765
- if (num.layer === 0 && num.array.length === 1 && num.array[0].length === 1) {
766
- var val = num.array[0][0]
767
- if (val > 0) {
768
- var recipVal = 1 / val
769
- if (isFinite(recipVal)) {
770
- return format(new MetaNum(recipVal), precision, small) + "⁻¹"
771
- }
772
- }
773
- }
774
- return format(num.rec(), precision, small) + "⁻¹"
775
- } else {
776
- // Traditional ⁻¹ notation
777
- if (num.sign === 2 || num.sign === -2) {
778
- // Already in small representation (sign=2), toggle sign to get reciprocal
779
- var recipSmall = num.clone()
780
- recipSmall.sign = recipSmall.sign === 2 ? 1 : -1
781
- return format(recipSmall, precision, small) + "⁻¹"
782
- }
783
- // Normal representation but value < 1 (e.g., 0.0000000001 stored as [[1e-10]])
784
- // Compute reciprocal properly: 1/val
785
- if (num.layer === 0 && num.array.length === 1 && num.array[0].length === 1) {
786
- var val = num.array[0][0]
787
- if (val > 0) {
788
- var recipVal = 1 / val
789
- if (isFinite(recipVal)) {
790
- return format(new MetaNum(recipVal), precision, small) + "⁻¹"
791
- }
792
- }
793
- }
794
- // Fallback
795
- return format(num.rec(), precision, small) + "⁻¹"
796
- }
797
- }
798
-
799
- if (num.lt(1)) return regularFormat(num, FORMAT_OPTIONS.decimalPlaces + (small ? 2 : 0))
800
- if (num.lt(1000)) return regularFormat(num, FORMAT_OPTIONS.decimalPlaces)
801
-
802
- // Check decimal threshold: if value >= 10^decimalThreshold, don't show decimals
803
- let useDecimals = true
804
- if (FORMAT_OPTIONS.decimalThreshold > 0) {
805
- let thresholdVal = Math.pow(10, FORMAT_OPTIONS.decimalThreshold)
806
- if (num.gte(thresholdVal)) useDecimals = false
807
- }
808
-
809
- if (num.lt(Math.pow(10, FORMAT_OPTIONS.sciThreshold))) {
810
- if (useDecimals) return regularFormat(num, FORMAT_OPTIONS.decimalPlaces)
811
- else return commaFormat(num)
812
- }
813
-
814
- // ── Handle layer > 0 (symbol notation: !, @, #, ..., ε) ──
815
- if (num.layer > 0) {
816
- return formatLayer(num, precision, sciPrecision, singlePrecision, multiPrecision)
817
- }
818
-
819
- // ── Handle ordinal rows (Aa, Ab, ..., Aaa, ... range) ──
820
- let hasOrdinalRows = array.length > 1
821
- if (hasOrdinalRows) {
822
- let bang = formatBangAaValue(num, multiPrecision)
823
- if (bang !== null) return bang
824
- // issue #19: the full 10{ω^n}10 cascade (stored !Aa<n>) — display the
825
- // binary diagonal so the parser round-trips it
826
- let cascade = formatAaCascade(num, multiPrecision)
827
- if (cascade !== null) return cascade
828
- return formatOrdinal(num, precision, multiPrecision)
829
- }
830
-
831
- // ── r0-only: scientific notation, E-Z range ──
832
- let maxLevel = 0
833
- for (let i = 1; i < r0.length; i++) {
834
- if (r0[i] > 0) maxLevel = i
835
- }
836
-
837
- // ── Handle r0-only with maxLevel >= 23: Aa-diagonal (v2.0) ──
838
- // The cascade collapses to αAaβ with (bottom, repeation, arrows) from
839
- // polarizeFiniteChain (the structural climb), mantissa normalized into
840
- // [1,10) carrying decades into β — identical to the finite-row display
841
- // so format stays cross-config stable.
842
- if (maxLevel >= 23) {
843
- let pol = polarizeFiniteChain(r0.slice(0), null)
844
- if (pol && isFinite(pol.bottom) && pol.bottom > 0 && isFinite(pol.arrows)) {
845
- let pair = aaDiagonalPair(pol)
846
- return regularFormat(pair.mant, multiPrecision) + "Aa" + commaFormat(pair.beta)
847
- }
848
- // fallback: legacy base-9 coefficient form
849
- let coeff = r0[maxLevel]
850
- let pow9 = 9
851
- for (let i = maxLevel - 1; i >= 1; i--) {
852
- coeff += (r0[i] || 0) / pow9
853
- pow9 *= 9
854
- }
855
- let level = maxLevel
856
- while (coeff >= 9) {
857
- coeff /= 9
858
- level++
859
- }
860
- // Format coefficient: if close to integer, show as integer
861
- let coeffVal
862
- if (Math.abs(coeff - Math.round(coeff)) < 1e-12 && Math.round(coeff) <= Number.MAX_SAFE_INTEGER) {
863
- coeffVal = Math.round(coeff)
864
- } else {
865
- coeffVal = coeff
866
- }
867
- return regularFormat(coeffVal, multiPrecision) + "Aa" + commaFormat(level)
868
- }
869
-
870
- // ── All other r0-only cases: use the recursive chain builder ──
871
- // This handles plain numbers, E-level, F-level, ..., Z-level (maxLevel 0-22)
872
- // including multi-letter chains like GE700, FE400, GF800, GG900.
873
- return formatR0AsChain(r0.slice(0), sciPrecision)
874
- }
875
-
876
- // ─── Format with Layer (symbol notation) ─────────────────────────
877
-
878
- function formatLayer(num, precision, precision2, precision3, precision4) {
879
- let sym = symbolName(num.layer)
880
-
881
- // Create a layer-down version for the inner format
882
- let inner = num.clone()
883
- inner.layer = 0
884
- inner.normalize()
885
-
886
- // Check if inner de-layered to a "!Aa-like" form (all a's in ordinal)
887
- // If the ordinal row is [count, 0, 0, ..., 0, diag] and r0[0] equals the number of zeros,
888
- // we can format compactly as !Aa[r0[0]] (per README: !Aaα = (10^frac(α),0,...,0)|10 with int(α) zeros)
889
- let canCompact = false
890
- let compactBase = 0
891
- if (inner.array.length > 1) {
892
- let lastRow = inner.array[inner.array.length - 1]
893
- let diag = lastRow[lastRow.length - 1]
894
- let vals = lastRow.slice(1, lastRow.length - 1)
895
- let allZero = vals.every(v => v === 0)
896
- let base = inner.array[0][0]
897
- // Compact form only applies when diag=1 (A), all vals are 0, and r0[0] equals the number of zeros
898
- if (allZero && inner.array[0].length === 1 && diag === 1 && base === vals.length) {
899
- canCompact = true
900
- compactBase = base
901
- }
902
- }
903
-
904
- // For layers beyond the explicit symbols, use the ε format: αεβ
905
- // ε represents exponent tower layers of ω: αεβ ~ f_ω^ω^...^ω(β ω's)_(α)
906
- // This check must come before the compact !Aa form, otherwise ε layers
907
- // get mis-rendered as "Aa..." (e.g. 1ε500 → "1.000Aa10")
908
- if (num.layer > SYMBOLS.length) {
909
- let epsPrecision = FORMAT_OPTIONS.epsilonSignificantDigits | 0
910
- if (canCompact && compactBase >= 2 && Math.floor(compactBase) === compactBase) {
911
- // Compact Aa form at ε layers folds into one more ε level:
912
- // layer n + Aa-form ≡ ε(n+1) with mantissa 10^frac(compactBase)
913
- let bottom = Math.pow(10, compactBase - Math.floor(compactBase))
914
- return regularFormat(bottom, epsPrecision) + "ε" + commaFormat(num.layer + 1)
915
- }
916
- let innerStr = format(inner, epsPrecision, false)
917
- return innerStr + "ε" + commaFormat(num.layer)
918
- }
919
-
920
- // issue #19: the 10{ω^n}10 cascade at a symbol layer — the stored form of
921
- // @Aa<n> (layer 1), #Aa<n> (layer 2), … ONE symbol per value: the symbol
922
- // index is the total ω^-layer count (layer 0 → "!", 1 → "@", 2 → "#"),
923
- // never a stack ("@!…" is invalid). The body is the same binary diagonal
924
- // the layer-0 form uses, so the display stays isomorphic to !Aa<n>.
925
- let cascadeStr = formatAaCascade(inner, precision4)
926
- if (cascadeStr !== null) {
927
- let body = cascadeStr.slice(1) // strip the layer-0 "!"
928
- if (num.layer < SYMBOLS.length) return SYMBOLS[num.layer] + body
929
- return body + "ε" + commaFormat(num.layer + 1)
930
- }
931
-
932
- // Compact diagonal: the symbol row [1,0…0,1] with m=compactBase zeros is
933
- // 10{ω^m}10 — a DIAGONAL letter (A + m a's) at argument 10, with the pure
934
- // dlsdl α=2·5^f ∈ [2,10) convention (integer m anchors mantissa 2). For
935
- // layers above ! the symbol of the layer below prefixes the same inner
936
- // form (!Aa3 = 2.000Aaaa10, @Aa3 = !2.000Aaaa10); past multiLetterLimit the
937
- // Aa argument takes over the exponent (10{ω^10}10 → !2.000Aa10).
938
- if (canCompact && compactBase >= 2) {
939
- let mInt = Math.floor(compactBase)
940
- let frac = compactBase - mInt
941
- let mant = 2 * Math.pow(5, frac)
942
- // #28: past multiLetterLimit the old single-letter carry (!1.000N10)
943
- // did not round-trip — it added a layer and could not name the exact
944
- // diagonal. Keep the exact A(a×m)10 token while the string stays
945
- // reasonable; only fall back to the carry past a hard safety cap.
946
- if (mInt <= MULTI_TOKEN_CAP) {
947
- // Stored layer L: exactly ONE symbol per ω^ layer (symbolName(L));
948
- // stacking symbols ("@!…") is invalid (issue #19). The body is
949
- // the diagonal letter A(a×m)10 at the smooth mantissa. (Layers
950
- // past the symbol list already returned through the ε branch.)
951
- return symbolName(num.layer) + regularFormat(mant, precision4) +
952
- "A" + "a".repeat(mInt) + "10"
953
- }
954
- // Hard-cap fallback: keep the argument (10 for a compact diagonal) but
955
- // the level is the historical single-letter carry approximation.
956
- let total = num.layer + 1
957
- let body = regularFormat(1, precision4) + letterName(mInt) +
958
- formatR0Arg(10, precision4)
959
- if (total <= SYMBOLS.length) return SYMBOLS[total - 1] + body
960
- return body + "ε" + commaFormat(total)
961
- }
962
-
963
- // For !, @, #, $, %, &, ~, <, >, ? symbols: prefix the symbol. When the
964
- // inner display itself had to carry (its letter exceeded multiLetterLimit)
965
- // the symbols stack instead of doubling: layer 1 + inner "!…" → "@…".
966
- let innerStr = format(inner, precision, false)
967
- if (innerStr.length > 1 && SYMBOLS.indexOf(innerStr[0]) >= 0) {
968
- let total = num.layer + 1
969
- if (total <= SYMBOLS.length) return SYMBOLS[total - 1] + innerStr.slice(1)
970
- return innerStr.slice(1) + "ε" + commaFormat(total)
971
- }
972
- return sym + innerStr
973
- }
974
-
975
- // ─── Option-driven mantissa precisions ───────────────────────────
976
- // Decimal places of the mantissa α in an αEβ form: sciSignificantDigits, but
977
- // once the exponent β reaches 10^sciDecimalThreshold only the integer part of
978
- // α is shown (the low digits carry no information at that height).
979
- function sciMantissaPrecision(exponent) {
980
- let t = FORMAT_OPTIONS.sciDecimalThreshold | 0
981
- if (t > 0 && isFinite(exponent) && exponent >= Math.pow(10, t)) return 0
982
- return FORMAT_OPTIONS.sciSignificantDigits | 0
983
- }
984
- // Decimal places of the mantissa α in αΓβ: E → sciSignificantDigits,
985
- // F..Z → singleLetterDigits, Aa and beyond → multiLetterDigits.
986
- function letterMantissaPrecision(level) {
987
- if (level <= 1) return FORMAT_OPTIONS.sciSignificantDigits | 0
988
- if (level <= 22) return FORMAT_OPTIONS.singleLetterDigits | 0
989
- return FORMAT_OPTIONS.multiLetterDigits | 0
990
- }
991
-
992
- // ─── Format r0 Argument (plain number) ───────────────────────────
993
- // Formats a plain numeric argument as either a plain number or αEβ notation.
994
- // The mantissa α is always shown (even when 1.000).
995
- function formatR0Arg(value, precision) {
996
- if (!isFinite(value) || isNaN(value)) return "NaN"
997
- if (value < Math.pow(10, FORMAT_OPTIONS.sciThreshold)) {
998
- // Small argument: use comma format (integer, no decimals)
999
- return commaFormat(value)
1000
- }
1001
- let logVal = Math.log10(value)
1002
- let m = Math.pow(10, logVal - Math.floor(logVal))
1003
- let e = Math.floor(logVal)
1004
- // Normalize mantissa into [1, 10)
1005
- if (m < 1) { m *= 10; e -= 1 }
1006
- if (m >= 9.999999999999999) { m = 1; e += 1 }
1007
- // Always show mantissa (αEβ format, e.g. 1.000E700)
1008
- return regularFormat(m, sciMantissaPrecision(e)) + "E" + commaFormat(e)
1009
- }
1010
-
1011
- // ─── Gamma-Arg Recovery ─────────────────────────────────────────
1012
- // Recover the real argument x with 10{level}x = v (the Γ-canonical argument of
1013
- // v at letter `level`) by bisection on the engine's smooth arrow curve. null
1014
- // when x exceeds the double-precision bisect range; the doubling guard runs to
1015
- // 200 (hardy(1120)'s F-arg ≈ 4.4e13 needs ~45 doublings).
1016
- function gammaArgOf(v, level, iters) {
1017
- if (iters === undefined) iters = 60
1018
- let G = function (x) { return MetaNum(10).arrow(level)(x) }
1019
- // v must sit inside [Γ(1), Γ(HUGE)]: find integer hi with Γ(hi) >= v
1020
- let lo = 1, hi = 2
1021
- let guard = 0
1022
- while (G(hi).lt(v)) {
1023
- lo = hi
1024
- hi *= 2
1025
- if (++guard > 200) return null
1026
- }
1027
- // bisect the fractional part
1028
- for (let i = 0; i < iters; i++) {
1029
- let mid = (lo + hi) / 2
1030
- if (G(mid).lt(v)) lo = mid; else hi = mid
1031
- if (hi - lo < 1e-12) break
1032
- }
1033
- return lo
1034
- }
1035
-
1036
- // Format a recovered Γ-argument x as the binary form αΓβ:
1037
- // α = 10^frac(x) (in [1, 10)), β = floor(x) (may itself carry E notation).
1038
- // Once β ≥ 10^sciThreshold the α only perturbs β by log10(α) < 1, far below
1039
- // the displayed precision: write the letter bare and let the canonical β
1040
- // carry the single α (hardy(1120) → "F4.398E13").
1041
- function formatGammaBinary(x, level, precision) {
1042
- let sciBound = Math.pow(10, FORMAT_OPTIONS.sciThreshold)
1043
- let beta = Math.floor(x + 1e-12)
1044
- let frac = x - beta
1045
- if (frac < 0) { frac += 1; beta -= 1 }
1046
- if (frac >= 1) { frac -= 1; beta += 1 }
1047
- if (beta >= sciBound) {
1048
- let alpha = Math.pow(10, frac)
1049
- return letterName(level) + formatR0Arg(beta + Math.log10(alpha), precision)
1050
- }
1051
- if (frac < 1e-11 || frac > 1 - 1e-11) {
1052
- // exact integer argument: bare letter + β
1053
- return letterName(level) + formatR0Arg(beta, precision)
1054
- }
1055
- let alpha = Math.pow(10, frac)
1056
- return regularFormat(alpha, letterMantissaPrecision(level)) + letterName(level) + formatR0Arg(beta, precision)
1057
- }
1058
-
1059
- // Distinct letter types in a display string: single-uppercase letters and
1060
- // Aa-style multi-letter tokens, ignoring an E inside a number ("7.626E12"
1061
- // sci notation, not an op) and !/@/# symbol prefixes.
1062
- function distinctLetterTypes(str) {
1063
- let stripped = String(str).replace(/(\d(?:\.\d+)?)E(\d[\d,]*)/g, "$1$2")
1064
- let tokens = stripped.match(/[A-Z][a-z]*/g) || []
1065
- let seen = {}
1066
- let out = []
1067
- for (let i = 0; i < tokens.length; i++) {
1068
- if (!seen[tokens[i]]) { seen[tokens[i]] = true; out.push(tokens[i]) }
1069
- }
1070
- return out
1071
- }
1072
-
1073
- // ─── Format r0 as Chain ────────────────────────────────────────
1074
- // Formats r0 = [base, e, f, g, ...] as a dlsdl chain: outerLetters + α +
1075
- // lastLetter + β, with α = 10^(base-floor(base)) and β = floor(base)
1076
- // (EE200 → "E1.000E200", FE400 → "F1.000E400"). A letter ending in "a" is a
1077
- // diagonal letter (Aa = ω, Ba = ω·2, Aaa = ω², …) and its binary form uses
1078
- // α = 2·5^f ∈ [2,10) — 10{23}10 reads "2.000Aa23", never "1.000Aa23".
1079
- function diagonalMantissa(letter, mantissa) {
1080
- if (letter && letter.charAt(letter.length - 1) === 'a') {
1081
- let f = mantissa - Math.floor(mantissa)
1082
- if (!(f >= 0 && f < 1)) f = 0
1083
- return 2 * Math.pow(5, f)
1084
- }
1085
- let mantVal = Math.pow(10, mantissa - Math.floor(mantissa))
1086
- if (mantVal < 1) mantVal *= 10
1087
- return mantVal
1088
- }
1089
-
1090
- // `used` = how many copies of the letter the caller already emitted: an inner
1091
- // level may only promote to the next letter while the total stays within
1092
- // repeatLetterThreshold, otherwise it saturates (see the noPromote block below).
1093
- function formatR0AsChain(r0, precision, used) {
1094
- if (r0.length === 0) r0 = [0]
1095
- let usedCount = used || 0
1096
-
1097
- // Find maxLevel (highest non-zero index in r0[1..])
1098
- let maxLevel = 0
1099
- for (let i = r0.length - 1; i >= 1; i--) {
1100
- if (r0[i] > 0) { maxLevel = i; break }
1101
- }
1102
-
1103
- if (maxLevel === 0) {
1104
- return formatR0Arg(r0[0], precision)
1105
- }
1106
-
1107
- let count = r0[maxLevel]
1108
- let effThreshold = Math.max(2, FORMAT_OPTIONS.repeatLetterThreshold)
1109
-
1110
- // Detect a descending run of count-1 letters (e.g. the VUTS…G chain that
1111
- // the engine produces for arrow(3,19,3) = 3{19}3). Such a chain is the
1112
- // diagonalized expansion of the top letter applied twice, so it must be
1113
- // compressed to the ΓαΓβ binary form instead of being spelled out.
1114
- let runLen = 0
1115
- if (count === 1) {
1116
- runLen = 1
1117
- while (maxLevel - runLen >= 2 && r0[maxLevel - runLen] === 1) runLen++
1118
- }
1119
-
1120
- // ── ≤2-letter-types rule ──
1121
- // When the full spelling would use MORE than two letter types, spell only
1122
- // the top two levels' letters and compress everything below into the
1123
- // second letter's binary-canonical form "bottom Γ₂ repeation" (the
1124
- // polarize triple; bisect fails there — the arg exceeds double range):
1125
- // 3{9}3 → "L2.376K2", 3{10}3 → "M2.376L2",
1126
- // 4{9}4 → "LLK3.550K3", 5{9}5 → "LLLKK4.669K4".
1127
- // A top count ≥ repeatLetterThreshold+1 carries to the next single letter
1128
- // (6{9}6 → "5.760M5").
1129
- if (maxLevel >= 2 && maxLevel <= 22 && count <= effThreshold) {
1130
- let spellTypes = 0
1131
- for (let s = 2; s <= maxLevel; s++) {
1132
- if ((r0[s] || 0) > 0) spellTypes++
1133
- }
1134
- if (spellTypes > 2) {
1135
- let second = 0
1136
- for (let s = maxLevel - 1; s >= 2; s--) {
1137
- if (r0[s] > 0) { second = s; break }
1138
- }
1139
- if (second >= 2) {
1140
- let c2 = r0[second]
1141
- if (c2 <= effThreshold) {
1142
- let restR0 = r0.slice(0)
1143
- restR0[maxLevel] = 0
1144
- let pol = polarizeFiniteChain(restR0, null)
1145
- if (pol && pol.arrows === second && isFinite(pol.bottom) &&
1146
- pol.bottom >= 1 && isFinite(pol.repeation)) {
1147
- let prefix = letterName(maxLevel).repeat(count) +
1148
- letterName(second).repeat(Math.max(c2 - 1, 0))
1149
- return prefix + regularFormat(pol.bottom, precision) +
1150
- letterName(second) + commaFormat(pol.repeation)
1151
- }
1152
- }
1153
- }
1154
- }
1155
- }
1156
-
1157
- if (count <= effThreshold && runLen <= effThreshold) {
1158
- // Non-collapse: peel off one letter at maxLevel, recurse on inner.
1159
- // Long descending count-1 runs (runLen > threshold) fall through to the
1160
- // Γ-canonical collapse below (2-letter rule: the diagonal
1161
- // chain formats at its bisect-exact letter, not spelled out VUTS…).
1162
- let innerR0 = r0.slice(0)
1163
- innerR0[maxLevel] = count - 1
1164
- if (innerR0[maxLevel] === 0) {
1165
- innerR0 = innerR0.slice(0, maxLevel)
1166
- }
1167
- let innerStr = formatR0AsChain(innerR0, precision, usedCount + 1)
1168
-
1169
- // null = the inner level would need one more copy of the outer letter
1170
- // than repeatLetterThreshold allows (3{3}6 = FFF(E^7.6e12) would spell a
1171
- // fourth F). An inner level propagates it; the OUTERMOST call instead
1172
- // falls through to the Γ-canonical collapse below, which renders the
1173
- // whole value at the next letter by its real argument: "2.045G5".
1174
- if (innerStr !== null) {
1175
- // Check if innerStr already has letters (meaning deeper operations exist)
1176
- let hasLetter = /[A-Z]/.test(innerStr)
1177
-
1178
- if (!hasLetter) {
1179
- // innerStr is a plain number: this is the innermost operation
1180
- // Format: α + letterName(maxLevel) + innerStr
1181
- let base = r0[0]
1182
- let alpha = Math.pow(10, base - Math.floor(base))
1183
- if (alpha < 1) alpha *= 10
1184
- // an E letter's αEβ obeys sciDecimalThreshold: β ≥ 10^n → α
1185
- // keeps only its integer part
1186
- let mantPrec = (maxLevel === 1)
1187
- ? sciMantissaPrecision(Number(String(innerStr).replace(/,/g, '')))
1188
- : letterMantissaPrecision(maxLevel)
1189
- let alphaStr = regularFormat(alpha, mantPrec)
1190
- return alphaStr + letterName(maxLevel) + innerStr
1191
- } else {
1192
- // innerStr already has α and letters: just prepend the outer letter
1193
- return letterName(maxLevel) + innerStr
1194
- }
1195
- }
1196
- if (usedCount > 0) return null
1197
- }
1198
-
1199
- // count > effThreshold and the promotion would exceed repeatLetterThreshold
1200
- // copies of the letter in front of it: signal the caller (the structural
1201
- // spelling is impossible) instead of spelling an extra copy.
1202
- if (usedCount + 1 > effThreshold) {
1203
- return null
1204
- }
1205
-
1206
- // count >= effThreshold: promote to next level (maxLevel + 1)
1207
- // Check for the all-8s pattern: base = 10^10 and every level 1..maxLevel-1 equals 8
1208
- let all8 = (r0[0] === 10000000000)
1209
- for (let i = 1; i < maxLevel && all8; i++) {
1210
- if ((r0[i] || 0) !== 8) all8 = false
1211
- }
1212
-
1213
- // sciThreshold boundary: once the top-level argument reaches 10^sciThreshold
1214
- // the binary form αΓβ = Γ(β+log α) renders the argument in its own canonical
1215
- // (αEβ) form and the outer letter is written bare — α must appear only once,
1216
- // at the innermost value (2-letter rule: "G1.000E12", not "1.000G1.000E12")
1217
- let sciBound = Math.pow(10, FORMAT_OPTIONS.sciThreshold)
1218
-
1219
- if (all8) {
1220
- // all-8s promotion: E^count(10^10) → F(count+2), F^count(F10) → G(count+2), etc.
1221
- let arg = count + 2
1222
- let level = maxLevel + 1
1223
- let letter = letterName(level)
1224
- if (level >= 23) {
1225
- // Promotion into a diagonal letter: the all-8s r0 is the exact
1226
- // diagonal 10{L+1}10 = Aa(L+1), whose dlsdl binary form anchors
1227
- // mantissa 2 (α=2·5^0): 10{23}10 -> "2.000Aa23".
1228
- return regularFormat(2.0, precision) + "Aa" + commaFormat(maxLevel + 1)
1229
- }
1230
- if (arg >= sciBound) {
1231
- // Γ(β) with β ≥ 10^sciThreshold: bare letter + canonical argument
1232
- return letter + formatR0Arg(arg, precision)
1233
- }
1234
- // Format: α + letter + β (always show α)
1235
- let alpha = Math.pow(10, arg - Math.floor(arg))
1236
- if (alpha < 1) alpha *= 10
1237
- let alphaStr = regularFormat(alpha, letterMantissaPrecision(level))
1238
- let betaStr = formatR0Arg(Math.floor(arg), precision)
1239
- return alphaStr + letter + betaStr
1240
- }
1241
-
1242
- // ── Γ-canonical recovery (2-letter rule) ──
1243
- // (a) structural top count < threshold AND inner top < maxLevel: keep
1244
- // the top letter Γᵀ bare and format the inner chain recursively (at
1245
- // most 2 letter types: VαEβ → VαFβ → … → VαVβ, never "VFαEβ").
1246
- // (b) otherwise: collapse to the single letter Γ = the HIGHEST level L
1247
- // whose recovered argument (bisect 10{L}x = v) is ≥ 2, in binary form
1248
- // αΓβ (hardy(4166) → "2.397G5", arrow(3,4.3,3) → "1.285H8").
1249
- // Verified law: n ops of level L on a Γ^{L+1}-structured value collapse to
1250
- // ONE Γ^{L+1} with arg+n (F^4(G(1.3796)) = G(5.3796)).
1251
- let r0Num = new MetaNum({ sign: 1, layer: 0, array: [r0.slice(0)] })
1252
-
1253
- if (count < effThreshold && maxLevel >= 2 && runLen <= effThreshold) {
1254
- // (a) structural top letter: peel ONE op of level maxLevel and format
1255
- // the inner chain recursively (exact even when the argument itself is
1256
- // letter-structured, e.g. arrow(3,4.1,3) = G(F^895-chain) →
1257
- // "G" + format(F^895-chain) = "G1.161G897")
1258
- let innerR0 = r0.slice(0)
1259
- innerR0[maxLevel] = count - 1
1260
- if (innerR0[maxLevel] === 0) {
1261
- innerR0 = innerR0.slice(0, maxLevel)
1262
- }
1263
- let innerStr = formatR0AsChain(innerR0, precision, true)
1264
- let hasLetter = /[A-Z]/.test(innerStr)
1265
- if (!hasLetter) {
1266
- let base = r0[0]
1267
- let alpha = Math.pow(10, base - Math.floor(base))
1268
- if (alpha < 1) alpha *= 10
1269
- return regularFormat(alpha, letterMantissaPrecision(maxLevel)) + letterName(maxLevel) + innerStr
1270
- }
1271
- // inner carries letters: bare outer letter (2-letter rule) — the
1272
- // inner top must be LOWER (descending chain); ascending or same-level
1273
- // chains fall through to collapse
1274
- let innerTop = 0
1275
- for (let it = innerR0.length - 1; it >= 1; it--) {
1276
- if (innerR0[it] > 0) { innerTop = it; break }
1277
- }
1278
- if (innerTop < maxLevel) {
1279
- // ≤2 letter types rule: count the distinct letter types the
1280
- // peeled prefix + innerStr would use. If the inner chain spells a
1281
- // THIRD type, collapse it to the binary form at maxLevel-1 —
1282
- // VαEβ → VαFβ → … → VαVβ, never a mixed "VFαEβ" (arrow(3,9,3) →
1283
- // "L2.376K2": the M..J part collapses into K's arg).
1284
- let topLetter = letterName(maxLevel)
1285
- let innerTypes = distinctLetterTypes(innerStr)
1286
- if (innerTypes.length >= 2
1287
- && innerTypes.indexOf(topLetter) < 0
1288
- && innerTypes.indexOf(letterName(innerTop)) < 0) {
1289
- // inner already uses its own 2 types: cannot keep the structural
1290
- // letter — collapse below
1291
- } else {
1292
- let wouldTypes = {}
1293
- wouldTypes[topLetter] = true
1294
- for (let wt = 0; wt < innerTypes.length; wt++) wouldTypes[innerTypes[wt]] = true
1295
- if (Object.keys(wouldTypes).length <= 2) {
1296
- return letterName(maxLevel) + innerStr
1297
- }
1298
- // 3rd type would appear: collapse the inner chain to the binary
1299
- // form at innerTop — arg recovered on the engine curve when
1300
- // possible (level < 20), else structurally via refPolarize
1301
- let innerNum = new MetaNum({ sign: 1, layer: 0, array: [innerR0.slice(0)] })
1302
- let bx = (innerTop <= 19) ? gammaArgOf(innerNum, innerTop, 40) : null
1303
- if (bx !== null && isFinite(bx) && bx >= 2) {
1304
- return letterName(maxLevel) + formatGammaBinary(bx, innerTop, precision)
1305
- }
1306
- let pol2 = polarizeFiniteChain(innerR0, null)
1307
- if (pol2 && pol2.arrows >= 2 && pol2.arrows <= 22) {
1308
- let aStr = regularFormat(Math.max(pol2.bottom, 1.0001), precision)
1309
- return letterName(maxLevel) + aStr + letterName(pol2.arrows) + commaFormat(pol2.repeation)
1310
- }
1311
- // polarize reached the multi-letter region: Aa-diagonal form
1312
- if (pol2 && pol2.arrows >= 23) {
1313
- let aStr = regularFormat(Math.max(pol2.bottom, 1.0001), precision)
1314
- return letterName(maxLevel) + aStr + "Aa" + commaFormat(pol2.arrows)
1315
- }
1316
- }
1317
- }
1318
- }
1319
-
1320
- // (b) collapse: the structural chain (n repeats of the top letter Γᵀ on an
1321
- // inner value whose canonical letter is Γᵀ⁺¹, e.g. F^895(G(2.06)))
1322
- // compresses to ONE Γᵀ⁺¹ with arg+n — bisect at the structural next letter
1323
- // first (maxLevel+1); if its arg falls below 2, search upward for the
1324
- // highest level whose arg ≥ 2 (hardy(4166) → "2.397G5").
1325
- let structuralNext = Math.min(maxLevel + 1, 22)
1326
- let sx = gammaArgOf(r0Num, structuralNext, 40)
1327
- if (sx !== null && isFinite(sx) && sx >= 2) {
1328
- return formatGammaBinary(sx, structuralNext, precision)
1329
- }
1330
- for (let lv = 22; lv >= 2; lv--) {
1331
- if (lv === structuralNext) continue
1332
- let x = gammaArgOf(r0Num, lv, 40)
1333
- if (x !== null && isFinite(x) && x >= 2) {
1334
- return formatGammaBinary(x, lv, precision)
1335
- }
1336
- }
1337
-
1338
- // Γ-arg not recoverable as a double (arg beyond bisect range): fall back
1339
- // to metaPolarize for the polarized form
1340
- let pol = metaPolarize(r0.slice(0), r0Num)
1341
- let h = pol.height
1342
- let rep = pol.repeat || 1
1343
- let top = pol.top
1344
- let bottom = pol.bottom
1345
-
1346
- if (runLen > effThreshold) {
1347
- // The descending count-1 run is the diagonalized expansion of the top
1348
- // letter applied twice: force the ΓαΓβ form (issues.md: arrow(3,19,3)
1349
- // → "VαVβ", not "VUTS…G…")
1350
- rep = 2
1351
- h = maxLevel
1352
- }
1353
-
1354
- // Convert repeated letters to next level when over threshold
1355
- if (rep > 1 && rep >= effThreshold) {
1356
- let newH = h + 1
1357
- let newTop = rep + 1
1358
- let newLetter = letterName(newH)
1359
- if (newTop >= sciBound) {
1360
- // bare letter + canonical argument (single α at the innermost value)
1361
- return newLetter + formatR0Arg(newTop + Math.log10(bottom < 1 ? Math.pow(10, bottom) : bottom), precision)
1362
- }
1363
- // Format: α + letter + β. Canonical all-8s arrays (from the 10^10
1364
- // base: G600, ZZ10, …) carry no recoverable mantissa below 10^10, so
1365
- // α = 1.000 by construction; every other value recovers its real α by
1366
- // stripping newTop slog's — the residue in [1,10) is exactly the α of
1367
- // αΓβ = Γ(β+log α) (hardy(4150) → "2.300G5").
1368
- let alpha = 1.0
1369
- let all8s = (r0[0] === 10000000000)
1370
- for (let ai = 2; ai < pol.height && all8s; ai++) {
1371
- if ((r0[ai] || 0) !== 8) all8s = false
1372
- }
1373
- if (!all8s) {
1374
- try {
1375
- let av = r0Num.clone()
1376
- for (let si = 0; si < newTop && av.gt(MetaNum(1e15)); si++) av = av.slog()
1377
- if (av.gte(1) && av.lt(10)) alpha = av.toNumber()
1378
- } catch (e) { /* keep α = 1.0 */ }
1379
- }
1380
- let alphaStr = regularFormat(alpha, precision)
1381
- let betaStr = formatR0Arg(newTop, precision)
1382
- return alphaStr + newLetter + betaStr
1383
- }
1384
-
1385
- // Below threshold: use outerLetters + α + lastLetter + β pattern
1386
- if (h <= 22) {
1387
- let letter = letterName(h)
1388
- if (rep > 1) {
1389
- // Repeated letters: outerLetters + α + lastLetter + β
1390
- let outerLetters = letter.repeat(rep - 1)
1391
- let alpha = bottom
1392
- let logAlpha = 0
1393
- if (alpha < 1) {
1394
- logAlpha = alpha
1395
- alpha = Math.pow(10, alpha)
1396
- } else {
1397
- logAlpha = Math.log10(alpha)
1398
- }
1399
- let betaVal = top + logAlpha
1400
- if (top >= sciBound) {
1401
- // bare letters + canonical argument (single α at the innermost value)
1402
- return outerLetters + letter + formatR0Arg(betaVal, precision)
1403
- }
1404
- let alphaStr = regularFormat(alpha, precision)
1405
- let betaStr = formatR0Arg(top, precision)
1406
- return outerLetters + alphaStr + letter + betaStr
1407
- }
1408
- // Single letter: α + letter + β — but once β ≥ 10^sciThreshold the
1409
- // α only perturbs β by log10(α) < 1, far below the displayed
1410
- // precision: write the letter bare and let β carry the single α
1411
- // (issues.md: hardy(1120) → "F4.398E13", not "4.295F4.398E13")
1412
- let alpha = bottom
1413
- if (alpha < 1) alpha = Math.pow(10, alpha)
1414
- let betaVal = top + Math.log10(alpha)
1415
- if (top >= sciBound) {
1416
- return letter + formatR0Arg(betaVal, precision)
1417
- }
1418
- let alphaStr = regularFormat(alpha, precision)
1419
- let betaStr = formatR0Arg(top, precision)
1420
- return alphaStr + letter + betaStr
1421
- }
1422
-
1423
- // Multi-letter range fallback: α + letter + β
1424
- let letter = letterName(Math.max(h, 23))
1425
- let alpha = bottom
1426
- if (alpha < 1) alpha = Math.pow(10, alpha)
1427
- let alphaStr = regularFormat(alpha, precision)
1428
- let betaStr = formatR0Arg(top, precision)
1429
- return alphaStr + letter + betaStr
1430
- }
1431
-
1432
- // ─── Format with Ordinal Rows ────────────────────────────────────
1433
-
1434
- // finite-row chain display (≤2-letter-types rule): r0 cols + [count, level]
1435
- // rows form one hyperoperation cascade.
1436
- // top level ≥ 23 (Aa region): the αAaβ diagonal from polarizeFiniteChain,
1437
- // mantissa normalized into [1,10) carrying decades into β:
1438
- // 3{24}3 → "2.376Aa23", 3{100}3 → "2.376Aa99", 10{10000}10 → "1.000Aa10,000".
1439
- // top level ≤ 22 (single letters): the structural two-letter form
1440
- // Γ_top×c₁ + Γ_second×(c₂−1) + bottom + Γ_second + repeation:
1441
- // 3{22}3 → "Y2.376X2", 3{23}3 → "Z2.376Y2".
1442
- // c₁ ≥ repeatLetterThreshold+1 carries to the next single letter.
1443
- function formatFiniteRowChain(r0, finiteRows, precision) {
1444
- function levelCount(lv) {
1445
- if (lv < r0.length && (r0[lv] || 0) > 0) return r0[lv]
1446
- for (let i = 0; i < finiteRows.length; i++) {
1447
- if (finiteRows[i][1] === lv) return finiteRows[i][0]
1448
- }
1449
- return 0
1450
- }
1451
- let topLv = 0, c1 = 0
1452
- for (let i = 1; i < r0.length; i++) {
1453
- if ((r0[i] || 0) > 0) { topLv = i; c1 = r0[i] }
1454
- }
1455
- for (let i = 0; i < finiteRows.length; i++) {
1456
- if (finiteRows[i][1] > topLv) { topLv = finiteRows[i][1]; c1 = finiteRows[i][0] }
1457
- }
1458
- if (topLv === 0) return formatR0Arg(r0[0], precision)
1459
- let effThreshold = Math.max(2, FORMAT_OPTIONS.repeatLetterThreshold)
1460
-
1461
- if (topLv >= 23) {
1462
- let pol = polarizeFiniteChain(r0, finiteRows)
1463
- if (pol && isFinite(pol.bottom) && pol.bottom > 0 && isFinite(pol.arrows)) {
1464
- let pair = aaDiagonalPair(pol)
1465
- return regularFormat(pair.mant, precision) + "Aa" + commaFormat(pair.beta)
1466
- }
1467
- // fallback: legacy coefficient form on the top row
1468
- let lastRow = finiteRows[finiteRows.length - 1]
1469
- if (lastRow) return lastRow[0] + "Aa" + commaFormat(lastRow[1])
1470
- return formatR0AsChain(r0.slice(0), precision)
1471
- }
1472
-
1473
- // carry: c₁ ≥ threshold+1 top-letter repeats advance to the next letter
1474
- if (c1 >= effThreshold + 1) {
1475
- let lv = topLv + 1
1476
- if (lv <= 19) {
1477
- let num = new MetaNum({ sign: 1, layer: 0, array: [r0.slice(0)].concat(finiteRows.map(r => r.slice(0))) })
1478
- let bx = gammaArgOf(num, lv, 40)
1479
- if (bx !== null && isFinite(bx) && bx >= 2) return formatGammaBinary(bx, lv, precision)
1480
- }
1481
- let pol = polarizeFiniteChain(r0, finiteRows)
1482
- if (pol && isFinite(pol.bottom) && pol.bottom > 0 && isFinite(pol.arrows)) {
1483
- if (lv >= 23) {
1484
- // carry lands on the Aa diagonal: convert the polarize triple
1485
- // via the same linear mantissa/β rule as the topLv>=23 path
1486
- // (10{23}10 -> 1.000Aa23, not "1.000Aa10")
1487
- let pair = aaDiagonalPair(pol)
1488
- return regularFormat(pair.mant, precision) + "Aa" + commaFormat(pair.beta)
1489
- }
1490
- if (pol.bottom >= 1) {
1491
- return regularFormat(pol.bottom, precision) + letterName(lv) + commaFormat(pol.repeation)
1492
- }
1493
- }
1494
- }
1495
-
1496
- // structural two-letter form (≤ 22: single-letter region)
1497
- let secondLv = 0, c2 = 0
1498
- for (let s = topLv - 1; s >= 1; s--) {
1499
- let c = levelCount(s)
1500
- if (c > 0) { secondLv = s; c2 = c; break }
1501
- }
1502
- if (secondLv >= 1 && c2 <= effThreshold) {
1503
- let restR0 = r0.slice(0, Math.min(secondLv + 1, r0.length))
1504
- let restRows = finiteRows.filter(r => r[1] <= secondLv)
1505
- let pol = polarizeFiniteChain(restR0, restRows)
1506
- if (pol && pol.arrows === secondLv && isFinite(pol.bottom) && pol.bottom >= 1) {
1507
- let prefix = letterName(topLv).repeat(Math.min(c1, effThreshold)) +
1508
- letterName(secondLv).repeat(Math.max(c2 - 1, 0))
1509
- return prefix + regularFormat(pol.bottom, precision) + letterName(secondLv) + commaFormat(pol.repeation)
1510
- }
1511
- // low levels: engine-curve bisect at the second letter
1512
- if (secondLv <= 19) {
1513
- let num = new MetaNum({ sign: 1, layer: 0, array: [restR0].concat(restRows.map(r => r.slice(0))) })
1514
- let bx = gammaArgOf(num, secondLv, 40)
1515
- if (bx !== null && isFinite(bx) && bx >= 2) {
1516
- let prefix = letterName(topLv).repeat(Math.min(c1, effThreshold))
1517
- return prefix + formatGammaBinary(bx, secondLv, precision)
1518
- }
1519
- }
1520
- }
1521
-
1522
- // ── Repeated top letter over a dominant lower level ──
1523
- // When the top row is only a prefix (count ≤ threshold) but a lower row
1524
- // holds the real argument, polarizeFiniteChain collapses the chain and the
1525
- // top argument degenerates (ZZ152416 read "1.000Z3"). Spell the top row as
1526
- // prefix letters and format the remaining chain on its own, keeping the
1527
- // real argument (ZZ152416 → "Z1.000Z152,416").
1528
- let topRow = finiteRows[finiteRows.length - 1]
1529
- if (finiteRows.length >= 2 && topRow && topRow[1] === topLv &&
1530
- Number.isInteger(topRow[0]) && topRow[0] >= 1 && topRow[0] <= effThreshold) {
1531
- let restR0 = r0.slice(0)
1532
- for (let i = 0; i < finiteRows.length - 1; i++) {
1533
- let r = finiteRows[i]
1534
- while (restR0.length <= r[1]) restR0.push(0)
1535
- restR0[r[1]] = r[0]
1536
- }
1537
- let innerStr = formatR0AsChain(restR0, precision)
1538
- if (innerStr) return letterName(topLv).repeat(topRow[0]) + innerStr
1539
- }
1540
-
1541
- // fallback: single binary at the top letter
1542
- let polF = polarizeFiniteChain(r0, finiteRows)
1543
- if (polF && isFinite(polF.bottom) && polF.bottom >= 1) {
1544
- return regularFormat(polF.bottom, precision) + letterName(topLv) + commaFormat(polF.repeation)
1545
- }
1546
- return formatR0AsChain(r0.slice(0), precision)
1547
- }
1548
-
1549
- function formatOrdinal(num, precision, precision4) {
1550
- let r0 = num.array[0]
1551
- let ordRows = num.array.slice(1)
1552
-
1553
- // v2.1 classification: Format-B finite rows [count, level] form the
1554
- // hyperoperation cascade; Format-A ordinal rows [count, v…, diag] are the
1555
- // ω-diagonalization markers displayed as letter prefixes.
1556
- let finiteRows = []
1557
- let ordinalRows = []
1558
- for (let i = 0; i < ordRows.length; i++) {
1559
- if (ordRows[i].length === 2) finiteRows.push(ordRows[i])
1560
- else ordinalRows.push(ordRows[i])
1561
- }
1562
- if (finiteRows.length > 0 && ordinalRows.length === 0) {
1563
- return formatFiniteRowChain(r0, finiteRows, precision4)
1564
- }
1565
- if (finiteRows.length > 0 && ordinalRows.length > 0) {
1566
- let prefixLetter = getOrdinalLetter(ordinalRows)
1567
- if (prefixLetter) {
1568
- return prefixLetter + formatFiniteRowChain(r0, finiteRows, precision4)
1569
- }
1570
- // no letter recovered: fall through to the legacy machinery below
1571
- }
1572
- ordRows = ordinalRows
1573
-
1574
- // Get the letter name from ordinal rows (3+ element format)
1575
- // ── Check for ω-level rows (diag=1, all vals=0) → J-like format ──
1576
- // Aa (ω-level) uses J-like format: mantissa = log10(bottom) + count
1577
- let allAaOnly = true
1578
- let totalAaCount = 0
1579
- let aaZeroCount = -1
1580
- for (let i = 0; i < ordRows.length; i++) {
1581
- let row = ordRows[i]
1582
- if (row.length < 3) { allAaOnly = false; break }
1583
- let diag = row[row.length - 1]
1584
- let vals = row.slice(1, row.length - 1)
1585
- if (diag !== 1 || !vals.every(v => v === 0)) { allAaOnly = false; break }
1586
- let nZeros = vals.length
1587
- if (aaZeroCount === -1) aaZeroCount = nZeros
1588
- else if (nZeros !== aaZeroCount) { allAaOnly = false; break }
1589
- totalAaCount += row[0] || 1
1590
- }
1591
- if (allAaOnly && totalAaCount > 0) {
1592
- // Build the letter "A" + "a".repeat(aaZeroCount) (Aa, Aaa, Aaaa, …):
1593
- // for ordinal rows diag=1 → "A" and each val 0 → "a", so
1594
- // aaZeroCount = vals length (Aa → 1, height 23; Aaa → 2, height 699).
1595
- let baseHeight
1596
- if (aaZeroCount === 1) {
1597
- baseHeight = 23 // Aa
1598
- } else {
1599
- // 3+ letters: use offset formula from letterName
1600
- let nLetters = aaZeroCount + 1 // total letters (1 uppercase + n lowercase)
1601
- let offset = 0
1602
- for (let k = 2; k < nLetters; k++) {
1603
- offset += Math.pow(26, k)
1604
- }
1605
- // For Aaa (nLetters=3): n=0, so height=23 + offset + 0
1606
- baseHeight = 23 + offset
1607
- }
1608
- let letter = letterName(baseHeight)
1609
- let effThreshold = Math.max(2, FORMAT_OPTIONS.multiLetterRepeatThreshold)
1610
-
1611
- // Check if r0 has multiple levels (e, f, g, ...) - requires different format
1612
- let hasMultiLevelR0 = r0.length > 1 && (r0[1] || 0) + (r0[2] || 0) + (r0[3] || 0) > 0
1613
-
1614
- if (hasMultiLevelR0) {
1615
- // r0 = [base, e, f, g, ...] with at least one non-zero higher level
1616
- // Format: chain letters (F, G, etc.) + scientific notation at the end
1617
- let argStr = formatR0AsChain(r0, precision4)
1618
-
1619
- // Only collapse when totalAaCount >= effThreshold (default 3)
1620
- // This is the GRAHAMS_NUMBER case: 63 Aa's → Ab(64)
1621
- if (totalAaCount >= effThreshold && aaZeroCount === 1) {
1622
- // Only do ONE collapse: n Aa → 1 Ab with param (n+1)
1623
- // Only for 2-letter (Aa) so we don't break Aaa etc.
1624
- let finalLevel = baseHeight + 1 // Aa → Ab (exactly 1 step: 23→24)
1625
- let finalParam = totalAaCount + 1 // param is n+1, not more repeats
1626
- let finalLetter = letterName(finalLevel)
1627
- // Mantissa: get a meaningful display number
1628
- // For GRAHAMS_NUMBER: want ~3.1, use a reasonable formula
1629
- let r0Base = r0[0]
1630
- let r0Bottom = Math.pow(10, r0Base - Math.floor(r0Base))
1631
- let mantissa = Math.log10(Math.max(r0Bottom, 0.001)) + Math.log10(Math.max(finalParam, 1)) * 0.4 + 1.6
1632
- return regularFormat(mantissa, precision4) + finalLetter + commaFormat(finalParam)
1633
- } else if (totalAaCount > 1) {
1634
- // Repeated Aa below threshold: use AaAa... prefix
1635
- let tokAa = letterTokenOf(baseHeight)
1636
- if (tokAa.sym) {
1637
- // multiLetterLimit symbol carry: the diagonal letter reads
1638
- // as one more symbol with the chain as its argument
1639
- return tokAa.sym + regularFormat(2, precision4) + tokAa.letter + argStr
1640
- }
1641
- // past the collapse threshold the repeats shift the argument and
1642
- // advance the letter — a raw repeat would try to build a string
1643
- // with `count` copies (Aaa repeated 1e9 times cannot be built)
1644
- let repArgStr = argStr
1645
- if (totalAaCount > 64) {
1646
- let r0Bottom = Math.pow(10, r0[0] - Math.floor(r0[0]))
1647
- let repParam = totalAaCount + 1
1648
- let mantissa = Math.log10(Math.max(r0Bottom, 0.001)) +
1649
- Math.log10(Math.max(repParam, 1)) * 0.4 + 1.6
1650
- return regularFormat(mantissa, precision4) +
1651
- letterName(baseHeight + 1) + commaFormat(repParam)
1652
- }
1653
- return letter.repeat(totalAaCount) + repArgStr
1654
- } else {
1655
- // Single Aa
1656
- let tokAa = letterTokenOf(baseHeight)
1657
- if (tokAa.sym) {
1658
- return tokAa.sym + regularFormat(2, precision4) + tokAa.letter + argStr
1659
- }
1660
- return letter + argStr
1661
- }
1662
- } else {
1663
- // r0 is a simple number (length=1 or just r0[0])
1664
- let base = r0[0]
1665
- let alpha = Math.pow(10, base - Math.floor(base))
1666
- if (alpha < 1) alpha *= 10
1667
- let alphaStr = regularFormat(alpha, precision4)
1668
- let top = Math.floor(base)
1669
- let betaStr = formatR0Arg(top, precision4)
1670
-
1671
- // Collapse threshold: at multiLetterRepeatThreshold+1, advance to next letter
1672
- let collapseAt = effThreshold + 1
1673
-
1674
- if (totalAaCount >= collapseAt) {
1675
- // Collapse to next letter (Aa→Ab, Ab→Ac, etc.): the repeats
1676
- // shift the argument (arg = count+1) and the mantissa keeps
1677
- // the [1,10) convention (2.398Ab99 — the same α the GRAHAMS
1678
- // branch above produces), never the raw count as α
1679
- let arg = totalAaCount + 1
1680
- let mantVal = Math.log10(Math.max(alpha, 0.001)) +
1681
- Math.log10(Math.max(arg, 1)) * 0.4 + 1.6
1682
- let newHeight = baseHeight + 1
1683
- let newLetter = letterName(newHeight)
1684
- return regularFormat(mantVal, precision4) + newLetter + formatR0Arg(arg, precision4)
1685
- } else if (totalAaCount > 1) {
1686
- // Repeated letters: outerLetters + α + lastLetter + β
1687
- let outerLetters = letter.repeat(totalAaCount - 1)
1688
- return outerLetters + alphaStr + letter + betaStr
1689
- } else {
1690
- // Single DIAGONAL letter (the row ends in 'a': Aa, Aaa,
1691
- // Ba, …): pure dlsdl convention α=2·5^f ∈ [2,10).
1692
- // Decision 1B: the base is the ARGUMENT β (the row zero count
1693
- // encodes the letter level). !Aa3 = Aaaa3 therefore reads
1694
- // "2.000Aaaa3" — not the historical anchor-A "2.000Aaaa10".
1695
- let diagMant = 2 * Math.pow(5, base - Math.floor(base))
1696
- let diagBeta = top
1697
- // #26/#28: a single multi-a diagonal marker round-trips exactly
1698
- // as the letter token itself (Aaa1.5, Aaaaa3.5, Aaaaa10). The
1699
- // αAaaβ spelling is only used for integer arguments that stay
1700
- // inside multiLetterLimit (α=2); past the limit the old
1701
- // single-letter carry hard-coded 10 and did not round-trip.
1702
- let multiLimit = Math.max(2, FORMAT_OPTIONS.multiLetterLimit | 0)
1703
- if (aaZeroCount >= 2 && (base !== top || aaZeroCount + 1 > multiLimit)) {
1704
- let argStr = String(base)
1705
- if (/e-/i.test(argStr)) argStr = base.toFixed(20)
1706
- argStr = argStr.replace(/e\+?/i, "E")
1707
- if (aaZeroCount <= MULTI_TOKEN_CAP) return letter + argStr
1708
- // Hard-cap fallback: preserve the argument but accept the
1709
- // historical single-letter level approximation.
1710
- return "!" + regularFormat(1, precision4) +
1711
- letterName(aaZeroCount) + argStr
1712
- }
1713
- return regularFormat(diagMant, precision4) + letter + commaFormat(diagBeta)
1714
- }
1715
- }
1716
- }
1717
-
1718
- // ── Unnamed-level display (v2.0.2) ──
1719
- // The letter grid only names ordinals with coefficients ≤ 25 (top ≤ 26).
1720
- // When the TOP row's ordinal is above that (ω*2+96, ω*99, ω²*100, …) every
1721
- // row snaps up to the SAME next nameable level, and summing their counts
1722
- // would collapse the letter further (243 Ca's → Cb(244)) — overstating the
1723
- // level and hiding the argument. Instead the value reads as level-arg:
1724
- // 10{ω*2+100}100 → "1.000Ca100", 10{ω*100}100 → "1.000Aaa100",
1725
- // 10{ω²*100+ω*100+100}1000 → "1.000Aaaa1,000".
1726
- let gapStr = null
1727
- {
1728
- let topRow = ordRows[ordRows.length - 1]
1729
- if (topRow && topRow.length >= 3) {
1730
- let oc = topRow.slice(1)
1731
- let carried = false
1732
- for (let gi = 0; gi < oc.length; gi++) {
1733
- let gc = oc[gi]
1734
- let gbound = (gi === oc.length - 1) ? 26 : 25
1735
- if (typeof gc !== 'number' || !isFinite(gc) || gc < 0 ||
1736
- Math.round(gc) > gbound) { carried = true; break }
1737
- }
1738
- if (carried) {
1739
- let g = snapCoeffsToGrid(oc)
1740
- let gdiag = g[g.length - 1]
1741
- let gvals = g.slice(0, g.length - 1)
1742
- let gh = 23 + (gdiag - 1) * 26 + (gvals.length ? gvals[0] : 0)
1743
- if (gvals.length >= 2) {
1744
- let goffset = 0
1745
- for (let gk = 2; gk <= gvals.length; gk++) goffset += Math.pow(26, gk)
1746
- let gn = (gdiag - 1) * Math.pow(26, gvals.length)
1747
- for (let gj = 0; gj < gvals.length; gj++) gn += gvals[gj] * Math.pow(26, gj)
1748
- gh = 23 + goffset + gn
1749
- }
1750
- // β = the fundamental-sequence index recovering the ordinal
1751
- // from the snapped level. Carry in the TOP coefficient
1752
- // (ω^p·c → ω^(p+1)): the index is c+1 —
1753
- // 10{ω²·50+ω·100+100}100 → "2.000Aaaa51"
1754
- // 10{ω²·100+ω·100+100}100 → "2.000Aaaa101"
1755
- // 10{ω²·200+…}100 → "2.000Aaaa201"
1756
- // (the largest coefficient collapsed all three into one
1757
- // string). Carry BELOW the top (ω·2+100 → ω·3): the index is
1758
- // the operation's argument.
1759
- let gbeta = (topRow[0] || 1) + 2
1760
- for (let g2 = oc.length - 1; g2 >= 0; g2--) {
1761
- let gc2 = Math.round(oc[g2])
1762
- let gbound = (g2 === oc.length - 1) ? 26 : 25
1763
- if (isFinite(gc2) && gc2 > gbound) { gbeta = gc2 + 1; break }
1764
- }
1765
- let gtok = letterTokenOf(gh)
1766
- let gbase = r0[0]
1767
- let galpha = Math.pow(10, gbase - Math.floor(gbase))
1768
- if (galpha < 1) galpha *= 10
1769
- if (gtok.sym) {
1770
- // the carried !αAaβ form: β is the ω-EXPONENT of the
1771
- // snapped level (ω³·50+… → ω⁴ → "!2.000Aa4"), not the
1772
- // fundamental-sequence index — !2.000Aa51 would read as
1773
- // the ω⁵¹ level (README: !αAaβ = ω^β + digits of α)
1774
- gapStr = emitLetterToken(gtok, regularFormat(gtok.mant, precision4),
1775
- formatR0Arg(gbeta, precision4), precision4)
1776
- } else {
1777
- // a diagonal letter ("Ca", "Aaa", …) carries α = 2·5^f ∈
1778
- // [2,10) — never the [1,10) mantissa of the other letters
1779
- gapStr = regularFormat(
1780
- diagonalMantissa(gtok.letter, Math.log10(galpha)), precision4) +
1781
- gtok.letter + formatR0Arg(gbeta, precision4)
1782
- }
1783
- }
1784
- }
1785
- }
1786
- if (gapStr !== null) return gapStr
1787
-
1788
- // ── Check for repeated non-ω letters → advance to next letter ──
1789
- // AbAb→Ac, AcAc→Ad, ..., AzAz→Ba, BaBa→Bb, etc.
1790
- // Only applies when repeat count >= multiLetterRepeatThreshold
1791
- let allSameLetter = true
1792
- let totalRepeat = 0
1793
- let baseLetterHeight = -1
1794
-
1795
- for (let i = 0; i < ordRows.length; i++) {
1796
- let row = ordRows[i]
1797
- if (row.length < 3) { allSameLetter = false; break }
1798
- // The letter grid only names ordinals whose coefficients are ≤ 25 (the
1799
- // top one ≤ 26); anything larger (ω*2+96, ω*99, ω²*100, …) is rounded UP
1800
- // to the next nameable ordinal — ω*2+96 → ω*3 (Ca), ω*99 → ω² (Aaa),
1801
- // ω²*100 → ω³ (Aaaa) — never clamped down, never wrapped.
1802
- let g = snapCoeffsToGrid(row.slice(1))
1803
- let diag = g[g.length - 1]
1804
- let vals = g.slice(0, g.length - 1)
1805
- let nVals = vals.length
1806
-
1807
- // Calculate height for this letter
1808
- let height = 0
1809
- if (nVals === 1) {
1810
- // 2-letter: Aa=23, Ab=24, ..., Az=48, Ba=49, ...
1811
- height = 23 + (diag - 1) * 26 + vals[0]
1812
- } else {
1813
- // 3+ letters: need to calculate offset
1814
- // vals are stored in reverse letter order (e.g. "bc" -> [2,1]),
1815
- // so the leftmost letter digit is vals[nVals-1]:
1816
- // n = vals[0]*26^0 + vals[1]*26^1 + ... (little-endian)
1817
- let offset = 0
1818
- for (let k = 2; k <= nVals; k++) {
1819
- offset += Math.pow(26, k)
1820
- }
1821
- let n = (diag - 1) * Math.pow(26, nVals)
1822
- for (let j = 0; j < nVals; j++) {
1823
- n += vals[j] * Math.pow(26, j)
1824
- }
1825
- height = 23 + offset + n
1826
- }
1827
-
1828
- if (baseLetterHeight === -1) {
1829
- baseLetterHeight = height
1830
- } else if (height !== baseLetterHeight) {
1831
- allSameLetter = false
1832
- break
1833
- }
1834
- totalRepeat += row[0] || 1
1835
- }
1836
-
1837
- if (allSameLetter && totalRepeat > 0 && baseLetterHeight >= 23) {
1838
- let base = r0[0]
1839
- let alpha = Math.pow(10, base - Math.floor(base))
1840
- if (alpha < 1) alpha *= 10
1841
- let alphaStr = regularFormat(alpha, precision4)
1842
- let top = Math.floor(base)
1843
- let betaStr = formatR0Arg(top, precision4)
1844
-
1845
- // Check if we should advance (repeat threshold)
1846
- let effThreshold = Math.max(2, FORMAT_OPTIONS.multiLetterRepeatThreshold)
1847
- let collapseAt = effThreshold + 1
1848
-
1849
- // Check if r0 has multiple levels (e, f, g, ...)
1850
- let hasMultiLevelR0 = r0.length > 1
1851
-
1852
- if (hasMultiLevelR0) {
1853
- // r0 has E/F/G levels: format as letter(s) + chain (e.g., Ab1.000E500)
1854
- let r0Str = formatR0AsChain(r0, precision4)
1855
- let letter = letterName(baseLetterHeight)
1856
- let tokAdv = letterTokenOf(baseLetterHeight + 1)
1857
- if (totalRepeat >= collapseAt && tokAdv.sym) {
1858
- // Collapse to next letter — carried when it exceeds the limit.
1859
- // !αAaβ takes the ω-EXPONENT as β (README: !αAaβ = ω^β + the
1860
- // digits of α), not the r0 chain.
1861
- return emitLetterToken(tokAdv, regularFormat(tokAdv.mant, precision4),
1862
- r0Str, precision4)
1863
- }
1864
- if (totalRepeat >= collapseAt) {
1865
- // Collapse to next letter — the repeat count shifts the
1866
- // argument, so the mantissa keeps the [1,10) convention
1867
- let mantissa = Math.log10(Math.max(alpha, 0.001)) + totalRepeat
1868
- let newLetter = letterName(baseLetterHeight + 1)
1869
- let mantVal = diagonalMantissa(newLetter, mantissa)
1870
- return regularFormat(mantVal, precision4) + newLetter + r0Str
1871
- } else if (totalRepeat > 1) {
1872
- // Repeated letters + chain: one token per application, the
1873
- // innermost one in front of the chain (Ba(Ba(1e16)) → the
1874
- // stacked "BaBa1.000E16" — apea(apea(a)) must stay visible)
1875
- let outerLetters = letter.repeat(totalRepeat)
1876
- return outerLetters + r0Str
1877
- } else {
1878
- // Single letter + chain
1879
- return letter + r0Str
1880
- }
1881
- }
1882
-
1883
- // Simple r0 (no E/F/G levels)
1884
- if (totalRepeat >= collapseAt) {
1885
- // Advance to next letter with mantissa — carried when the letter
1886
- // exceeds multiLetterLimit (!αAaβ, repeats below display precision)
1887
- let tokAdv = letterTokenOf(baseLetterHeight + 1)
1888
- if (tokAdv.sym) {
1889
- return emitLetterToken(tokAdv, regularFormat(tokAdv.mant, precision4), betaStr, precision4)
1890
- }
1891
- let mantissa = Math.log10(Math.max(alpha, 0.001)) + totalRepeat
1892
- let newHeight = baseLetterHeight + 1
1893
- let letter = letterName(newHeight)
1894
- let mantVal = diagonalMantissa(letter, mantissa)
1895
- return regularFormat(mantVal, precision4) + letter +
1896
- formatR0Arg(totalRepeat + 1, precision4)
1897
- } else if (totalRepeat > 1) {
1898
- // Repeated letters: outerLetters + α + lastLetter + β
1899
- let letter = letterName(baseLetterHeight)
1900
- let tokRep = letterTokenOf(baseLetterHeight)
1901
- if (tokRep.sym) {
1902
- return emitLetterToken(tokRep, alphaStr, betaStr, precision4)
1903
- }
1904
- let outerLetters = letter.repeat(totalRepeat - 1)
1905
- return outerLetters + alphaStr + letter + betaStr
1906
- } else {
1907
- // Single letter. DIAGONAL letters (token ends in 'a': Aa, Ba,
1908
- // Ca, Aaa, …) use the dlsdl [2,10) mantissa 2·5^f with β = base
1909
- // argument (Ba1000 -> 2.000Ba1,000); successor letters (Ab, Bb,
1910
- // … keep the ordinary [1,10) α/β form).
1911
- let letter = letterName(baseLetterHeight)
1912
- // multiLetterLimit symbol carry for a single long letter: the
1913
- // diagonal keeps its 2·5^f mantissa, the ordinary letters use the
1914
- // definition digits (!αAaβ), and β becomes the ω-exponent
1915
- let tokSingle = letterTokenOf(baseLetterHeight)
1916
- if (tokSingle.sym) {
1917
- if (letter.length >= 2 && letter[letter.length - 1] === "a") {
1918
- let diagMant = 2 * Math.pow(5, base - Math.floor(base))
1919
- return tokSingle.sym + regularFormat(diagMant, precision4) +
1920
- tokSingle.letter + formatR0Arg(tokSingle.arg, precision4)
1921
- }
1922
- return emitLetterToken(tokSingle, alphaStr, betaStr, precision4)
1923
- }
1924
- if (letter.length >= 2 && letter[letter.length - 1] === "a") {
1925
- let diagMant = 2 * Math.pow(5, base - Math.floor(base))
1926
- return regularFormat(diagMant, precision4) + letter + betaStr
1927
- }
1928
- return alphaStr + letter + betaStr
1929
- }
1930
- }
1931
-
1932
- // ── Handle mixed letter types with collapse ──
1933
- // When ordinal rows have multiple different letter types (e.g., Aa + Ab),
1934
- // collapse lower-level letters to higher-level if count >= threshold
1935
- {
1936
- let letterCounts = {} // height -> count
1937
- let heights = []
1938
-
1939
- for (let i = 0; i < ordRows.length; i++) {
1940
- let row = ordRows[i]
1941
- if (row.length < 2) continue
1942
-
1943
- // Parse height from row
1944
- let height = -1
1945
- if (row.length === 2) {
1946
- height = 23 // ω-level (Aa)
1947
- } else {
1948
- // round the ordinal UP to the next one the letter grid can name
1949
- // (ω*2+96 → ω*3 = Ca, ω*99 → ω² = Aaa, ω²*100 → ω³ = Aaaa)
1950
- let g2 = snapCoeffsToGrid(row.slice(1))
1951
- let diag = g2[g2.length - 1]
1952
- let vals = g2.slice(0, g2.length - 1)
1953
- let nVals = vals.length
1954
- if (nVals === 1) {
1955
- // 2-letter: Aa=23, Ab=24, ..., Az=48, Ba=49, ...
1956
- height = 23 + (diag - 1) * 26 + vals[0]
1957
- } else {
1958
- // vals are the CNF coefficients a1, a2, …, a(x-1) of
1959
- // ord = ω^(x-1)·ax + … + ω·a2 + a1 — little-endian, the same
1960
- // order letterName()/getOrdinalLetter() decode the letter:
1961
- // the LAST val is the first lowercase letter of the token.
1962
- let offset = 0
1963
- for (let k = 2; k <= nVals; k++) offset += Math.pow(26, k)
1964
- let n = (diag - 1) * Math.pow(26, nVals)
1965
- for (let j = 0; j < nVals; j++) n += vals[j] * Math.pow(26, j)
1966
- height = 23 + offset + n
1967
- }
1968
- }
1969
- if (height < 0) continue
1970
-
1971
- let count = row[0] || 1
1972
- if (!(height in letterCounts)) heights.push(height)
1973
- letterCounts[height] = (letterCounts[height] || 0) + count
1974
- }
1975
-
1976
- if (heights.length >= 1) {
1977
- // Sort heights ascending
1978
- heights.sort((a, b) => a - b)
1979
-
1980
- // README: at most TWO finite letter types survive — a longer
1981
- // cascade keeps only its top two levels, every lower row
1982
- // compresses into the second letter's argument (they are below
1983
- // display precision, and folding them into its repeat COUNT would
1984
- // overstate the level: 8 ω's + 8 (ω+1)'s ≠ 16 more (ω+2)'s).
1985
- if (heights.length > 2) {
1986
- let keepLo = heights[heights.length - 2]
1987
- for (let i = 0; i < heights.length - 2; i++) delete letterCounts[heights[i]]
1988
- heights = Object.keys(letterCounts).map(Number).sort((a, b) => a - b)
1989
- }
1990
-
1991
- if (heights.length >= 1) {
1992
- // ── Display rules (README "format-metanum rules (v2.0)") ──
1993
- // * the rows are a COMPOSITION: the top row leads and the row
1994
- // below supplies the single α and β (at most TWO letter
1995
- // types — lower rows compress into that inner argument);
1996
- // * "+count collapse": count >= multiLetterRepeatThreshold+1
1997
- // repeats collapse to ONE next letter with arg count+1
1998
- // (F⁴(G(1.3796)) = G(5.3796));
1999
- // * stacking the same function nests the letter:
2000
- // poea(10,poea(10,100)) → "Ad1.000Ad99";
2001
- // * a combination longer than multiLetterLimit carries to the
2002
- // symbol notation !αAaβ.
2003
- let effTh = Math.max(2, FORMAT_OPTIONS.multiLetterRepeatThreshold)
2004
- let collapseAt = effTh + 1
2005
-
2006
- let base = r0[0]
2007
- let r0Alpha = Math.pow(10, base - Math.floor(base))
2008
- if (r0Alpha < 1) r0Alpha *= 10
2009
- let frac = base - Math.floor(base)
2010
- if (frac < 0) frac += 1
2011
-
2012
- // α of a "+count collapse" (the ω-level form recovers the base
2013
- // mantissa the way the single-row Aa cascade does: 2.398Ab99)
2014
- let collapseMant = function (h, count) {
2015
- let arg = count + 1
2016
- if (h === 23) {
2017
- return regularFormat(Math.log10(Math.max(r0Alpha, 0.001)) +
2018
- Math.log10(Math.max(arg, 1)) * 0.4 + 1.6, precision4)
2019
- }
2020
- return regularFormat(r0Alpha, precision4)
2021
- }
2022
- // one collapsed level: α + next letter + (count+1)
2023
- let collapseStr = function (h, count) {
2024
- let tok = letterTokenOf(h + 1)
2025
- if (tok.sym) {
2026
- return tok.sym + regularFormat(tok.mant, precision4) +
2027
- tok.letter + formatR0Arg(count + 1, precision4)
2028
- }
2029
- return collapseMant(h, count) + tok.letter + formatR0Arg(count + 1, precision4)
2030
- }
2031
-
2032
- let hTop = heights[heights.length - 1]
2033
- let cTop = letterCounts[hTop] || 1
2034
- let hLow = heights.length >= 2 ? heights[heights.length - 2] : -1
2035
- let cLow = hLow < 0 ? 0 : (letterCounts[hLow] || 1)
2036
-
2037
- // (1) a single row level: collapse, or repeats with α + letter + β
2038
- if (hLow < 0) {
2039
- if (cTop >= collapseAt) return collapseStr(hTop, cTop)
2040
- let tok = letterTokenOf(hTop)
2041
- if (tok.sym) return emitLetterToken(tok, regularFormat(r0Alpha, precision4),
2042
- formatR0Arg(Math.floor(base), precision4), precision4)
2043
- let aStr = (tok.letter.length >= 2 && tok.letter[tok.letter.length - 1] === "a")
2044
- ? regularFormat(2 * Math.pow(5, frac), precision4)
2045
- : regularFormat(r0Alpha, precision4)
2046
- return tok.letter.repeat(Math.max(cTop - 1, 0)) + aStr + tok.letter +
2047
- formatR0Arg(Math.floor(base), precision4)
2048
- }
2049
-
2050
- // (2) the inner (second) level carries the single α and β
2051
- let lowTok = letterTokenOf(hLow)
2052
- let innerStr
2053
- if (cLow >= collapseAt) {
2054
- innerStr = collapseStr(hLow, cLow)
2055
- } else {
2056
- let aStr = regularFormat(r0Alpha, precision4)
2057
- innerStr = lowTok.letter.repeat(Math.max(cLow - 1, 0)) + aStr + lowTok.letter +
2058
- formatR0Arg(Math.floor(base), precision4)
2059
- }
2060
-
2061
- // (3) the top level leads: collapse when it repeats enough, else
2062
- // one token per application (or the symbol-carried !αAaβ)
2063
- if (cTop >= collapseAt) return collapseStr(hTop, cTop)
2064
- let topTok = letterTokenOf(hTop)
2065
- if (topTok.sym) {
2066
- // multiLetterLimit carry: !αAaβ, β = the ω-exponent; the
2067
- // inner level only survives when it collapses on its own
2068
- if (cLow >= collapseAt) {
2069
- return topTok.sym + regularFormat(topTok.mant, precision4) +
2070
- topTok.letter + collapseStr(hLow, cLow)
2071
- }
2072
- return topTok.sym + regularFormat(topTok.mant, precision4) +
2073
- topTok.letter + formatR0Arg(topTok.arg, precision4)
2074
- }
2075
- return topTok.letter.repeat(Math.min(cTop, effTh)) + innerStr
2076
- }
2077
- }
2078
- }
2079
-
2080
- let letter = getOrdinalLetter(ordRows)
2081
- if (!letter) {
2082
- // Fallback: use r0 only
2083
- let pol = metaPolarize(r0.slice(0))
2084
- let h = pol.height
2085
- letter = letterName(Math.max(h, 23))
2086
- let bottomVal = Math.log10(Math.max(pol.bottom, 1)) + pol.top
2087
- return regularFormat(bottomVal, precision4) + letter + commaFormat(Math.max(h, 23))
2088
- }
2089
-
2090
- // Check if r0 has multiple levels: use formatR0AsChain for the r0 part
2091
- let hasMultiLevelR0 = r0.length > 1
2092
- if (hasMultiLevelR0) {
2093
- // Ordinal letter(s) + r0 chain (which includes its own α)
2094
- let r0Str = formatR0AsChain(r0, precision4)
2095
- return letter + r0Str
2096
- }
2097
-
2098
- // Simple r0: format as outerLetters + α + lastLetter + β
2099
- let base = r0[0]
2100
- let alpha = Math.pow(10, base - Math.floor(base))
2101
- if (alpha < 1) alpha *= 10
2102
- let alphaStr = regularFormat(alpha, precision4)
2103
- let top = Math.floor(base)
2104
- let betaStr = formatR0Arg(top, precision4)
2105
-
2106
- // Split letter string into tokens (each starts with uppercase)
2107
- let tokens = []
2108
- let current = ""
2109
- for (let i = 0; i < letter.length; i++) {
2110
- let c = letter[i]
2111
- if (c >= 'A' && c <= 'Z') {
2112
- if (current.length > 0) tokens.push(current)
2113
- current = c
2114
- } else {
2115
- current += c
2116
- }
2117
- }
2118
- if (current.length > 0) tokens.push(current)
2119
-
2120
- if (tokens.length <= 1) {
2121
- // Single letter: α + letter + β
2122
- return alphaStr + letter + betaStr
2123
- }
2124
-
2125
- // Multiple letters: outerLetters + α + lastLetter + β
2126
- let lastToken = tokens.pop()
2127
- let outerTokens = tokens.join("")
2128
- return outerTokens + alphaStr + lastToken + betaStr
2129
- }
2130
-
2131
- // ─── Public API ──────────────────────────────────────────────────
2132
-
2133
- function formatWhole(num) {
2134
- return format(num, 0)
2135
- }
2136
-
2137
- function formatSmall(num, precision=2) {
2138
- return format(num, precision, true)
2139
- }
2140
-
2141
- // ─── Exports ─────────────────────────────────────────────────────
2142
-
2143
- if (typeof module !== 'undefined' && module.exports) {
2144
- module.exports = { format, formatWhole, formatSmall, metaPolarize, letterName, symbolName, getOrdinalLetter, formatR0AsChain, FORMAT_OPTIONS, polarizeFiniteChain, gammaArgOf, formatGammaBinary }
1
+ // Author: dlsdl v2.1.2
2
+ // v2.1.2 Fix(format): `format` now caps every display at TWO letter combinations with an αΓβ binary tail
3
+ // Code snippets and templates from format-omeganum.js
4
+ // Uses dlsdl's Letter Notation (see README.md)
5
+
6
+ // Set to 1 to print debug information to console
7
+ let FORMAT_DEBUG = 0
8
+
9
+ // keep the exact A(a×k) token past multiLetterLimit up to this many a's;
10
+ // beyond it, fall back to the historical single-letter carry approximation.
11
+ const MULTI_TOKEN_CAP = 64
12
+
13
+ // re-entrancy guard for formatSingleLetterType's "ordinary display" fallback
14
+ // (format may itself ask for a single-letter collapse through composeLetterChain)
15
+ let singleDepth = 0
16
+
17
+ // formatFull() keeps the raw canonical chain (unlimited letter combinations);
18
+ // format() post-processes it into the binary-letter-canonical form.
19
+ // The flag disables the ≤2 guards inside the chain builders while formatFull runs.
20
+ let fullChainMode = false
21
+
22
+ // ─── Configuration Options ────────────────────────────────────────
23
+ const FORMAT_OPTIONS = {
24
+ smallNotationUseE: true, //true/false
25
+ smallNotationThreshold: 3, //0~9
26
+ decimalPlaces: 3, //0~9
27
+ decimalThreshold: 3, //0~15
28
+ useCommas: true, //true/false
29
+ sciThreshold: 9, //0~15
30
+ sciSignificantDigits: 3, //0~9
31
+ sciDecimalThreshold: 3, //0~15
32
+ singleLetterDigits: 3, //0~9
33
+ repeatLetterThreshold: 3, //2~9
34
+ multiLetterDigits: 3, //0~9
35
+ multiLetterRepeatThreshold: 3,//2~9
36
+ multiLetterLimit: 4, //2~9
37
+ epsilonSignificantDigits: 6 //0~9
38
+ }
39
+
40
+ // ─── Utility Functions ───────────────────────────────────────────
41
+
42
+ function commaFormat(num) {
43
+ if (!FORMAT_OPTIONS.useCommas) {
44
+ let n = typeof num === 'number' ? num : (num.toNumber ? num.toNumber() : Number(num))
45
+ if (isNaN(n) || !isFinite(n)) return "NaN"
46
+ return String(Math.floor(n))
47
+ }
48
+ if (num === null || num === undefined) return "NaN"
49
+ let n = typeof num === 'number' ? num : (num.toNumber ? num.toNumber() : Number(num))
50
+ if (isNaN(n) || !isFinite(n)) return "NaN"
51
+ if (n < 0.001) return "0"
52
+ let init = n.toString()
53
+ let portions = init.split(".")
54
+ portions[0] = portions[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
55
+ return portions[0]
56
+ }
57
+
58
+ function regularFormat(num, precision) {
59
+ if (num === null || num === undefined) return "NaN"
60
+ let n = typeof num === 'number' ? num : (num.toNumber ? num.toNumber() : Number(num))
61
+ if (isNaN(n) || !isFinite(n)) return "NaN"
62
+ if (n < 0.001) return (0).toFixed(precision)
63
+ if (precision === 0) return commaFormat(Math.floor(n))
64
+ let fmt
65
+ if (Number.isInteger(n) && precision > 0) {
66
+ fmt = n + "." + "0".repeat(precision)
67
+ } else {
68
+ fmt = n.toFixed(precision)
69
+ }
70
+ // Add commas to integer part if useCommas is enabled
71
+ if (FORMAT_OPTIONS.useCommas && precision > 0) {
72
+ let parts = fmt.split(".")
73
+ parts[0] = parts[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
74
+ fmt = parts.join(".")
75
+ }
76
+ return fmt
77
+ }
78
+
79
+ // ─── MetaNum-Specific Polarize ───────────────────────────────────
80
+ // r0 is [base, e, f, g, ...]: r0[0] is the argument, r0[1..] count the E/F/G… operations (levels 1, 2, 3, …).
81
+ // Binary form αΓβ: bottom = α (mantissa in [1,10)), top = β, height = Γ (1=E … 22=Z),
82
+ // repeat = count of repeated operations at the highest level (>1 means repeated letters).
83
+ function metaPolarize(r0, num) {
84
+ if (FORMAT_DEBUG >= 1) console.log("metaPolarize input:", JSON.stringify(r0))
85
+ if (r0.length === 0) r0 = [0]
86
+
87
+ // Find the highest non-zero index (level)
88
+ let highest = 0
89
+ for (let i = r0.length - 1; i >= 1; i--) {
90
+ if (r0[i] > 0) { highest = i; break }
91
+ }
92
+
93
+ if (highest === 0) {
94
+ // Simple number: just r0[0], no higher levels
95
+ let bottom = r0[0]
96
+ let top = 0
97
+ let height = 0
98
+ if (bottom >= 10) {
99
+ let logVal = Math.log10(bottom)
100
+ bottom = Math.pow(10, logVal - Math.floor(logVal))
101
+ top = Math.floor(logVal)
102
+ height = 1
103
+ }
104
+ if (FORMAT_DEBUG >= 1) console.log("metaPolarize simple:", {bottom, top, height, repeat: 1})
105
+ return {bottom, top, height, repeat: 1}
106
+ }
107
+
108
+ // r0 = [v, e, f, g, ...], For E^n (highest=1): climb E to convert to F format;
109
+ // For F^n or higher (highest>=2): compute the argument at the E→F boundary
110
+ let value = r0[0]
111
+ let eCount = r0[1] || 0
112
+
113
+ // Climb the base value through E level
114
+ let eClimbExtra = 0
115
+ while (value >= 10) {
116
+ value = Math.log10(value)
117
+ eClimbExtra++
118
+ }
119
+ eCount += eClimbExtra
120
+
121
+ // Compute the F-level argument from the climbed E value
122
+ let fArg
123
+ if (value >= 1) {
124
+ fArg = eCount + Math.log10(value)
125
+ } else {
126
+ fArg = eCount + value - 1
127
+ if (fArg < 1) fArg = eCount + Math.log10(Math.pow(10, value))
128
+ }
129
+
130
+ if (highest === 1) {
131
+ // E level only: convert to F format
132
+ let bottom = value
133
+ let top = eCount
134
+ let height = 1
135
+ let repeat = eCount
136
+ if (top >= 2) {
137
+ height = 2
138
+ if (bottom < 1) {
139
+ bottom = Math.pow(10, bottom)
140
+ }
141
+ top = Math.floor(top)
142
+ repeat = 1
143
+ } else {
144
+ bottom = Math.pow(10, bottom - Math.floor(bottom))
145
+ top = Math.floor(top)
146
+ }
147
+ if (FORMAT_DEBUG >= 1) console.log("metaPolarize E level:", {bottom, top, height, repeat})
148
+ return {bottom, top, height, repeat}
149
+ }
150
+
151
+ // For mixed levels like FE20 or G10, the F argument is the value after E operations.
152
+ // Try to compute it directly (E^e(base) = 10^e * base for e=1, or tower for e>1).
153
+ let levelArg = fArg
154
+ let eOps = r0[1] || 0
155
+ let canCompute = false
156
+ if (eOps > 0) {
157
+ let eVal = r0[0]
158
+ canCompute = true
159
+ for (let i = 0; i < eOps; i++) {
160
+ eVal = Math.pow(10, eVal)
161
+ if (!isFinite(eVal) || eVal > 1e308) {
162
+ canCompute = false
163
+ break
164
+ }
165
+ }
166
+ if (canCompute) {
167
+ levelArg = eVal
168
+ }
169
+ // If not computable, levelArg stays as fArg (from E climbing)
170
+ }
171
+
172
+ let height = highest
173
+ let repeat = r0[highest] || 0
174
+
175
+ // Case 1: Directly computable(e.g., FE20) -> Don't climb the computed value, use it directly as the top argument.
176
+ if (canCompute) {
177
+ let bottom = 1.0
178
+ let top = levelArg
179
+ if (FORMAT_DEBUG >= 1) console.log("metaPolarize computable:", {bottom, top, height, repeat})
180
+ return {bottom, top, height, repeat}
181
+ }
182
+
183
+ // Case 2: Not computable ─> Check for the base=10^10 and all intermediate levels 8 (original argument was 10)
184
+ let all8 = (r0[0] === 10000000000)
185
+ for (let i = 2; i < highest && all8; i++) {
186
+ if ((r0[i] || 0) !== 8) all8 = false
187
+ }
188
+ if (all8) {
189
+ // The normalization collapses one level when the argument is 10
190
+ let bottom = 1.0
191
+ let top = 10
192
+ if (r0[highest] === 8) {
193
+ // Letter level not present (e.g., Z10 → Y^8(...E^8(10^10)...)): go up one level, repeat=1
194
+ height = highest + 1
195
+ repeat = 1
196
+ } else {
197
+ // Letter level present (e.g., ZZ(10) → Z(Y^8(...E^8(10^10)...))): add 1 for the base level
198
+ repeat = 1 + repeat
199
+ }
200
+ if (FORMAT_DEBUG >= 1) console.log("metaPolarize all-8s:", {bottom, top, height, repeat})
201
+ return {bottom, top, height, repeat}
202
+ }
203
+
204
+ // Case 3: General non-computable ─> Climb through intermediate levels to compute the argument at the highest level.
205
+ if (eOps > 0) {
206
+ for (let lv = 2; lv < highest; lv++) {
207
+ let cnt = r0[lv] || 0
208
+ let climbExtra = 0
209
+ while (levelArg >= 10) {
210
+ levelArg = Math.log10(levelArg)
211
+ climbExtra++
212
+ }
213
+ cnt += climbExtra
214
+ levelArg = cnt + Math.log10(Math.max(levelArg, 1))
215
+ }
216
+ }
217
+
218
+ // When the F argument was not computable and the highest level is F (level 2), the E→F conversion adds 1 to the effective F count.
219
+ if (highest === 2 && eOps > 0) {
220
+ repeat += 1
221
+ }
222
+
223
+ // Climb at the highest level to compute the total repeat count
224
+ let climbExtra = 0
225
+ let argVal = levelArg
226
+ while (argVal >= 10) {
227
+ argVal = Math.log10(argVal)
228
+ climbExtra++
229
+ }
230
+ let totalRepeat = repeat + climbExtra
231
+
232
+ // Compute bottom (mantissa) and top (argument) from the climbed argVal
233
+ let bottom
234
+ if (argVal < 1) {
235
+ bottom = Math.pow(10, argVal)
236
+ } else {
237
+ bottom = argVal
238
+ }
239
+ let top = Math.floor(levelArg)
240
+
241
+ if (FORMAT_DEBUG >= 1) console.log("metaPolarize high level:", {bottom, top, height, repeat: totalRepeat, levelArg, climbExtra})
242
+ return {bottom, top, height, repeat: totalRepeat}
243
+ }
244
+
245
+ // ─── Letter Name: Map height index to dlsdl's letter name ────────
246
+ // height 1 = E, 2 = F, ..., 22 = Z, 23 = Aa, 24 = Ab, ..., 48 = Az, 49 = Ba, ..., 698 = Zz, 699 = Aaa, ...
247
+ function letterName(height) {
248
+ if (height < 1) return "E"
249
+ if (height <= 22) {
250
+ // E = charCode 69, F = 70, ..., Z = 90
251
+ return String.fromCharCode(68 + height)
252
+ }
253
+
254
+ // Multi-letter: height >= 23 maps to the bijective base-26 sequence
255
+ let n = height - 23 // 0-based into multi-letter: 0=Aa, 1=Ab, ..., 25=Az, 26=Ba, ...
256
+
257
+ // Determine number of letters (starts at 2: Aa-Zz is 26*26 = 676 values)
258
+ let digits = 2
259
+ let rangeSize = 26 * 26
260
+ let offset = 0
261
+ while (n >= offset + rangeSize) {
262
+ offset += rangeSize
263
+ digits++
264
+ rangeSize *= 26
265
+ }
266
+
267
+ n -= offset
268
+ // n is now a base-26 number with 'digits' digits. First digit is uppercase (A-Z), rest are lowercase (a-z)
269
+ let result = ""
270
+ let divisor = Math.pow(26, digits - 1)
271
+ for (let i = 0; i < digits; i++) {
272
+ let digit = Math.floor(n / divisor)
273
+ n %= divisor
274
+ divisor /= 26
275
+ if (i === 0) {
276
+ result += String.fromCharCode(65 + digit) // A-Z
277
+ } else {
278
+ result += String.fromCharCode(97 + digit) // a-z
279
+ }
280
+ }
281
+ return result
282
+ }
283
+
284
+ // ─── Letter token with the multiLetterLimit symbol carry ──────────
285
+ // A k-letter combination (Aa, Aaa, …) sits at level ω^(k-1). Past multiLetterLimit switches to the symbol{index+1} form.
286
+ function letterTokenOf(height) {
287
+ let plain = letterName(height)
288
+ let limit = Math.max(2, FORMAT_OPTIONS.multiLetterLimit | 0)
289
+ if (plain.length <= limit) return { sym: "", letter: plain, arg: 0, mant: null }
290
+ // The carried form is "!" + the single-letter αΓβ: "!" adds one ω^ layer on top of Γ
291
+ let expo = plain.length - 1
292
+ if (expo >= 1 && expo <= 22) {
293
+ return { sym: "!", letter: letterName(expo), arg: expo, mant: 1, useBeta: true }
294
+ }
295
+ let mant = plain.charCodeAt(0) - 64 // coefficient of ω^(k-1)
296
+ for (let i = 1; i < plain.length; i++) {
297
+ mant += (plain.charCodeAt(i) - 97) * Math.pow(10, -i)
298
+ }
299
+ if (mant < 2) mant = 2 // diagonal [2,10) anchor
300
+ if (mant >= 10) mant = 9 + (mant - 10) / 170 // keep α ∈ [2,10)
301
+ return { sym: "!", letter: "Aa", arg: expo, mant: mant }
302
+ }
303
+
304
+ // Emit α·letter·β for a token: the plain form is αΓβ, the carried form is the symbol-first !αAaβ whose α is the definition mantissa and β the ω-exponent.
305
+ function emitLetterToken(tok, alphaStr, betaStr, precision) {
306
+ if (!tok.sym) return alphaStr + tok.letter + betaStr
307
+ let a = (tok.mant === null || tok.mant === undefined) ? alphaStr
308
+ : regularFormat(tok.mant, precision)
309
+ // the single-letter carried form keeps the caller's argument (!1H51), the Aa form carries the ω-exponent instead
310
+ if (tok.useBeta) return tok.sym + a + tok.letter + betaStr
311
+ return tok.sym + a + tok.letter + formatR0Arg(tok.arg, precision)
312
+ }
313
+
314
+ // ─── Symbol Name: Map layer to symbol ────────────────────────────
315
+ const SYMBOLS = "!@#$%&~<>?"
316
+ function symbolName(layer) {
317
+ if (layer <= 0) return ""
318
+ if (layer <= SYMBOLS.length) return SYMBOLS[layer - 1]
319
+ // For layers beyond SYMBOLS, formatLayer uses the ε format: αεβ
320
+ return ""
321
+ }
322
+
323
+ // ─── Ordinal Letter: Extract letter name from ordinal rows ───────
324
+ // Format A (3+ elements): [count, v1..vN, diag] — diag 1-26 (A-Z, uppercase), v1..vN 0-25 (a-z, lowercase), count = repetition count.
325
+ // Format B (2 elements): [count, value] — count at ω-level, value the ordinal level number (901 means ω*901); letter is always "Aa".
326
+ // Snap CNF coefficients (little-endian [a1..ak], ordinal ω^(k-1)·ak+…+a1) to the ones the letter grid can name: 0 ≤ ai ≤ 25, top ak ≤ 26.
327
+ // Larger coefficients carry UP (ω*2+96→ω*3(Ca), ω*99→ω²(Aaa), ω²*100→ω³(Aaaa)), so an unnamed ordinal displays as the next nameable one above it.
328
+ function snapCoeffsToGrid(coeffs) {
329
+ let r = (coeffs || []).slice()
330
+ // little-endian ORDINAL carry: index 0 is the constant term. A term above its grid bound absorbs everything below it
331
+ // and bumps the next power so the snapped ordinal is the TIGHTEST nameable ordinal above the original one.
332
+ for (let i = 0; i < r.length; i++) {
333
+ let c = r[i]
334
+ if (typeof c !== 'number' || !isFinite(c) || c < 0) { r[i] = 0; continue }
335
+ c = Math.round(c) // integer coefficients only
336
+ let bound = (i === r.length - 1) ? 26 : 25 // top may reach 26 (A-Z)
337
+ if (c <= bound) { r[i] = c; continue }
338
+ for (let j = 0; j <= i; j++) r[j] = 0 // the carry absorbs the tail
339
+ if (i === r.length - 1) r.push(1) // ω^k·(bound+1) → ω^(k+1)
340
+ else r[i + 1] = (r[i + 1] || 0) + 1 // … → ω^(i+1)·(+1)
341
+ // keep scanning: the bumped slot may carry in turn
342
+ }
343
+ while (r.length > 1 && r[r.length - 1] === 0) r.pop()
344
+ if (r.length === 0) r = [1]
345
+ return r
346
+ }
347
+
348
+ function getOrdinalLetter(ordRows) {
349
+ if (!ordRows || ordRows.length === 0) return null
350
+
351
+ // Check if all rows are 2-element [count, value] format (ω-level operations)
352
+ let allTwoElement = true
353
+ for (let i = 0; i < ordRows.length; i++) {
354
+ if (ordRows[i].length !== 2) { allTwoElement = false; break }
355
+ }
356
+ if (allTwoElement) {
357
+ return "Aa" // Base ω-level letter; value is handled in formatOrdinal
358
+ }
359
+
360
+ let tokens = []
361
+ // Process rows in REVERSE order (matching toString behavior)
362
+ for (let i = ordRows.length - 1; i >= 0; i--) {
363
+ let row = ordRows[i]
364
+ if (row.length < 2) continue
365
+ let diag = row[row.length - 1]
366
+ let vals = row.slice(1, row.length - 1)
367
+ let count = row[0] || 1
368
+
369
+ // Build letter name (reverse order: last val first, matching toString)
370
+ let letter = String.fromCharCode(64 + diag)
371
+ for (let j = vals.length - 1; j >= 0; j--) {
372
+ letter += String.fromCharCode(97 + vals[j])
373
+ }
374
+
375
+ for (let c = 0; c < count; c++) {
376
+ tokens.push(letter)
377
+ }
378
+ }
379
+
380
+ // Do NOT sort - rows are already in canonical order from normalize
381
+ return tokens.join("")
382
+ }
383
+
384
+ // ─── Reference Polarize (verbatim port of PowiainaNum's myPolarize) ──
385
+ // Recovers the display α ("bottom") and the diagonal level ("arrows") of an r0 chain STRUCTURALLY, climbing log10 level by level.
386
+ // The only method that stays exact at high levels where the engine's fractional-arg bisect quantizes (level ≥ 20).
387
+ function refPolarizeArraySort(array) {
388
+ array.sort(function (a, b) {
389
+ if (typeof a == 'number') return
390
+ else if (a[3] > b[3]) return -1
391
+ else if (a[3] < b[3]) return 1
392
+ else if (a[2] == 'x' && b[2] != 'x') return -1
393
+ else if (a[2] != 'x' && b[2] == 'x') return 1
394
+ else if (a[2] == 'x' && b[2] == 'x') return -1
395
+ else if (a[2] > b[2]) return -1
396
+ else if (a[2] < b[2]) return 1
397
+ else if (a[0] == 'x' && b[0] != 'x') return -1
398
+ else if (a[0] != 'x' && b[0] == 'x') return 1
399
+ else if (a[0] == 'x' && b[0] == 'x') return -1
400
+ else if (a[0] > b[0]) return -1
401
+ else if (a[0] < b[0]) return 1
402
+ else if (a[1] > b[1]) return -1
403
+ else if (a[1] < b[1]) return 1
404
+ return -1
405
+ })
406
+ }
407
+ function refPolarizeArrayMerge(array) {
408
+ let elemOffset = 0
409
+ for (let i = 0; i < array.length - 2; ++i) {
410
+ if (array[i][0] == array[i + 1][0] &&
411
+ array[i][2] == array[i + 1][2] &&
412
+ array[i][3] == array[i + 1][3]) {
413
+ array[i][1] += array[i + 1][1]
414
+ array.splice(i + 1, 1)
415
+ --i
416
+ elemOffset++
417
+ }
418
+ }
419
+ return elemOffset
420
+ }
421
+ // Our r0 + [count, level] finite rows → PowiainaNum's [base, [level, count, 1, 1]...]
422
+ // (their row level = our level verbatim: their 3{21}3 rows top at [20,1] and their polarize returns arrows 20, displayed "…20" — no off-by-one)
423
+ function refPolarizeInput(r0, finiteRows) {
424
+ let arr = [r0[0]]
425
+ for (let i = 1; i < r0.length; i++) {
426
+ if (r0[i] > 0) arr.push([i, r0[i], 1, 1])
427
+ }
428
+ if (finiteRows) {
429
+ for (let i = 0; i < finiteRows.length; i++) {
430
+ let fr = finiteRows[i]
431
+ if (fr && fr.length === 2 && fr[0] > 0) arr.push([fr[1], fr[0], 1, 1])
432
+ }
433
+ }
434
+ return arr
435
+ }
436
+ function refPolarize(array, hasOperationRepeat = true) {
437
+ refPolarizeArraySort(array)
438
+ refPolarizeArrayMerge(array)
439
+ let ptr = array.length - 2
440
+ let b = () => array[array.length - 1]
441
+ let c = (x) => { array[array.length - 1] = x }
442
+ let repeatResult = 1000001
443
+ while (--repeatResult >= 0) {
444
+ if (b() >= 10) {
445
+ let a = Math.log10(b())
446
+ array.push([1, 1, 1, 1])
447
+ ptr++
448
+ refPolarizeArraySort(array)
449
+ let offset = refPolarizeArrayMerge(array)
450
+ ptr -= offset
451
+ c(a)
452
+ } else {
453
+ if (ptr == 0 && typeof array[ptr + 1] == 'number' &&
454
+ (hasOperationRepeat || (!hasOperationRepeat && array[ptr][1] == 1))) break
455
+ if (ptr != 0 && typeof array[ptr + 1] == 'number' && typeof array[ptr][0] == 'number' &&
456
+ array[ptr][1] == 1 &&
457
+ (array[ptr - 1][0] == 'x' || array[ptr - 1][2] > array[ptr][2] || array[ptr - 1][3] > array[ptr][3]) &&
458
+ array[ptr][0] > 2 && (ptr != 0 || array[ptr - 1][0] == 'x')) {
459
+ let arrow_count = array[ptr][0]
460
+ let base = b()
461
+ let Jx
462
+ if (arrow_count == 3) Jx = base
463
+ else Jx = arrow_count - 1 + Math.log(base / 2) / Math.log(5)
464
+ array[ptr][0] = 'x'
465
+ c(Jx)
466
+ refPolarizeArraySort(array)
467
+ let offset = refPolarizeArrayMerge(array)
468
+ ptr -= offset
469
+ }
470
+ if (typeof array[ptr + 1] == 'number' && array[ptr][0] == 'x' && b() < 10 && ptr != 0) {
471
+ let base = b()
472
+ let JRepeation = array[ptr][1]
473
+ let Kx = JRepeation + Math.log10(base)
474
+ array[ptr][1] = 1
475
+ array[ptr][0] = 1
476
+ array[ptr][2]++
477
+ c(Kx)
478
+ refPolarizeArraySort(array)
479
+ let offset = refPolarizeArrayMerge(array)
480
+ ptr -= offset
481
+ }
482
+ if (((ptr == 0 && !hasOperationRepeat && array[ptr][1] != 1) || ptr != 0) &&
483
+ array[ptr][0] != 'x' && b() < 10) {
484
+ if (b() == 1 && ptr > 0 && array[ptr - 1][0] > array[ptr][0] && array[ptr][1] == 1) {
485
+ array[ptr][0] = array[ptr - 1][0]
486
+ } else {
487
+ let right = array[ptr][1] + Math.log10(b())
488
+ array[ptr][0]++
489
+ array[ptr][1] = 1
490
+ c(right)
491
+ }
492
+ refPolarizeArraySort(array)
493
+ let offset = refPolarizeArrayMerge(array)
494
+ ptr -= offset
495
+ }
496
+ }
497
+ }
498
+ return {
499
+ bottom: b(),
500
+ repeation: array[ptr][1],
501
+ arrows: array[ptr][0],
502
+ }
503
+ }
504
+ // Convert a finite-chain polarize triple (bottom, repeation, arrows) into the diagonal-letter display pair (mantissa, β).
505
+ // The value behaves as 10{arrows+1}(t), t = log10(bottom)+repeation; the diagonal convention is α = 2·5^f ∈ [2,10):
506
+ // t ∈ [1,2) -> mantissa 2·5^(t-1), β = arrows-1
507
+ // t ∈ [2,10) -> mantissa t, β = arrows (3{100}3 -> 2.376Aa99)
508
+ // t ≥ 10 -> one level per smooth-log step f → 1+log10(f); the anchor t=10 is mantissa 2 at β=arrows+1 (10{100}10 -> 2.000Aa100)
509
+ // Truncation marker: a truncated cascade resets r0 to [10] and bumps the lowest kept row's count by 1 over the uniform fill (xCnt) — read it as xCnt so truncated displays match the untruncated anchor.
510
+ function normalizedFiniteRows(r0, finiteRows) {
511
+ if (!finiteRows || finiteRows.length === 0 || r0[0] !== 10) return finiteRows
512
+ let sorted = finiteRows.slice().sort((a, b) => a[1] - b[1])
513
+ let c0 = sorted[0][0] || 0
514
+ let c1 = sorted.length > 1 ? (sorted[1][0] || 0) : 0
515
+ if (c0 === c1 + 1) {
516
+ let copy = finiteRows.slice()
517
+ for (let i = 0; i < copy.length; i++) {
518
+ if (copy[i][1] === sorted[0][1]) copy[i] = [c1, copy[i][1]]
519
+ }
520
+ return copy
521
+ }
522
+ return finiteRows
523
+ }
524
+
525
+ function aaDiagonalPair(pol) {
526
+ let t = Math.log10(pol.bottom) + pol.repeation
527
+ let beta = pol.arrows
528
+ // discrete integer argument (10{arrows+1}(t) with integer t): climb the raw count C=t-1 at level arrows;
529
+ // C ≤ 9 is the anchor band (one smooth application 10{arrows+1}2 … through arg 9) -> mantissa 2 at β=arrows+1
530
+ let discrete = Math.abs(pol.bottom - 1) < 1e-12 && pol.repeation === Math.floor(pol.repeation)
531
+ if (discrete && t - 1 <= 9 + 1e-9 && t >= 2) {
532
+ return { mant: 2, beta: pol.arrows + 1 }
533
+ }
534
+ if (t >= 9.999999999) {
535
+ // v = 10{arrows+1}(t) = {arrows}^{t-1}(10): the raw level-(arrows) application count is (t-1);
536
+ // run the geometric smooth-log climb from a scalar count all the way to the diagonal band at β = arrows+1.
537
+ let n = pol.arrows
538
+ let s = Math.log10(Math.max(t - 1, 1))
539
+ for (let level = 1; level < n + 2; level++) {
540
+ s = (s >= 9.999999999) ? 2 : 1 + Math.log10(s)
541
+ }
542
+ let mant = s < 2 ? 1 + s : s
543
+ return { mant: Math.min(mant, 10), beta: n + 1 }
544
+ }
545
+ if (t < 2) return { mant: 2 * Math.pow(5, t - 1), beta: beta - 1 }
546
+ // t in [2,10): genuinely smooth (fractional compact row, or a non-10 base fixed point such as 3{100}3 -> 2.376) is shown directly;
547
+ // the discrete integer-argument anchor case was handled at the top of the function.
548
+ return { mant: t, beta: beta }
549
+ }
550
+
551
+ // Structural α/diagonal recovery for a value whose finite-level chain (r0 cols + [count, level] rows) reaches the Aa diagonal region.
552
+ // Mirrors the reference convention: e.g. 3{100}3 → bottom 2.375812, arrows 99 ("2.376Aa99").
553
+ function polarizeFiniteChain(r0, finiteRows) {
554
+ try {
555
+ finiteRows = normalizedFiniteRows(r0, finiteRows)
556
+ let arr = refPolarizeInput(r0.slice(0), finiteRows)
557
+ if (arr.length === 1) return null
558
+ return refPolarize(arr, true)
559
+ } catch (e) {
560
+ return null
561
+ }
562
+ }
563
+
564
+ // ─── Main Format Function ────────────────────────────────────────
565
+
566
+ // Parse an already-formatted r0 argument back to a number (e.g. "1,000" → 1000, "1.000E1,000" → null: carries its own E structure)
567
+ function formatR0ArgStr(argStr) {
568
+ var s = String(argStr).replace(/,/g, "")
569
+ if (/^\d+(\.\d+)?$/.test(s)) return Number(s)
570
+ return null
571
+ }
572
+
573
+ // De-layered !Aa x instance: the shape [[x],[1,0×k,1]] with k = max(1, floor(x)), x >= 1.
574
+ // Per the README the display is the APPROXIMATE binary form !α'Aa'β' (β' = floor(x), α' = 2·5^(x−β') ∈ [2,10))
575
+ // the mantissa carries only FORMAT_OPTIONS digits, so the round-trip recovers x to that precision。
576
+ // An INTEGER x has α' = 2 exactly, and the binary spelling now denotes the ω^n diagonal cascade.
577
+ function formatBangAaValue(num, precision) {
578
+ if (num.sign !== 1 || num.layer !== 0) return null
579
+ let a = num.array
580
+ if (a.length !== 2 || a[0].length !== 1) return null
581
+ let x = a[0][0]
582
+ if (typeof x !== 'number' || !isFinite(x) || x < 2) return null
583
+ let row = a[1]
584
+ if (row.length < 3 || row[0] !== 1 || row[row.length - 1] !== 1) return null
585
+ for (let i = 1; i < row.length - 1; i++) if (row[i] !== 0) return null
586
+ let k = row.length - 2
587
+ if (k !== Math.max(1, Math.floor(x))) return null
588
+ if (x === Math.floor(x)) {
589
+ // integer anchor: the letter token A(a×k)x is the exact spelling
590
+ return "A" + "a".repeat(k) + formatR0Arg(x, precision)
591
+ }
592
+ let beta = Math.floor(x)
593
+ let mant = 2 * Math.pow(5, x - beta)
594
+ return "!" + regularFormat(mant, precision) + "Aa" + formatR0Arg(beta, precision)
595
+ }
596
+
597
+ // The full rule-3 cascade of 10{ω^n}10 (n ≥ 2) — the stored form of !Aa<n> A cheap shape pre-filter (base [10], full row budget, top row [8, 9×n])
598
+ // plus an exact comparison against the engine's own cascade, so nothing else matches. Displayed as the binary diagonal !2.000Aa<n>, which parses back to the same cascade.
599
+ function formatAaCascade(num, precision) {
600
+ if (num.sign !== 1 || num.layer !== 0) return null
601
+ let a = num.array
602
+ if (a.length !== MetaNum.maxRows || a.length < 3) return null
603
+ if (a[0].length !== 1 || a[0][0] !== 10) return null
604
+ let last = a[a.length - 1]
605
+ let n = last.length - 1
606
+ if (n < 2 || last[0] !== 8) return null
607
+ for (let i = 1; i < last.length; i++) if (last[i] !== 9) return null
608
+ let coeffs = []
609
+ for (let i = 0; i < n; i++) coeffs.push(0)
610
+ coeffs.push(1)
611
+ let ref = MetaNum._hyperopFromOrdinalRaw(MetaNum.TEN, MetaNum.TEN, coeffs)
612
+ if (!ref.eq(num)) return null
613
+ return "!" + regularFormat(2, precision) + "Aa" + formatR0Arg(n, precision)
614
+ }
615
+
616
+ function formatCore(num, precision=3, small=false) {
617
+ if (MetaNum.isNaN(num)) return "NaN"
618
+ let sciSigDigits = FORMAT_OPTIONS.sciSignificantDigits // for E notation
619
+ let sciPrecision = Math.max(sciSigDigits, precision)
620
+ let singlePrecision = FORMAT_OPTIONS.singleLetterDigits // for F, G, H, ...
621
+ let multiPrecision = FORMAT_OPTIONS.multiLetterDigits // for Aa and beyond
622
+ num = new MetaNum(num)
623
+ let array = num.array
624
+ let r0 = array[0]
625
+
626
+ // Basic edge cases
627
+ if (num.sign !== 2 && num.sign !== -2 && num.abs().lt(1e-308)) return (0).toFixed(precision)
628
+ if (num.sign < 0) return "-" + format(num.neg(), precision, small)
629
+ if (num.isInfinite()) return "Infinity"
630
+
631
+ // Sub-unit values (sign 2 / -2, 0 < |v| < 1): a plain finite r0 stores the RECIPROCAL, so the real value is 1/r0.
632
+ if ((num.sign === 2 || num.sign === -2) && num.layer === 0 &&
633
+ num.array.length === 1 && num.array[0].length === 1 &&
634
+ isFinite(num.array[0][0]) && num.array[0][0] !== 0) {
635
+ let realVal = 1 / num.array[0][0]
636
+ if (isFinite(realVal) && realVal > 0) {
637
+ let asNormal = num.clone()
638
+ asNormal.sign = 1
639
+ asNormal.array = [[realVal]]
640
+ num = asNormal
641
+ }
642
+ }
643
+
644
+ // Small value handling (e.g., 0.0000000001 → 1.000E-10 or 1.000E10⁻¹)
645
+ let smallThreshold = Math.pow(10, -FORMAT_OPTIONS.smallNotationThreshold)
646
+ if (num.lt(smallThreshold)) {
647
+ if (FORMAT_OPTIONS.smallNotationUseE) {
648
+ // Handle reciprocal values (sign=2/-2) that underflow to 0 in double precision
649
+ if (num.sign === 2 || num.sign === -2) {
650
+ var recipFmt = num.clone()
651
+ recipFmt.sign = recipFmt.sign === 2 ? 1 : -1
652
+ var prefix = num.sign === -2 ? "-" : ""
653
+ // Compute magnitude (log10 of reciprocal)
654
+ var mag = recipFmt.log10()
655
+ // Tier 1: mag is a simple number → αE-β format
656
+ if (mag.array.length === 1 && mag.array[0].length <= 2) {
657
+ var magNum = mag.toNumber()
658
+ if (isFinite(magNum) && magNum > 0) {
659
+ var frac = magNum - Math.floor(magNum)
660
+ var mant = Math.pow(10, frac)
661
+ var expPart = Math.floor(magNum)
662
+ if (mant < 1) { mant *= 10; expPart -= 1 }
663
+ if (mant >= 9.999999999999999) { mant = 1; expPart += 1 }
664
+ return prefix + regularFormat(mant, sciMantissaPrecision(expPart)) + "E-" + commaFormat(expPart)
665
+ }
666
+ }
667
+ // Tier 2: mag is large → "E-" + the letter-law form of mag, log10 shifts only the OUTERMOST letter.
668
+ var recipStr = format(recipFmt, precision, small)
669
+ var magStr = recipStr
670
+ // leading run of E letters (e.g. "EE1.000E1,000"): strip one E
671
+ var eRun = recipStr.match(/^(E+)(.*)$/)
672
+ var rm = recipStr.match(/^(\d(?:\.\d+)?)([A-Z])((?:\d[\d,]*)?)$/)
673
+ if (eRun && !rm) {
674
+ var restStr = eRun[2]
675
+ if (eRun[1].length >= 2) {
676
+ // "EE…" → "E…" (log10 of an E-chain drops one E)
677
+ magStr = eRun[1].slice(0, -1) + restStr
678
+ } else if (eRun[1].length === 1) {
679
+ // single "EαEβ" / "Eβ": log10 is the β part
680
+ var betaPart = restStr.replace(/^\d(?:\.\d+)?(?=[A-Z])/, "")
681
+ if (/^[A-Z]/.test(betaPart) || /^[\d,]/.test(betaPart)) magStr = betaPart
682
+ }
683
+ } else if (rm) {
684
+ var rAlpha = rm[1], rLetter = rm[2], rArg = rm[3]
685
+ if (rLetter === "E" && rArg !== "") {
686
+ // E-chain with numeric arg (E200): log10 keeps E-arg
687
+ magStr = rAlpha + "E" + rArg
688
+ } else if (rLetter === "F" && rArg !== "") {
689
+ // F-chain: arg −1
690
+ magStr = rAlpha + "F" + commaFormat(Math.max(0, Number(rArg.replace(/,/g, "")) - 1))
691
+ }
692
+ // G and above: display unchanged
693
+ }
694
+ return prefix + "E-" + magStr
695
+ }
696
+ // Format as aE-b (e.g., 0.0000000001 → 1.000E-10)
697
+ let nVal = num.toNumber()
698
+ if (nVal > 0 && isFinite(nVal)) {
699
+ let logVal = Math.log10(nVal)
700
+ let m = Math.pow(10, logVal - Math.floor(logVal))
701
+ let e = Math.abs(Math.floor(logVal))
702
+ // Normalize: ensure m in [1, 10)
703
+ if (m < 1) { m *= 10; e -= 1 }
704
+ if (m >= 9.999999999999999) { m = 1; e += 1 }
705
+ return regularFormat(m, sciMantissaPrecision(e)) + "E-" + commaFormat(e)
706
+ }
707
+ // Fallback for non-simple values: use ⁻¹ notation
708
+ if (num.layer === 0 && num.array.length === 1 && num.array[0].length === 1) {
709
+ var val = num.array[0][0]
710
+ if (val > 0) {
711
+ var recipVal = 1 / val
712
+ if (isFinite(recipVal)) {
713
+ return format(new MetaNum(recipVal), precision, small) + "⁻¹"
714
+ }
715
+ }
716
+ }
717
+ return format(num.rec(), precision, small) + "⁻¹"
718
+ } else {
719
+ // Traditional ⁻¹ notation
720
+ if (num.sign === 2 || num.sign === -2) {
721
+ // Already in small representation (sign=2), toggle sign to get reciprocal
722
+ var recipSmall = num.clone()
723
+ recipSmall.sign = recipSmall.sign === 2 ? 1 : -1
724
+ return format(recipSmall, precision, small) + "⁻¹"
725
+ }
726
+ // Normal representation but value < 1 (e.g., 0.0000000001 stored as [[1e-10]]), Compute reciprocal properly: 1/val
727
+ if (num.layer === 0 && num.array.length === 1 && num.array[0].length === 1) {
728
+ var val = num.array[0][0]
729
+ if (val > 0) {
730
+ var recipVal = 1 / val
731
+ if (isFinite(recipVal)) {
732
+ return format(new MetaNum(recipVal), precision, small) + "⁻¹"
733
+ }
734
+ }
735
+ }
736
+ // Fallback
737
+ return format(num.rec(), precision, small) + "⁻¹"
738
+ }
739
+ }
740
+
741
+ if (num.lt(1)) return regularFormat(num, FORMAT_OPTIONS.decimalPlaces + (small ? 2 : 0))
742
+ if (num.lt(1000)) return regularFormat(num, FORMAT_OPTIONS.decimalPlaces)
743
+
744
+ // Check decimal threshold: if value >= 10^decimalThreshold, don't show decimals
745
+ let useDecimals = true
746
+ if (FORMAT_OPTIONS.decimalThreshold > 0) {
747
+ let thresholdVal = Math.pow(10, FORMAT_OPTIONS.decimalThreshold)
748
+ if (num.gte(thresholdVal)) useDecimals = false
749
+ }
750
+
751
+ if (num.lt(Math.pow(10, FORMAT_OPTIONS.sciThreshold))) {
752
+ if (useDecimals) return regularFormat(num, FORMAT_OPTIONS.decimalPlaces)
753
+ else return commaFormat(num)
754
+ }
755
+
756
+ // ── Handle layer > 0 (symbol notation: !, @, #, ..., ε) ──
757
+ if (num.layer > 0) {
758
+ return formatLayer(num, precision, sciPrecision, singlePrecision, multiPrecision)
759
+ }
760
+
761
+ // ── Handle ordinal rows (Aa, Ab, ..., Aaa, ... range) ──
762
+ let hasOrdinalRows = array.length > 1
763
+ if (hasOrdinalRows) {
764
+ let bang = formatBangAaValue(num, multiPrecision)
765
+ if (bang !== null) return bang
766
+ // The full 10{ω^n}10 cascade (stored !Aa<n>) — display the binary diagonal so the parser round-trips it
767
+ let cascade = formatAaCascade(num, multiPrecision)
768
+ if (cascade !== null) return cascade
769
+ return formatOrdinal(num, precision, multiPrecision)
770
+ }
771
+
772
+ // ── r0-only: scientific notation, E-Z range ──
773
+ let maxLevel = 0
774
+ for (let i = 1; i < r0.length; i++) {
775
+ if (r0[i] > 0) maxLevel = i
776
+ }
777
+
778
+ // ── Handle r0-only with maxLevel >= 23: Aa-diagonal──
779
+ // The cascade collapses to αAaβ with (bottom, repeation, arrows) from polarizeFiniteChain (the structural climb), mantissa normalized into [1,10) carrying decades into β.
780
+ if (maxLevel >= 23) {
781
+ let pol = polarizeFiniteChain(r0.slice(0), null)
782
+ if (pol && isFinite(pol.bottom) && pol.bottom > 0 && isFinite(pol.arrows)) {
783
+ let pair = aaDiagonalPair(pol)
784
+ return regularFormat(pair.mant, multiPrecision) + "Aa" + commaFormat(pair.beta)
785
+ }
786
+ // fallback: legacy base-9 coefficient form
787
+ let coeff = r0[maxLevel]
788
+ let pow9 = 9
789
+ for (let i = maxLevel - 1; i >= 1; i--) {
790
+ coeff += (r0[i] || 0) / pow9
791
+ pow9 *= 9
792
+ }
793
+ let level = maxLevel
794
+ while (coeff >= 9) {
795
+ coeff /= 9
796
+ level++
797
+ }
798
+ // Format coefficient: if close to integer, show as integer
799
+ let coeffVal
800
+ if (Math.abs(coeff - Math.round(coeff)) < 1e-12 && Math.round(coeff) <= Number.MAX_SAFE_INTEGER) {
801
+ coeffVal = Math.round(coeff)
802
+ } else {
803
+ coeffVal = coeff
804
+ }
805
+ return regularFormat(coeffVal, multiPrecision) + "Aa" + commaFormat(level)
806
+ }
807
+
808
+ // ── All other r0-only cases: use the recursive chain builder ──
809
+ return formatR0AsChain(r0.slice(0), sciPrecision)
810
+ }
811
+
812
+ // ─── Format with Layer (symbol notation) ─────────────────────────
813
+
814
+ function formatLayer(num, precision, precision2, precision3, precision4) {
815
+ let sym = symbolName(num.layer)
816
+
817
+ // Create a layer-down version for the inner format
818
+ let inner = num.clone()
819
+ inner.layer = 0
820
+ inner.normalize()
821
+
822
+ // Check if inner de-layered to a "!Aa-like" form (all a's in ordinal)
823
+ // If the ordinal row is [count, 0, 0, ..., 0, diag] and r0[0] equals the number of zeros, we can format compactly as !Aa[r0[0]] (per README: !Aaα = (10^frac(α),0,...,0)|10 with int(α) zeros)
824
+ let canCompact = false
825
+ let compactBase = 0
826
+ if (inner.array.length > 1) {
827
+ let lastRow = inner.array[inner.array.length - 1]
828
+ let diag = lastRow[lastRow.length - 1]
829
+ let vals = lastRow.slice(1, lastRow.length - 1)
830
+ let allZero = vals.every(v => v === 0)
831
+ let base = inner.array[0][0]
832
+ // Compact form only applies when diag=1 (A), all vals are 0, and r0[0] equals the number of zeros
833
+ if (allZero && inner.array[0].length === 1 && diag === 1 && base === vals.length) {
834
+ canCompact = true
835
+ compactBase = base
836
+ }
837
+ }
838
+
839
+ // For layers beyond the explicit symbols, use the ε format: αεβ, ε represents exponent tower layers of ω: αεβ ~ f_ω^ω^...^ω(β ω's)_(α)
840
+ // This check must come before the compact !Aa form, otherwise ε layers get mis-rendered as "Aa..." (e.g. 1ε500 → "1.000Aa10")
841
+ if (num.layer > SYMBOLS.length) {
842
+ let epsPrecision = FORMAT_OPTIONS.epsilonSignificantDigits | 0
843
+ if (canCompact && compactBase >= 2 && Math.floor(compactBase) === compactBase) {
844
+ // Compact Aa form at ε layers folds into one more ε level: layer n + Aa-form ≡ ε(n+1) with mantissa 10^frac(compactBase)
845
+ let bottom = Math.pow(10, compactBase - Math.floor(compactBase))
846
+ return regularFormat(bottom, epsPrecision) + "ε" + commaFormat(num.layer + 1)
847
+ }
848
+ let innerStr = format(inner, epsPrecision, false)
849
+ return innerStr + "ε" + commaFormat(num.layer)
850
+ }
851
+
852
+ // The 10{ω^n}10 cascade at a symbol layer — the stored form of @Aa<n> (layer 1), #Aa<n> (layer 2), index is the total ω^-layer count.
853
+ let cascadeStr = formatAaCascade(inner, precision4)
854
+ if (cascadeStr !== null) {
855
+ let body = cascadeStr.slice(1) // strip the layer-0 "!"
856
+ if (num.layer < SYMBOLS.length) return SYMBOLS[num.layer] + body
857
+ return body + "ε" + commaFormat(num.layer + 1)
858
+ }
859
+
860
+ // Compact diagonal: the symbol row [1,0…0,1] with m=compactBase zeros is 10{ω^m}10 — a DIAGONAL letter (A + m a's) at argument 10, with the pure dlsdl α=2·5^f ∈ [2,10) convention.
861
+ // For layers above ! the symbol of the layer below prefixes the same inner form (!Aa3 = 2.000Aaaa10, @Aa3 = !2.000Aaaa10).
862
+ if (canCompact && compactBase >= 2) {
863
+ let mInt = Math.floor(compactBase)
864
+ let frac = compactBase - mInt
865
+ let mant = 2 * Math.pow(5, frac)
866
+ // Past multiLetterLimit the old single-letter carry (!1.000N10) did not round-trip — it added a layer and could not name the exact diagonal.
867
+ // Keep the exact A(a×m)10 token while the string stays reasonable; only fall back to the carry past a hard safety cap.
868
+ if (mInt <= MULTI_TOKEN_CAP) {
869
+ return symbolName(num.layer) + regularFormat(mant, precision4) +
870
+ "A" + "a".repeat(mInt) + "10"
871
+ }
872
+ // Hard-cap fallback: keep the argument (10 for a compact diagonal) but the level is the historical single-letter carry approximation.
873
+ let total = num.layer + 1
874
+ let body = regularFormat(1, precision4) + letterName(mInt) +
875
+ formatR0Arg(10, precision4)
876
+ if (total <= SYMBOLS.length) return SYMBOLS[total - 1] + body
877
+ return body + "ε" + commaFormat(total)
878
+ }
879
+
880
+ // For !, @, #, $, %, &, ~, <, >, ? symbols: prefix the symbol.
881
+ // When the inner display itself had to carry (its letter exceeded multiLetterLimit) the symbols stack instead of doubling: layer 1 + inner "!…" → "@…".
882
+ let innerStr = format(inner, precision, false)
883
+ if (innerStr.length > 1 && SYMBOLS.indexOf(innerStr[0]) >= 0) {
884
+ let total = num.layer + 1
885
+ if (total <= SYMBOLS.length) return SYMBOLS[total - 1] + innerStr.slice(1)
886
+ return innerStr.slice(1) + "ε" + commaFormat(total)
887
+ }
888
+ return sym + innerStr
889
+ }
890
+
891
+ // ─── Option-driven mantissa precisions ───────────────────────────
892
+ // Decimal places of the mantissa α in an αEβ form = sciSignificantDigits
893
+ // When β reaches 10^sciDecimalThreshold only the integer part of α is shown (the low digits carry no information at that height).
894
+ function sciMantissaPrecision(exponent) {
895
+ let t = FORMAT_OPTIONS.sciDecimalThreshold | 0
896
+ if (t > 0 && isFinite(exponent) && exponent >= Math.pow(10, t)) return 0
897
+ return FORMAT_OPTIONS.sciSignificantDigits | 0
898
+ }
899
+ // Decimal places of the mantissa α in αΓβ: E → sciSignificantDigits, F..Z → singleLetterDigits, Aa and beyond → multiLetterDigits.
900
+ function letterMantissaPrecision(level) {
901
+ if (level <= 1) return FORMAT_OPTIONS.sciSignificantDigits | 0
902
+ if (level <= 22) return FORMAT_OPTIONS.singleLetterDigits | 0
903
+ return FORMAT_OPTIONS.multiLetterDigits | 0
904
+ }
905
+
906
+ // ─── Format r0 Argument (plain number) ───────────────────────────
907
+ // Formats a plain numeric argument as either a plain number or αEβ notation. The mantissa α is always shown (even when 1.000).
908
+ function formatR0Arg(value, precision) {
909
+ if (!isFinite(value) || isNaN(value)) return "NaN"
910
+ if (value < Math.pow(10, FORMAT_OPTIONS.sciThreshold)) {
911
+ // Small argument: use comma format (integer, no decimals)
912
+ return commaFormat(value)
913
+ }
914
+ let logVal = Math.log10(value)
915
+ let m = Math.pow(10, logVal - Math.floor(logVal))
916
+ let e = Math.floor(logVal)
917
+ // Normalize mantissa into [1, 10)
918
+ if (m < 1) { m *= 10; e -= 1 }
919
+ if (m >= 9.999999999999999) { m = 1; e += 1 }
920
+ // Always show mantissa (αEβ format, e.g. 1.000E700)
921
+ return regularFormat(m, sciMantissaPrecision(e)) + "E" + commaFormat(e)
922
+ }
923
+
924
+ // ─── Gamma-Arg Recovery ─────────────────────────────────────────
925
+ // Recover the real argument x with 10{level}x = v (the Γ-canonical argument of v at letter `level`) by bisection on the engine's smooth arrow curve.
926
+ function gammaArgOf(v, level, iters) {
927
+ if (iters === undefined) iters = 60
928
+ let G = function (x) { return MetaNum(10).arrow(level)(x) }
929
+ // v must sit inside [Γ(1), Γ(HUGE)]: find integer hi with Γ(hi) >= v
930
+ let lo = 1, hi = 2
931
+ let guard = 0
932
+ while (G(hi).lt(v)) {
933
+ lo = hi
934
+ hi *= 2
935
+ if (++guard > 200) return null
936
+ }
937
+ // bisect the fractional part
938
+ for (let i = 0; i < iters; i++) {
939
+ let mid = (lo + hi) / 2
940
+ if (G(mid).lt(v)) lo = mid; else hi = mid
941
+ if (hi - lo < 1e-12) break
942
+ }
943
+ return lo
944
+ }
945
+
946
+ // Format a recovered Γ-argument x as the binary form αΓβ: α = 10^frac(x) (in [1, 10)), β = floor(x) (may itself carry E notation).
947
+ // Once β ≥ 10^sciThreshold the α only perturbs β by log10(α) < 1.
948
+ function formatGammaBinary(x, level, precision) {
949
+ let sciBound = Math.pow(10, FORMAT_OPTIONS.sciThreshold)
950
+ let beta = Math.floor(x + 1e-12)
951
+ let frac = x - beta
952
+ if (frac < 0) { frac += 1; beta -= 1 }
953
+ if (frac >= 1) { frac -= 1; beta += 1 }
954
+ if (beta >= sciBound) {
955
+ let alpha = Math.pow(10, frac)
956
+ return letterName(level) + formatR0Arg(beta + Math.log10(alpha), precision)
957
+ }
958
+ if (frac < 1e-9) {
959
+ // exact integer argument: bare letter + β
960
+ return letterName(level) + formatR0Arg(beta, precision)
961
+ }
962
+ let alpha = Math.pow(10, frac)
963
+ if (alpha >= 10 - 1e-6) { // 9.99999… rounds up to the next integer
964
+ alpha = 1
965
+ beta += 1
966
+ return letterName(level) + formatR0Arg(beta, precision)
967
+ }
968
+ return regularFormat(alpha, letterMantissaPrecision(level)) + letterName(level) + formatR0Arg(beta, precision)
969
+ }
970
+
971
+ // Distinct letter types in a display string: single-uppercase letters and Aa-style multi-letter tokens.
972
+ function distinctLetterTypes(str) {
973
+ let stripped = String(str).replace(/(\d(?:\.\d+)?)E(\d[\d,]*)/g, "$1$2")
974
+ let tokens = stripped.match(/[A-Z][a-z]*/g) || []
975
+ let seen = {}
976
+ let out = []
977
+ for (let i = 0; i < tokens.length; i++) {
978
+ if (!seen[tokens[i]]) { seen[tokens[i]] = true; out.push(tokens[i]) }
979
+ }
980
+ return out
981
+ }
982
+
983
+ // ─── Format r0 as Chain ────────────────────────────────────────
984
+ // Formats r0 = [base, e, f, g, ...] as a dlsdl chain: outerLetters + α + lastLetter + β, with α = 10^(base-floor(base)) and β = floor(base).
985
+ // A letter ending in "a" is a diagonal letter (Aa = ω, Ba = ω·2, Aaa = ω², …) and its binary form uses α = 2·5^f ∈ [2,10).
986
+ function diagonalMantissa(letter, mantissa) {
987
+ if (letter && letter.charAt(letter.length - 1) === 'a') {
988
+ let f = mantissa - Math.floor(mantissa)
989
+ if (!(f >= 0 && f < 1)) f = 0
990
+ return 2 * Math.pow(5, f)
991
+ }
992
+ let mantVal = Math.pow(10, mantissa - Math.floor(mantissa))
993
+ if (mantVal < 1) mantVal *= 10
994
+ return mantVal
995
+ }
996
+
997
+ // `used` = how many copies of the letter the caller already emitted: an inner level may only promote to the next letter while the total stays within repeatLetterThreshold.
998
+ function formatR0AsChainRaw(r0, precision, used) {
999
+ if (r0.length === 0) r0 = [0]
1000
+ let usedCount = used || 0
1001
+
1002
+ // Find maxLevel (highest non-zero index in r0[1..])
1003
+ let maxLevel = 0
1004
+ for (let i = r0.length - 1; i >= 1; i--) {
1005
+ if (r0[i] > 0) { maxLevel = i; break }
1006
+ }
1007
+
1008
+ if (maxLevel === 0) {
1009
+ return formatR0Arg(r0[0], precision)
1010
+ }
1011
+
1012
+ let count = r0[maxLevel]
1013
+ let effThreshold = Math.max(2, FORMAT_OPTIONS.repeatLetterThreshold)
1014
+
1015
+ // Detect a descending run of count-1 letters (e.g. the VUTS…G chain that the engine produces for arrow(3,19,3) = 3{19}3).
1016
+ // Such a chain is the diagonalized expansion of the top letter applied twice, so it must be compressed to the ΓαΓβ binary form instead of being spelled out.
1017
+ let runLen = 0
1018
+ if (count === 1) {
1019
+ runLen = 1
1020
+ while (maxLevel - runLen >= 2 && r0[maxLevel - runLen] === 1) runLen++
1021
+ }
1022
+
1023
+ // ≤2-letter-types rule: when the full spelling would use MORE than two letter types, spell only the top two levels' letters and compress everything below into the second letter's binary-canonical form.
1024
+ // 3{9}3 → "L2.376K2", 3{10}3 → "M2.376L2", 4{9}4 → "LLK3.550K3", 5{9}5 → "LLLKK4.669K4".
1025
+ // A top count ≥ repeatLetterThreshold+1 carries to the next single letter (6{9}6 → "5.760M5").
1026
+ if (maxLevel >= 2 && maxLevel <= 22 && count <= effThreshold) {
1027
+ let spellTypes = 0
1028
+ for (let s = 2; s <= maxLevel; s++) {
1029
+ if ((r0[s] || 0) > 0) spellTypes++
1030
+ }
1031
+ if (spellTypes > 2) {
1032
+ let second = 0
1033
+ for (let s = maxLevel - 1; s >= 2; s--) {
1034
+ if (r0[s] > 0) { second = s; break }
1035
+ }
1036
+ if (second >= 2) {
1037
+ let c2 = r0[second]
1038
+ if (c2 <= effThreshold) {
1039
+ let restR0 = r0.slice(0)
1040
+ restR0[maxLevel] = 0
1041
+ let pol = polarizeFiniteChain(restR0, null)
1042
+ if (pol && pol.arrows === second && isFinite(pol.bottom) &&
1043
+ pol.bottom >= 1 && isFinite(pol.repeation)) {
1044
+ let prefix = letterName(maxLevel).repeat(count) +
1045
+ letterName(second).repeat(Math.max(c2 - 1, 0))
1046
+ return prefix + regularFormat(pol.bottom, precision) +
1047
+ letterName(second) + commaFormat(pol.repeation)
1048
+ }
1049
+ }
1050
+ }
1051
+ }
1052
+ }
1053
+
1054
+ if (count <= effThreshold && runLen <= effThreshold) {
1055
+ // Non-collapse: peel off one letter at maxLevel, recurse on inner. Long descending count-1 runs (runLen > threshold) fall through to the Γ-canonical collapse below.
1056
+ let innerR0 = r0.slice(0)
1057
+ innerR0[maxLevel] = count - 1
1058
+ if (innerR0[maxLevel] === 0) {
1059
+ innerR0 = innerR0.slice(0, maxLevel)
1060
+ }
1061
+ let innerStr = formatR0AsChain(innerR0, precision, usedCount + 1)
1062
+
1063
+ // null = the inner level would need one more copy of the outer letter than repeatLetterThreshold allows
1064
+ // (3{3}6 = FFF(E^7.6e12) would spell a fourth F, falls through to the Γ-canonical collapse below, which renders the whole value at the next letter by its real argument: "2.045G5").
1065
+ if (innerStr !== null) {
1066
+ // Check if innerStr already has letters (meaning deeper operations exist)
1067
+ let hasLetter = /[A-Z]/.test(innerStr)
1068
+
1069
+ if (!hasLetter) {
1070
+ // innerStr is a plain number: this is the innermost operation Format: α + letterName(maxLevel) + innerStr
1071
+ let base = r0[0]
1072
+ let alpha = Math.pow(10, base - Math.floor(base))
1073
+ if (alpha < 1) alpha *= 10
1074
+ // an E letter's αEβ obeys sciDecimalThreshold: β ≥ 10^n → α keeps only its integer part
1075
+ let mantPrec = (maxLevel === 1)
1076
+ ? sciMantissaPrecision(Number(String(innerStr).replace(/,/g, '')))
1077
+ : letterMantissaPrecision(maxLevel)
1078
+ let alphaStr = regularFormat(alpha, mantPrec)
1079
+ return alphaStr + letterName(maxLevel) + innerStr
1080
+ } else {
1081
+ // innerStr already has α and letters: just prepend the outer letter
1082
+ return letterName(maxLevel) + innerStr
1083
+ }
1084
+ }
1085
+ if (usedCount > 0) return null
1086
+ }
1087
+
1088
+ // count > effThreshold and the promotion would exceed repeatLetterThreshold copies of the letter in front of it: signal the caller (the structural spelling is impossible) instead of spelling an extra copy.
1089
+ if (usedCount + 1 > effThreshold) {
1090
+ return null
1091
+ }
1092
+
1093
+ // count >= effThreshold: promote to next level (maxLevel + 1) Check for the all-8s pattern: base = 10^10 and every level 1..maxLevel-1 equals 8
1094
+ let all8 = (r0[0] === 10000000000)
1095
+ for (let i = 1; i < maxLevel && all8; i++) {
1096
+ if ((r0[i] || 0) !== 8) all8 = false
1097
+ }
1098
+
1099
+ // sciThreshold boundary: once the top-level argument reaches 10^sciThreshold, the binary form αΓβ = Γ(β+log α) renders the argument in its own canonical form
1100
+ let sciBound = Math.pow(10, FORMAT_OPTIONS.sciThreshold)
1101
+
1102
+ if (all8) {
1103
+ // all-8s promotion: E^count(10^10) → F(count+2), F^count(F10) → G(count+2), etc.
1104
+ let arg = count + 2
1105
+ let level = maxLevel + 1
1106
+ let letter = letterName(level)
1107
+ if (level >= 23) {
1108
+ // Promotion into a diagonal letter: the all-8s r0 is the exact diagonal 10{L+1}10 = Aa(L+1), whose dlsdl binary form anchors mantissa 2 (α=2·5^0): 10{23}10 -> "2.000Aa23".
1109
+ return regularFormat(2.0, precision) + "Aa" + commaFormat(maxLevel + 1)
1110
+ }
1111
+ if (arg >= sciBound) {
1112
+ // Γ(β) with β ≥ 10^sciThreshold: bare letter + canonical argument
1113
+ return letter + formatR0Arg(arg, precision)
1114
+ }
1115
+ // Format: α + letter + β (always show α)
1116
+ let alpha = Math.pow(10, arg - Math.floor(arg))
1117
+ if (alpha < 1) alpha *= 10
1118
+ let alphaStr = regularFormat(alpha, letterMantissaPrecision(level))
1119
+ let betaStr = formatR0Arg(Math.floor(arg), precision)
1120
+ return alphaStr + letter + betaStr
1121
+ }
1122
+
1123
+ // ── Γ-canonical recovery (2-letter rule) ──
1124
+ // 1. structural top count < threshold AND inner top < maxLevel: keep the top letter Γᵀ bare and format the inner chain recursively at most 2 letter types.
1125
+ // 2. otherwise collapse to the single letter Γ = the HIGHEST level whose recovered argument is ≥ 2, in binary form αΓβ.
1126
+ let r0Num = new MetaNum({ sign: 1, layer: 0, array: [r0.slice(0)] })
1127
+
1128
+ if (count < effThreshold && maxLevel >= 2 && runLen <= effThreshold) {
1129
+ // (a) structural top letter: peel ONE op of level maxLevel and format the inner chain recursively, exact even when the argument itself is letter-structured.
1130
+ // e.g. arrow(3,4.1,3) = G(F^895-chain) → "G" + format(F^895-chain) = "G1.161G897")
1131
+ let innerR0 = r0.slice(0)
1132
+ innerR0[maxLevel] = count - 1
1133
+ if (innerR0[maxLevel] === 0) {
1134
+ innerR0 = innerR0.slice(0, maxLevel)
1135
+ }
1136
+ let innerStr = formatR0AsChain(innerR0, precision, true)
1137
+ let hasLetter = /[A-Z]/.test(innerStr)
1138
+ if (!hasLetter) {
1139
+ let base = r0[0]
1140
+ let alpha = Math.pow(10, base - Math.floor(base))
1141
+ if (alpha < 1) alpha *= 10
1142
+ return regularFormat(alpha, letterMantissaPrecision(maxLevel)) + letterName(maxLevel) + innerStr
1143
+ }
1144
+ // inner carries letters: bare outer letter (2-letter rule) — the inner top must be LOWER (descending chain); ascending or same-level chains fall through to collapse
1145
+ let innerTop = 0
1146
+ for (let it = innerR0.length - 1; it >= 1; it--) {
1147
+ if (innerR0[it] > 0) { innerTop = it; break }
1148
+ }
1149
+ if (innerTop < maxLevel) {
1150
+ // ≤2 letter types rule: count the distinct letter types the peeled prefix + innerStr would use. If the inner chain spells a THIRD type, collapse it to the binary form.
1151
+ let topLetter = letterName(maxLevel)
1152
+ let innerTypes = distinctLetterTypes(innerStr)
1153
+ if (innerTypes.length >= 2
1154
+ && innerTypes.indexOf(topLetter) < 0
1155
+ && innerTypes.indexOf(letterName(innerTop)) < 0) {
1156
+ // inner already uses its own 2 types: cannot keep the structural letter — collapse below
1157
+ } else {
1158
+ let wouldTypes = {}
1159
+ wouldTypes[topLetter] = true
1160
+ for (let wt = 0; wt < innerTypes.length; wt++) wouldTypes[innerTypes[wt]] = true
1161
+ if (Object.keys(wouldTypes).length <= 2) {
1162
+ return letterName(maxLevel) + innerStr
1163
+ }
1164
+ // 3rd type would appear: collapse the inner chain to the binary form at innerTop — arg recovered on the engine curve when possible (level < 20), else structurally via refPolarize
1165
+ let innerNum = new MetaNum({ sign: 1, layer: 0, array: [innerR0.slice(0)] })
1166
+ let bx = (innerTop <= 19) ? gammaArgOf(innerNum, innerTop, 40) : null
1167
+ if (bx !== null && isFinite(bx) && bx >= 2) {
1168
+ return letterName(maxLevel) + formatGammaBinary(bx, innerTop, precision)
1169
+ }
1170
+ let pol2 = polarizeFiniteChain(innerR0, null)
1171
+ if (pol2 && pol2.arrows >= 2 && pol2.arrows <= 22) {
1172
+ let aStr = regularFormat(Math.max(pol2.bottom, 1.0001), precision)
1173
+ return letterName(maxLevel) + aStr + letterName(pol2.arrows) + commaFormat(pol2.repeation)
1174
+ }
1175
+ // polarize reached the multi-letter region: Aa-diagonal form
1176
+ if (pol2 && pol2.arrows >= 23) {
1177
+ let aStr = regularFormat(Math.max(pol2.bottom, 1.0001), precision)
1178
+ return letterName(maxLevel) + aStr + "Aa" + commaFormat(pol2.arrows)
1179
+ }
1180
+ }
1181
+ }
1182
+ }
1183
+
1184
+ // (b) collapse: the structural chain (n repeats of the top letter Γᵀ on an inner value whose canonical letter is Γᵀ⁺¹, e.g. F^895(G(2.06))) compresses to ONE Γᵀ⁺¹ with arg+n
1185
+ // bisect at the structural next letter first (maxLevel+1); if its arg falls below 2, search upward for the highest level whose arg ≥ 2 (hardy(4166) → "2.397G5").
1186
+ let structuralNext = Math.min(maxLevel + 1, 22)
1187
+ let sx = gammaArgOf(r0Num, structuralNext, 40)
1188
+ if (sx !== null && isFinite(sx) && sx >= 2) {
1189
+ return formatGammaBinary(sx, structuralNext, precision)
1190
+ }
1191
+ for (let lv = 22; lv >= 2; lv--) {
1192
+ if (lv === structuralNext) continue
1193
+ let x = gammaArgOf(r0Num, lv, 40)
1194
+ if (x !== null && isFinite(x) && x >= 2) {
1195
+ return formatGammaBinary(x, lv, precision)
1196
+ }
1197
+ }
1198
+
1199
+ // Γ-arg not recoverable as a double (arg beyond bisect range): fall back to metaPolarize for the polarized form
1200
+ let pol = metaPolarize(r0.slice(0), r0Num)
1201
+ let h = pol.height
1202
+ let rep = pol.repeat || 1
1203
+ let top = pol.top
1204
+ let bottom = pol.bottom
1205
+
1206
+ if (runLen > effThreshold) {
1207
+ // The descending count-1 run is the diagonalized expansion of the top letter applied twice: force the ΓαΓβ form
1208
+ rep = 2
1209
+ h = maxLevel
1210
+ }
1211
+
1212
+ // Convert repeated letters to next level when over threshold
1213
+ if (rep > 1 && rep >= effThreshold) {
1214
+ let newH = h + 1
1215
+ let newTop = rep + 1
1216
+ let newLetter = letterName(newH)
1217
+ if (newTop >= sciBound) {
1218
+ // bare letter + canonical argument (single α at the innermost value)
1219
+ return newLetter + formatR0Arg(newTop + Math.log10(bottom < 1 ? Math.pow(10, bottom) : bottom), precision)
1220
+ }
1221
+ // Format: α + letter + β. Canonical all-8s arrays (from the 10^10 base: G600, ZZ10, …) carry no recoverable mantissa below 10^10, so α = 1.000 by construction;
1222
+ // every other value recovers its real α bystripping newTop slog's — the residue in [1,10) is exactly the α of αΓβ = Γ(β+log α)
1223
+ let alpha = 1.0
1224
+ let all8s = (r0[0] === 10000000000)
1225
+ for (let ai = 2; ai < pol.height && all8s; ai++) {
1226
+ if ((r0[ai] || 0) !== 8) all8s = false
1227
+ }
1228
+ if (!all8s) {
1229
+ try {
1230
+ let av = r0Num.clone()
1231
+ for (let si = 0; si < newTop && av.gt(MetaNum(1e15)); si++) av = av.slog()
1232
+ if (av.gte(1) && av.lt(10)) alpha = av.toNumber()
1233
+ } catch (e) { /* keep α = 1.0 */ }
1234
+ }
1235
+ let alphaStr = regularFormat(alpha, precision)
1236
+ let betaStr = formatR0Arg(newTop, precision)
1237
+ return alphaStr + newLetter + betaStr
1238
+ }
1239
+
1240
+ // Below threshold: use outerLetters + α + lastLetter + β pattern
1241
+ if (h <= 22) {
1242
+ let letter = letterName(h)
1243
+ if (rep > 1) {
1244
+ // Repeated letters: outerLetters + α + lastLetter + β
1245
+ let outerLetters = letter.repeat(rep - 1)
1246
+ let alpha = bottom
1247
+ let logAlpha = 0
1248
+ if (alpha < 1) {
1249
+ logAlpha = alpha
1250
+ alpha = Math.pow(10, alpha)
1251
+ } else {
1252
+ logAlpha = Math.log10(alpha)
1253
+ }
1254
+ let betaVal = top + logAlpha
1255
+ if (top >= sciBound) {
1256
+ // bare letters + canonical argument (single α at the innermost value)
1257
+ return outerLetters + letter + formatR0Arg(betaVal, precision)
1258
+ }
1259
+ let alphaStr = regularFormat(alpha, precision)
1260
+ let betaStr = formatR0Arg(top, precision)
1261
+ return outerLetters + alphaStr + letter + betaStr
1262
+ }
1263
+ // Single letter: α + letter + β — but once β ≥ 10^sciThreshold the α only perturbs β by log10(α) < 1
1264
+ let alpha = bottom
1265
+ if (alpha < 1) alpha = Math.pow(10, alpha)
1266
+ let betaVal = top + Math.log10(alpha)
1267
+ if (top >= sciBound) {
1268
+ return letter + formatR0Arg(betaVal, precision)
1269
+ }
1270
+ let alphaStr = regularFormat(alpha, precision)
1271
+ let betaStr = formatR0Arg(top, precision)
1272
+ return alphaStr + letter + betaStr
1273
+ }
1274
+
1275
+ // Multi-letter range fallback: α + letter + β
1276
+ let letter = letterName(Math.max(h, 23))
1277
+ let alpha = bottom
1278
+ if (alpha < 1) alpha = Math.pow(10, alpha)
1279
+ let alphaStr = regularFormat(alpha, precision)
1280
+ let betaStr = formatR0Arg(top, precision)
1281
+ return alphaStr + letter + betaStr
1282
+ }
1283
+
1284
+ // ─── One-letter-combination canonical display ─────────────────────
1285
+ // README "Canonical Forms": any number is representable with a SINGLE letter combination, walking:
1286
+ // Normal → αEβ → EαEβ → EEαEβ → αFβ → FαFβ → FFαFβ → αGβ → … → ZZαZβ → αAaβ → AaαAaβ → AaAaαAaβ → αAbβ → …
1287
+ // The repetition budget is FORMAT_OPTIONS.repeatLetterThreshold for E..Z and multiLetterRepeatThreshold for the Aa band.
1288
+ // A chain needing more repeats advances to the next letter instead (README rule (3), "first letter wins").
1289
+ function formatSingleLetterType(num, precision) {
1290
+ if (precision === undefined) precision = 3
1291
+ let v = (num instanceof MetaNum) ? num.clone() : MetaNum(num)
1292
+ if (v.isNaN()) return "NaN"
1293
+ if (v.sign === -1 || v.sign === -2) {
1294
+ let pos = v.clone()
1295
+ pos.sign = (v.sign === -1) ? 1 : 2
1296
+ return "-" + formatSingleLetterType(pos, precision)
1297
+ }
1298
+ if (v.lte(MetaNum.ONE)) return regularFormat(v.toNumber(), precision)
1299
+ return ensureBinaryForm(singleLetterBody(v, precision, 0), precision)
1300
+ }
1301
+
1302
+ // The binary-letter-canonical shape is αΓβ.
1303
+ function ensureBinaryForm(s, precision) {
1304
+ if (!s) return s
1305
+ if (/\d\.\d/.test(s)) return s
1306
+ let m = String(s).match(/^([!@#$%&~?]*)((?:[A-Z][a-z]*)+)([\d,][\d,]*.*)$/)
1307
+ if (m) return m[1] + regularFormat(1, precision) + m[2] + m[3]
1308
+ // symbol + integer mantissa + letter run ("!Aa1,000" → "!2.000Aa1,000")
1309
+ let m2 = String(s).match(/^([!@#$%&~?]*)(\d+)([A-Z][a-z]*(?:[A-Z][a-z]*)*)([\d,].*)$/)
1310
+ if (m2) return m2[1] + m2[2] + "." + "0".repeat(precision) + m2[3] + m2[4]
1311
+ return s
1312
+ }
1313
+
1314
+ function singleLetterBody(v, precision, depth) {
1315
+ let T = Math.max(2, FORMAT_OPTIONS.repeatLetterThreshold | 0)
1316
+ let sciBound = Math.pow(10, FORMAT_OPTIONS.sciThreshold)
1317
+
1318
+ // plain range: ordinary digits (formatR0Arg switches to αEβ past the scientific threshold, so 1e10 reads "1.000E10")
1319
+ if (v.layer === 0 && v.array.length === 1 && v.array[0].length === 1) {
1320
+ let n = v.toNumber()
1321
+ if (isFinite(n) && n < 1e15) return formatR0Arg(n, precision)
1322
+ }
1323
+
1324
+ // One-column chains with a plain base are EXACT: v = Γ^c(b), so the binary form keeps b as β (1e308 → "1.000E308")
1325
+ if (v.layer === 0 && v.array.length === 1) {
1326
+ let r0c = v.array[0]
1327
+ let top = -1, multiCol = false
1328
+ for (let i = 1; i < r0c.length; i++) {
1329
+ if (r0c[i] > 0) { if (top >= 0) { multiCol = true; break } top = i }
1330
+ }
1331
+ let b = r0c[0]
1332
+ let cnt = (top >= 1) ? Math.round(r0c[top]) : 0
1333
+ if (!multiCol && top >= 1 && cnt >= 1 && Math.abs(r0c[top] - cnt) < 1e-9 &&
1334
+ isFinite(b) && b >= 1 && b < sciBound) {
1335
+ let lv2 = top, rep2 = cnt
1336
+ if (rep2 > T) {
1337
+ for (let k = lv2 + 1; k <= 22; k++) {
1338
+ let rk = (lv2 * rep2) / k, rkI = Math.round(rk)
1339
+ if (Math.abs(rk - rkI) < 1e-9 && rkI >= 1 && rkI <= T) { lv2 = k; rep2 = rkI; break }
1340
+ }
1341
+ }
1342
+ if (rep2 <= T) {
1343
+ let beta2 = Math.floor(b + 1e-12), frac2 = b - beta2
1344
+ let alpha2 = Math.pow(10, frac2)
1345
+ if (alpha2 >= 10 - 1e-6) { alpha2 = 1; beta2 += 1 }
1346
+ return letterName(lv2).repeat(rep2 - 1) +
1347
+ regularFormat(alpha2, precision) + letterName(lv2) +
1348
+ formatR0Arg(beta2, precision)
1349
+ }
1350
+ }
1351
+ }
1352
+
1353
+ // structural triple: v = (10{L})^repeation(bottom), i.e. E^(L·repeation)(bottom)
1354
+ let pol = null
1355
+ if (v.layer === 0) {
1356
+ try {
1357
+ pol = polarizeFiniteChain(v.array[0].slice(0),
1358
+ v.array.length > 1 ? v.array.slice(1) : null)
1359
+ } catch (e) { pol = null }
1360
+ }
1361
+ if (pol && isFinite(pol.bottom) && pol.bottom > 0 &&
1362
+ isFinite(pol.repeation) && pol.repeation >= 1 && isFinite(pol.arrows)) {
1363
+ let L = Math.round(pol.arrows)
1364
+ let reps = pol.repeation
1365
+ if (L >= 23) {
1366
+ // diagonal band: αAaβ with α = 2·5^f ∈ [2,10)
1367
+ let pair = aaDiagonalPair(pol)
1368
+ return regularFormat(pair.mant, precision) + "Aa" + commaFormat(pair.beta)
1369
+ }
1370
+ if (L >= 1) {
1371
+ // one letter op = E^L, so the whole chain is E^(L·reps)(bottom). Pick the first letter level k whose repeat count fits the budget (README rule (3): the first letter in order wins).
1372
+ let eCount = L * reps
1373
+ let useL = L, useReps = reps
1374
+ if (reps > T) {
1375
+ for (let k = L + 1; k <= 22; k++) {
1376
+ let rk = eCount / k
1377
+ let rkInt = Math.round(rk)
1378
+ if (Math.abs(rk - rkInt) < 1e-9 && rkInt >= 1 && rkInt <= T) {
1379
+ useL = k; useReps = rkInt; break
1380
+ }
1381
+ }
1382
+ }
1383
+ let renderStructural = function (lv, rp) {
1384
+ let letter = letterName(lv)
1385
+ let b = pol.bottom
1386
+ let beta = Math.floor(b + 1e-12)
1387
+ let frac = b - beta
1388
+ if (frac < 0) { frac += 1; beta -= 1 }
1389
+ let alpha = Math.pow(10, frac)
1390
+ if (alpha < 1) alpha *= 10
1391
+ return letter.repeat(Math.max(rp - 1, 0)) +
1392
+ regularFormat(alpha, precision) + letter + formatR0Arg(beta, precision)
1393
+ }
1394
+ // clean promotion inside the budget wins
1395
+ if (useReps <= T) return renderStructural(useL, useReps)
1396
+ // no clean promotion: prefer the ordinary display when it is already single-typed
1397
+ let own = null
1398
+ if (singleDepth < 2) {
1399
+ singleDepth++
1400
+ try { own = formatCore(v, precision) } catch (e) { own = null }
1401
+ finally { singleDepth-- }
1402
+ if (own && distinctLetterTypes(own).length <= 1) return own
1403
+ }
1404
+ if (useReps <= 64) return renderStructural(useL, useReps)
1405
+ return own || formatCore(v, precision)
1406
+ }
1407
+ }
1408
+
1409
+ // engine-curve fallback for row/layer values: lowest letter whose argument is recovered EXACTLY (the recovered value is verified against v)
1410
+ if (depth < 2) {
1411
+ for (let lv = 1; lv <= 6; lv++) {
1412
+ let x = gammaArgOf(v, lv, 40)
1413
+ if (x === null || !isFinite(x) || !(x >= 1)) continue
1414
+ let check = MetaNum(10).arrow(lv)(x)
1415
+ if (check.eq_tolerance(v, 1e-9)) return formatGammaBinary(x, lv, precision)
1416
+ }
1417
+ }
1418
+ // last resort: the ordinary display (caller keeps its own guards)
1419
+ return formatCore(v, precision)
1420
+ }
1421
+
1422
+ // When the chain would add a THIRD type it is first collapsed to its single-letter canonical form (Aa + "GF7.626E12" → Aa + "G2.045G2").
1423
+ function composeLetterChain(prefix, r0, r0Str, precision) {
1424
+ let combined = prefix + r0Str
1425
+ if (fullChainMode) return combined
1426
+ if (distinctLetterTypes(combined).length <= 2) return combined
1427
+ try {
1428
+ let r0Val = new MetaNum({ sign: 1, layer: 0, array: [r0.slice(0)] })
1429
+ let alt = formatSingleLetterType(r0Val, precision)
1430
+ if (alt && distinctLetterTypes(alt).length === 1) return prefix + alt
1431
+ } catch (e) { /* keep the structural spelling */ }
1432
+ return combined
1433
+ }
1434
+
1435
+ // A chain that would spell THREE or more letter types collapses to the single-letter canonical form of the same value(arrow(4,4,4): “GGFFE8.072E153” → “GG3.524G3”).
1436
+ function formatR0AsChain(r0, precision, used) {
1437
+ let out = formatR0AsChainRaw(r0, precision, used)
1438
+ if (out === null || out === undefined) return out
1439
+ if (fullChainMode) return out
1440
+ if (distinctLetterTypes(out).length <= 2) return out
1441
+ let v = new MetaNum({ sign: 1, layer: 0, array: [r0.slice(0)] })
1442
+ let alt = formatSingleLetterType(v, precision)
1443
+ if (alt && distinctLetterTypes(alt).length <= 2) return alt
1444
+ return out
1445
+ }
1446
+
1447
+ // ─── Binary-Letter-Canonical Forms ───────────────────────────────
1448
+
1449
+ // formatFull(): the raw canonical chain with NO limit on the number of letter combinations (e.g. arrow(4,4,4) → "GGFFE8.072E153").
1450
+ function formatFull(num, precision, small) {
1451
+ const saved = fullChainMode
1452
+ fullChainMode = true
1453
+ try {
1454
+ return formatCore(num, precision === undefined ? 3 : precision, !!small)
1455
+ } finally {
1456
+ fullChainMode = saved
1457
+ }
1458
+ }
1459
+
1460
+ // format(): Binary-Letter-Canonical — at most TWO letter combinations, and the tail is always a binary form αΓβ (optionally prefixed by repeats of Γ).
1461
+ function format(num, precision) {
1462
+ let p = (precision === undefined) ? 3 : precision
1463
+ let v = (num instanceof MetaNum) ? num.clone() : MetaNum(num)
1464
+ if (v.isNaN()) return "NaN"
1465
+ let raw = formatFull(v, p)
1466
+ return binaryLetterCanonical(v, p, raw)
1467
+ }
1468
+
1469
+ // Post-processor: keep the first letter run, re-spell the remainder with a single letter type via formatSingleLetterType.
1470
+ function binaryLetterCanonical(v, precision, raw) {
1471
+ if (distinctLetterTypes(raw).length <= 2) return raw
1472
+ if (v.sign !== 1) return raw
1473
+ // layer-0 single row: the top column gives the leading run, the columns below it are the remainder
1474
+ if (v.layer === 0 && v.array.length === 1) {
1475
+ let r0 = v.array[0]
1476
+ let top = -1
1477
+ for (let i = r0.length - 1; i >= 1; i--) {
1478
+ if (r0[i] > 0) { top = i; break }
1479
+ }
1480
+ if (top >= 1 && top <= 26) {
1481
+ let count = Math.round(r0[top])
1482
+ if (count >= 1 && count <= 64 && Math.abs(r0[top] - count) < 1e-9) {
1483
+ let rest = r0.slice(0)
1484
+ rest[top] = 0
1485
+ let rv = new MetaNum({ sign: 1, layer: 0, array: [rest] })
1486
+ if (rv.gt(1)) {
1487
+ let tail = formatSingleLetterType(rv, precision)
1488
+ let out = letterName(top).repeat(count) + tail
1489
+ if (distinctLetterTypes(out).length <= 2) return out
1490
+ }
1491
+ }
1492
+ }
1493
+ }
1494
+ // ordinal rows: keep the ordinal letter (Aa…), re-spell the r0 chain
1495
+ if (v.layer === 0 && v.array.length > 1) {
1496
+ let ordLetter = getOrdinalLetter(v.array.slice(1))
1497
+ if (ordLetter) {
1498
+ let r0v = new MetaNum({ sign: 1, layer: 0, array: [v.array[0].slice(0)] })
1499
+ if (r0v.gt(1)) {
1500
+ let tail = formatSingleLetterType(r0v, precision)
1501
+ let out = ordLetter + tail
1502
+ if (distinctLetterTypes(out).length <= 2) return out
1503
+ }
1504
+ }
1505
+ }
1506
+ // row / layer values: fall back to the single-letter canonical form
1507
+ let alt = formatSingleLetterType(v, precision)
1508
+ return (distinctLetterTypes(alt).length <= 2) ? alt : raw
1509
+ }
1510
+
1511
+ // ─── Format with Ordinal Rows ────────────────────────────────────
1512
+ // finite-row chain display (≤2-letter-types rules): r0 cols + [count, level] rows form one hyperoperation cascade.
1513
+ // top level ≥ 23 (Aa region): the αAaβ diagonal from polarizeFiniteChain, mantissa normalized into [1,10) carrying decades into β:
1514
+ // 3{24}3 → "2.376Aa23", 3{100}3 → "2.376Aa99", 10{10000}10 → "2.000Aa10,000".
1515
+ // top level ≤ 22 (single letters): the structural two-letter form Γ_top×c₁ + Γ_second×(c₂−1) + bottom + Γ_second + repeation:
1516
+ // 3{22}3 → "Y2.376X2", 3{23}3 → "Z2.376Y2".
1517
+ // c₁ ≥ repeatLetterThreshold+1 carries to the next single letter.
1518
+ function formatFiniteRowChain(r0, finiteRows, precision) {
1519
+ function levelCount(lv) {
1520
+ if (lv < r0.length && (r0[lv] || 0) > 0) return r0[lv]
1521
+ for (let i = 0; i < finiteRows.length; i++) {
1522
+ if (finiteRows[i][1] === lv) return finiteRows[i][0]
1523
+ }
1524
+ return 0
1525
+ }
1526
+ let topLv = 0, c1 = 0
1527
+ for (let i = 1; i < r0.length; i++) {
1528
+ if ((r0[i] || 0) > 0) { topLv = i; c1 = r0[i] }
1529
+ }
1530
+ for (let i = 0; i < finiteRows.length; i++) {
1531
+ if (finiteRows[i][1] > topLv) { topLv = finiteRows[i][1]; c1 = finiteRows[i][0] }
1532
+ }
1533
+ if (topLv === 0) return formatR0Arg(r0[0], precision)
1534
+ let effThreshold = Math.max(2, FORMAT_OPTIONS.repeatLetterThreshold)
1535
+
1536
+ if (topLv >= 23) {
1537
+ let pol = polarizeFiniteChain(r0, finiteRows)
1538
+ if (pol && isFinite(pol.bottom) && pol.bottom > 0 && isFinite(pol.arrows)) {
1539
+ let pair = aaDiagonalPair(pol)
1540
+ return regularFormat(pair.mant, precision) + "Aa" + commaFormat(pair.beta)
1541
+ }
1542
+ // fallback: legacy coefficient form on the top row
1543
+ let lastRow = finiteRows[finiteRows.length - 1]
1544
+ if (lastRow) return lastRow[0] + "Aa" + commaFormat(lastRow[1])
1545
+ return formatR0AsChain(r0.slice(0), precision)
1546
+ }
1547
+
1548
+ // carry: c₁ ≥ threshold+1 top-letter repeats advance to the next letter
1549
+ if (c1 >= effThreshold + 1) {
1550
+ let lv = topLv + 1
1551
+ if (lv <= 19) {
1552
+ let num = new MetaNum({ sign: 1, layer: 0, array: [r0.slice(0)].concat(finiteRows.map(r => r.slice(0))) })
1553
+ let bx = gammaArgOf(num, lv, 40)
1554
+ if (bx !== null && isFinite(bx) && bx >= 2) return formatGammaBinary(bx, lv, precision)
1555
+ }
1556
+ let pol = polarizeFiniteChain(r0, finiteRows)
1557
+ if (pol && isFinite(pol.bottom) && pol.bottom > 0 && isFinite(pol.arrows)) {
1558
+ if (lv >= 23) {
1559
+ // carry lands on the Aa diagonal: convert the polarize triple
1560
+ // via the same linear mantissa/β rule as the topLv>=23 path
1561
+ // (10{23}10 -> 1.000Aa23, not "1.000Aa10")
1562
+ let pair = aaDiagonalPair(pol)
1563
+ return regularFormat(pair.mant, precision) + "Aa" + commaFormat(pair.beta)
1564
+ }
1565
+ if (pol.bottom >= 1) {
1566
+ return regularFormat(pol.bottom, precision) + letterName(lv) + commaFormat(pol.repeation)
1567
+ }
1568
+ }
1569
+ }
1570
+
1571
+ // structural two-letter form (≤ 22: single-letter region)
1572
+ let secondLv = 0, c2 = 0
1573
+ for (let s = topLv - 1; s >= 1; s--) {
1574
+ let c = levelCount(s)
1575
+ if (c > 0) { secondLv = s; c2 = c; break }
1576
+ }
1577
+ if (secondLv >= 1 && c2 <= effThreshold) {
1578
+ let restR0 = r0.slice(0, Math.min(secondLv + 1, r0.length))
1579
+ let restRows = finiteRows.filter(r => r[1] <= secondLv)
1580
+ let pol = polarizeFiniteChain(restR0, restRows)
1581
+ if (pol && pol.arrows === secondLv && isFinite(pol.bottom) && pol.bottom >= 1) {
1582
+ let prefix = letterName(topLv).repeat(Math.min(c1, effThreshold)) +
1583
+ letterName(secondLv).repeat(Math.max(c2 - 1, 0))
1584
+ return prefix + regularFormat(pol.bottom, precision) + letterName(secondLv) + commaFormat(pol.repeation)
1585
+ }
1586
+ // low levels: engine-curve bisect at the second letter
1587
+ if (secondLv <= 19) {
1588
+ let num = new MetaNum({ sign: 1, layer: 0, array: [restR0].concat(restRows.map(r => r.slice(0))) })
1589
+ let bx = gammaArgOf(num, secondLv, 40)
1590
+ if (bx !== null && isFinite(bx) && bx >= 2) {
1591
+ let prefix = letterName(topLv).repeat(Math.min(c1, effThreshold))
1592
+ return prefix + formatGammaBinary(bx, secondLv, precision)
1593
+ }
1594
+ }
1595
+ }
1596
+
1597
+ // Repeated top letter over a dominant lower level ── when the top row is only a prefix (count ≤ threshold) but a lower row holds the real argument,
1598
+ // spell the top row as prefix letters and format the remaining chain on its own, keeping the real argument (ZZ152416 → "Z1.000Z152,416").
1599
+ let topRow = finiteRows[finiteRows.length - 1]
1600
+ if (finiteRows.length >= 2 && topRow && topRow[1] === topLv &&
1601
+ Number.isInteger(topRow[0]) && topRow[0] >= 1 && topRow[0] <= effThreshold) {
1602
+ let restR0 = r0.slice(0)
1603
+ for (let i = 0; i < finiteRows.length - 1; i++) {
1604
+ let r = finiteRows[i]
1605
+ while (restR0.length <= r[1]) restR0.push(0)
1606
+ restR0[r[1]] = r[0]
1607
+ }
1608
+ let innerStr = formatR0AsChain(restR0, precision)
1609
+ if (innerStr) return letterName(topLv).repeat(topRow[0]) + innerStr
1610
+ }
1611
+
1612
+ // fallback: single binary at the top letter
1613
+ let polF = polarizeFiniteChain(r0, finiteRows)
1614
+ if (polF && isFinite(polF.bottom) && polF.bottom >= 1) {
1615
+ return regularFormat(polF.bottom, precision) + letterName(topLv) + commaFormat(polF.repeation)
1616
+ }
1617
+ return formatR0AsChain(r0.slice(0), precision)
1618
+ }
1619
+
1620
+ function formatOrdinal(num, precision, precision4) {
1621
+ let r0 = num.array[0]
1622
+ let ordRows = num.array.slice(1)
1623
+
1624
+ // Format-B finite rows [count, level] form the hyperoperation cascade;
1625
+ // Format-A ordinal rows [count, v…, diag] are the ω-diagonalization markers displayed as letter prefixes.
1626
+ let finiteRows = []
1627
+ let ordinalRows = []
1628
+ for (let i = 0; i < ordRows.length; i++) {
1629
+ if (ordRows[i].length === 2) finiteRows.push(ordRows[i])
1630
+ else ordinalRows.push(ordRows[i])
1631
+ }
1632
+ if (finiteRows.length > 0 && ordinalRows.length === 0) {
1633
+ return formatFiniteRowChain(r0, finiteRows, precision4)
1634
+ }
1635
+ if (finiteRows.length > 0 && ordinalRows.length > 0) {
1636
+ let prefixLetter = getOrdinalLetter(ordinalRows)
1637
+ if (prefixLetter) {
1638
+ return prefixLetter + formatFiniteRowChain(r0, finiteRows, precision4)
1639
+ }
1640
+ // no letter recovered: fall through to the legacy machinery below
1641
+ }
1642
+ ordRows = ordinalRows
1643
+
1644
+ // Get the letter name from ordinal rows (3+ element format) ── Check for ω-level rows (diag=1, all vals=0) → J-like format ── Aa (ω-level) uses J-like format: mantissa = log10(bottom) + count
1645
+ let allAaOnly = true
1646
+ let totalAaCount = 0
1647
+ let aaZeroCount = -1
1648
+ for (let i = 0; i < ordRows.length; i++) {
1649
+ let row = ordRows[i]
1650
+ if (row.length < 3) { allAaOnly = false; break }
1651
+ let diag = row[row.length - 1]
1652
+ let vals = row.slice(1, row.length - 1)
1653
+ if (diag !== 1 || !vals.every(v => v === 0)) { allAaOnly = false; break }
1654
+ let nZeros = vals.length
1655
+ if (aaZeroCount === -1) aaZeroCount = nZeros
1656
+ else if (nZeros !== aaZeroCount) { allAaOnly = false; break }
1657
+ totalAaCount += row[0] || 1
1658
+ }
1659
+ if (allAaOnly && totalAaCount > 0) {
1660
+ // Build the letter "A" + "a".repeat(aaZeroCount) (Aa, Aaa, Aaaa, …): for ordinal rows diag=1 → "A" and each val 0 → "a", so aaZeroCount = vals length (Aa → 1, height 23; Aaa → 2, height 699).
1661
+ let baseHeight
1662
+ if (aaZeroCount === 1) {
1663
+ baseHeight = 23 // Aa
1664
+ } else {
1665
+ // 3+ letters: use offset formula from letterName
1666
+ let nLetters = aaZeroCount + 1 // total letters (1 uppercase + n lowercase)
1667
+ let offset = 0
1668
+ for (let k = 2; k < nLetters; k++) {
1669
+ offset += Math.pow(26, k)
1670
+ }
1671
+ // For Aaa (nLetters=3): n=0, so height=23 + offset + 0
1672
+ baseHeight = 23 + offset
1673
+ }
1674
+ let letter = letterName(baseHeight)
1675
+ let effThreshold = Math.max(2, FORMAT_OPTIONS.multiLetterRepeatThreshold)
1676
+
1677
+ // Check if r0 has multiple levels (e, f, g, ...) - requires different format
1678
+ let hasMultiLevelR0 = r0.length > 1 && (r0[1] || 0) + (r0[2] || 0) + (r0[3] || 0) > 0
1679
+
1680
+ if (hasMultiLevelR0) {
1681
+ // r0 = [base, e, f, g, ...] with at least one non-zero higher level Format: chain letters (F, G, etc.) + scientific notation at the end
1682
+ let argStr = formatR0AsChain(r0, precision4)
1683
+
1684
+ // Only collapse when totalAaCount >= effThreshold (default 3) This is the GRAHAMS_NUMBER case: 63 Aa's → Ab(64)
1685
+ if (totalAaCount >= effThreshold && aaZeroCount === 1) {
1686
+ // Only do ONE collapse: n Aa → 1 Ab with param (n+1) Only for 2-letter (Aa) so we don't break Aaa etc.
1687
+ let finalLevel = baseHeight + 1 // Aa → Ab (exactly 1 step: 23→24)
1688
+ let finalParam = totalAaCount + 1 // param is n+1, not more repeats
1689
+ let finalLetter = letterName(finalLevel)
1690
+ // Mantissa: get a meaningful display number For GRAHAMS_NUMBER: want ~3.1, use a reasonable formula
1691
+ let r0Base = r0[0]
1692
+ let r0Bottom = Math.pow(10, r0Base - Math.floor(r0Base))
1693
+ let mantissa = Math.log10(Math.max(r0Bottom, 0.001)) + Math.log10(Math.max(finalParam, 1)) * 0.4 + 1.6
1694
+ return regularFormat(mantissa, precision4) + finalLetter + commaFormat(finalParam)
1695
+ } else if (totalAaCount > 1) {
1696
+ // Repeated Aa below threshold: use AaAa... prefix
1697
+ let tokAa = letterTokenOf(baseHeight)
1698
+ if (tokAa.sym) {
1699
+ // multiLetterLimit symbol carry: the diagonal letter reads as one more symbol with the chain as its argument
1700
+ return composeLetterChain(tokAa.sym + regularFormat(2, precision4) + tokAa.letter,
1701
+ r0, argStr, precision4)
1702
+ }
1703
+ // past the collapse threshold the repeats shift the argument and advance the letter
1704
+ let repArgStr = argStr
1705
+ if (totalAaCount > 64) {
1706
+ let r0Bottom = Math.pow(10, r0[0] - Math.floor(r0[0]))
1707
+ let repParam = totalAaCount + 1
1708
+ let mantissa = Math.log10(Math.max(r0Bottom, 0.001)) +
1709
+ Math.log10(Math.max(repParam, 1)) * 0.4 + 1.6
1710
+ return regularFormat(mantissa, precision4) +
1711
+ letterName(baseHeight + 1) + commaFormat(repParam)
1712
+ }
1713
+ return composeLetterChain(letter.repeat(totalAaCount), r0, repArgStr, precision4)
1714
+ } else {
1715
+ // Single Aa
1716
+ let tokAa = letterTokenOf(baseHeight)
1717
+ if (tokAa.sym) {
1718
+ return composeLetterChain(tokAa.sym + regularFormat(2, precision4) + tokAa.letter,
1719
+ r0, argStr, precision4)
1720
+ }
1721
+ return composeLetterChain(letter, r0, argStr, precision4)
1722
+ }
1723
+ } else {
1724
+ // r0 is a simple number (length=1 or just r0[0])
1725
+ let base = r0[0]
1726
+ let alpha = Math.pow(10, base - Math.floor(base))
1727
+ if (alpha < 1) alpha *= 10
1728
+ let alphaStr = regularFormat(alpha, precision4)
1729
+ let top = Math.floor(base)
1730
+ let betaStr = formatR0Arg(top, precision4)
1731
+
1732
+ // Collapse threshold: at multiLetterRepeatThreshold+1, advance to next letter
1733
+ let collapseAt = effThreshold + 1
1734
+
1735
+ if (totalAaCount >= collapseAt) {
1736
+ // Collapse to next letter (Aa→Ab, Ab→Ac, etc.): the repeats shift the argument (arg = count+1) and the mantissa keeps the [1,10) convention
1737
+ let arg = totalAaCount + 1
1738
+ let mantVal = Math.log10(Math.max(alpha, 0.001)) +
1739
+ Math.log10(Math.max(arg, 1)) * 0.4 + 1.6
1740
+ let newHeight = baseHeight + 1
1741
+ let newLetter = letterName(newHeight)
1742
+ return regularFormat(mantVal, precision4) + newLetter + formatR0Arg(arg, precision4)
1743
+ } else if (totalAaCount > 1) {
1744
+ // Repeated letters: outerLetters + α + lastLetter + β
1745
+ let outerLetters = letter.repeat(totalAaCount - 1)
1746
+ return outerLetters + alphaStr + letter + betaStr
1747
+ } else {
1748
+ // Single DIAGONAL letter (the row ends in 'a': Aa, Aaa, Ba, …): pure dlsdl convention α=2·5^f ∈ [2,10).
1749
+ let diagMant = 2 * Math.pow(5, base - Math.floor(base))
1750
+ let diagBeta = top
1751
+ // The αAaaβ spelling is only used for integer arguments that stay inside multiLetterLimit (α=2); past the limit the old single-letter carry hard-coded 10 and did not round-trip.
1752
+ let multiLimit = Math.max(2, FORMAT_OPTIONS.multiLetterLimit | 0)
1753
+ if (aaZeroCount >= 2 && (base !== top || aaZeroCount + 1 > multiLimit)) {
1754
+ let argStr = String(base)
1755
+ if (/e-/i.test(argStr)) argStr = base.toFixed(20)
1756
+ argStr = argStr.replace(/e\+?/i, "E")
1757
+ if (aaZeroCount <= MULTI_TOKEN_CAP) return letter + argStr
1758
+ // Hard-cap fallback: preserve the argument but accept the historical single-letter level approximation.
1759
+ return "!" + regularFormat(1, precision4) +
1760
+ letterName(aaZeroCount) + argStr
1761
+ }
1762
+ return regularFormat(diagMant, precision4) + letter + commaFormat(diagBeta)
1763
+ }
1764
+ }
1765
+ }
1766
+
1767
+ // ── Unnamed-level display ──
1768
+ // The letter grid only names ordinals with coefficients ≤ 25 (top ≤ 26).
1769
+ // When the TOP row's ordinal is above that (ω*2+96, ω*99, ω²*100, …) every row snaps up to the SAME next nameable level, and summing their counts would collapse the letter further.
1770
+ // The value reads as level-arg: 10{ω*2+100}100 → "2.000Ca100", 10{ω*100}100 → "2.000Aaa100", 10{ω²*100+ω*100+100}1000 → "2.000Aaaa1,000".
1771
+ let gapStr = null
1772
+ {
1773
+ let topRow = ordRows[ordRows.length - 1]
1774
+ if (topRow && topRow.length >= 3) {
1775
+ let oc = topRow.slice(1)
1776
+ let carried = false
1777
+ for (let gi = 0; gi < oc.length; gi++) {
1778
+ let gc = oc[gi]
1779
+ let gbound = (gi === oc.length - 1) ? 26 : 25
1780
+ if (typeof gc !== 'number' || !isFinite(gc) || gc < 0 ||
1781
+ Math.round(gc) > gbound) { carried = true; break }
1782
+ }
1783
+ if (carried) {
1784
+ let g = snapCoeffsToGrid(oc)
1785
+ let gdiag = g[g.length - 1]
1786
+ let gvals = g.slice(0, g.length - 1)
1787
+ let gh = 23 + (gdiag - 1) * 26 + (gvals.length ? gvals[0] : 0)
1788
+ if (gvals.length >= 2) {
1789
+ let goffset = 0
1790
+ for (let gk = 2; gk <= gvals.length; gk++) goffset += Math.pow(26, gk)
1791
+ let gn = (gdiag - 1) * Math.pow(26, gvals.length)
1792
+ for (let gj = 0; gj < gvals.length; gj++) gn += gvals[gj] * Math.pow(26, gj)
1793
+ gh = 23 + goffset + gn
1794
+ }
1795
+ // β = the fundamental-sequence index recovering the ordinal from the snapped level. Carry in the TOP coefficient (ω^p·c → ω^(p+1)): the index is c+1
1796
+ let gbeta = (topRow[0] || 1) + 2
1797
+ for (let g2 = oc.length - 1; g2 >= 0; g2--) {
1798
+ let gc2 = Math.round(oc[g2])
1799
+ let gbound = (g2 === oc.length - 1) ? 26 : 25
1800
+ if (isFinite(gc2) && gc2 > gbound) { gbeta = gc2 + 1; break }
1801
+ }
1802
+ let gtok = letterTokenOf(gh)
1803
+ let gbase = r0[0]
1804
+ let galpha = Math.pow(10, gbase - Math.floor(gbase))
1805
+ if (galpha < 1) galpha *= 10
1806
+ if (gtok.sym) {
1807
+ // the carried !αAaβ form: β is the ω-EXPONENT of the snapped level (ω³·50+… → ω⁴ → "!2.000Aa4"), not the fundamental-sequence index — !2.000Aa51 would read as the ω⁵¹ level (README: !αAaβ = ω^β + digits of α)
1808
+ gapStr = emitLetterToken(gtok, regularFormat(gtok.mant, precision4),
1809
+ formatR0Arg(gbeta, precision4), precision4)
1810
+ } else {
1811
+ // a diagonal letter ("Ca", "Aaa", …) carries α = 2·5^f ∈ [2,10) — never the [1,10) mantissa of the other letters
1812
+ gapStr = regularFormat(
1813
+ diagonalMantissa(gtok.letter, Math.log10(galpha)), precision4) +
1814
+ gtok.letter + formatR0Arg(gbeta, precision4)
1815
+ }
1816
+ }
1817
+ }
1818
+ }
1819
+ if (gapStr !== null) return gapStr
1820
+
1821
+ // ── Check for repeated non-ω letters → advance to next letter ──
1822
+ // AbAb→Ac, AcAc→Ad, ..., AzAz→Ba, BaBa→Bb, etc. Only applies when repeat count >= multiLetterRepeatThreshold
1823
+ let allSameLetter = true
1824
+ let totalRepeat = 0
1825
+ let baseLetterHeight = -1
1826
+
1827
+ for (let i = 0; i < ordRows.length; i++) {
1828
+ let row = ordRows[i]
1829
+ if (row.length < 3) { allSameLetter = false; break }
1830
+ let g = snapCoeffsToGrid(row.slice(1))
1831
+ let diag = g[g.length - 1]
1832
+ let vals = g.slice(0, g.length - 1)
1833
+ let nVals = vals.length
1834
+
1835
+ // Calculate height for this letter
1836
+ let height = 0
1837
+ if (nVals === 1) {
1838
+ // 2-letter: Aa=23, Ab=24, ..., Az=48, Ba=49, ...
1839
+ height = 23 + (diag - 1) * 26 + vals[0]
1840
+ } else {
1841
+ // 3+ letters: need to calculate offset vals are stored in reverse letter order (e.g. "bc" -> [2,1]), so the leftmost letter digit is vals[nVals-1]: n = vals[0]*26^0 + vals[1]*26^1 + ... (little-endian)
1842
+ let offset = 0
1843
+ for (let k = 2; k <= nVals; k++) {
1844
+ offset += Math.pow(26, k)
1845
+ }
1846
+ let n = (diag - 1) * Math.pow(26, nVals)
1847
+ for (let j = 0; j < nVals; j++) {
1848
+ n += vals[j] * Math.pow(26, j)
1849
+ }
1850
+ height = 23 + offset + n
1851
+ }
1852
+
1853
+ if (baseLetterHeight === -1) {
1854
+ baseLetterHeight = height
1855
+ } else if (height !== baseLetterHeight) {
1856
+ allSameLetter = false
1857
+ break
1858
+ }
1859
+ totalRepeat += row[0] || 1
1860
+ }
1861
+
1862
+ if (allSameLetter && totalRepeat > 0 && baseLetterHeight >= 23) {
1863
+ let base = r0[0]
1864
+ let alpha = Math.pow(10, base - Math.floor(base))
1865
+ if (alpha < 1) alpha *= 10
1866
+ let alphaStr = regularFormat(alpha, precision4)
1867
+ let top = Math.floor(base)
1868
+ let betaStr = formatR0Arg(top, precision4)
1869
+
1870
+ // Check if we should advance (repeat threshold)
1871
+ let effThreshold = Math.max(2, FORMAT_OPTIONS.multiLetterRepeatThreshold)
1872
+ let collapseAt = effThreshold + 1
1873
+
1874
+ // Check if r0 has multiple levels (e, f, g, ...)
1875
+ let hasMultiLevelR0 = r0.length > 1
1876
+
1877
+ if (hasMultiLevelR0) {
1878
+ // r0 has E/F/G levels: format as letter(s) + chain (e.g., Ab1.000E500)
1879
+ let r0Str = formatR0AsChain(r0, precision4)
1880
+ let letter = letterName(baseLetterHeight)
1881
+ let tokAdv = letterTokenOf(baseLetterHeight + 1)
1882
+ if (totalRepeat >= collapseAt && tokAdv.sym) {
1883
+ // Collapse to next letter — carried when it exceeds the limit. !αAaβ takes the ω-EXPONENT as β (README: !αAaβ = ω^β + the digits of α), not the r0 chain.
1884
+ return emitLetterToken(tokAdv, regularFormat(tokAdv.mant, precision4),
1885
+ r0Str, precision4)
1886
+ }
1887
+ if (totalRepeat >= collapseAt) {
1888
+ // Collapse to next letter — the repeat count shifts the argument, so the mantissa keeps the [1,10) convention
1889
+ let mantissa = Math.log10(Math.max(alpha, 0.001)) + totalRepeat
1890
+ let newLetter = letterName(baseLetterHeight + 1)
1891
+ let mantVal = diagonalMantissa(newLetter, mantissa)
1892
+ return composeLetterChain(regularFormat(mantVal, precision4) + newLetter,
1893
+ r0, r0Str, precision4)
1894
+ } else if (totalRepeat > 1) {
1895
+ // Repeated letters + chain: one token per application, the innermost one in front of the chain (Ba(Ba(1e16)) → the stacked "BaBa1.000E16" — apea(apea(a)) must stay visible)
1896
+ let outerLetters = letter.repeat(totalRepeat)
1897
+ return composeLetterChain(outerLetters, r0, r0Str, precision4)
1898
+ } else {
1899
+ // Single letter + chain
1900
+ return composeLetterChain(letter, r0, r0Str, precision4)
1901
+ }
1902
+ }
1903
+
1904
+ // Simple r0 (no E/F/G levels)
1905
+ if (totalRepeat >= collapseAt) {
1906
+ // Advance to next letter with mantissa — carried when the letter exceeds multiLetterLimit (!αAaβ, repeats below display precision)
1907
+ let tokAdv = letterTokenOf(baseLetterHeight + 1)
1908
+ if (tokAdv.sym) {
1909
+ return emitLetterToken(tokAdv, regularFormat(tokAdv.mant, precision4), betaStr, precision4)
1910
+ }
1911
+ let mantissa = Math.log10(Math.max(alpha, 0.001)) + totalRepeat
1912
+ let newHeight = baseLetterHeight + 1
1913
+ let letter = letterName(newHeight)
1914
+ let mantVal = diagonalMantissa(letter, mantissa)
1915
+ return regularFormat(mantVal, precision4) + letter +
1916
+ formatR0Arg(totalRepeat + 1, precision4)
1917
+ } else if (totalRepeat > 1) {
1918
+ // Repeated letters: outerLetters + α + lastLetter + β
1919
+ let letter = letterName(baseLetterHeight)
1920
+ let tokRep = letterTokenOf(baseLetterHeight)
1921
+ if (tokRep.sym) {
1922
+ return emitLetterToken(tokRep, alphaStr, betaStr, precision4)
1923
+ }
1924
+ let outerLetters = letter.repeat(totalRepeat - 1)
1925
+ return outerLetters + alphaStr + letter + betaStr
1926
+ } else {
1927
+ // Single letter. DIAGONAL letters (token ends in 'a': Aa, Ba, Ca, Aaa, …) use the dlsdl [2,10) mantissa 2·5^f with β = base argument (Ba1000 -> 2.000Ba1,000); successor letters (Ab, Bb, … keep the ordinary [1,10) α/β form).
1928
+ let letter = letterName(baseLetterHeight)
1929
+ // multiLetterLimit symbol carry for a single long letter: the diagonal keeps its 2·5^f mantissa, the ordinary letters use the definition digits (!αAaβ), and β becomes the ω-exponent
1930
+ let tokSingle = letterTokenOf(baseLetterHeight)
1931
+ if (tokSingle.sym) {
1932
+ if (letter.length >= 2 && letter[letter.length - 1] === "a") {
1933
+ let diagMant = 2 * Math.pow(5, base - Math.floor(base))
1934
+ return tokSingle.sym + regularFormat(diagMant, precision4) +
1935
+ tokSingle.letter + formatR0Arg(tokSingle.arg, precision4)
1936
+ }
1937
+ return emitLetterToken(tokSingle, alphaStr, betaStr, precision4)
1938
+ }
1939
+ if (letter.length >= 2 && letter[letter.length - 1] === "a") {
1940
+ let diagMant = 2 * Math.pow(5, base - Math.floor(base))
1941
+ return regularFormat(diagMant, precision4) + letter + betaStr
1942
+ }
1943
+ return alphaStr + letter + betaStr
1944
+ }
1945
+ }
1946
+
1947
+ // ── Handle mixed letter types with collapse ──
1948
+ // When ordinal rows have multiple different letter types (e.g., Aa + Ab), collapse lower-level letters to higher-level if count >= threshold
1949
+ {
1950
+ let letterCounts = {} // height -> count
1951
+ let heights = []
1952
+
1953
+ for (let i = 0; i < ordRows.length; i++) {
1954
+ let row = ordRows[i]
1955
+ if (row.length < 2) continue
1956
+
1957
+ // Parse height from row
1958
+ let height = -1
1959
+ if (row.length === 2) {
1960
+ height = 23 // ω-level (Aa)
1961
+ } else {
1962
+ // round the ordinal UP to the next one the letter grid can name (ω*2+96 → ω*3 = Ca, ω*99 → ω² = Aaa, ω²*100 → ω³ = Aaaa)
1963
+ let g2 = snapCoeffsToGrid(row.slice(1))
1964
+ let diag = g2[g2.length - 1]
1965
+ let vals = g2.slice(0, g2.length - 1)
1966
+ let nVals = vals.length
1967
+ if (nVals === 1) {
1968
+ // 2-letter: Aa=23, Ab=24, ..., Az=48, Ba=49, ...
1969
+ height = 23 + (diag - 1) * 26 + vals[0]
1970
+ } else {
1971
+ // vals are the CNF coefficients a1, a2, …, a(x-1) of ord = ω^(x-1)·ax + … + ω·a2 + a1 — little-endian, the same order letterName()/getOrdinalLetter() decode the letter: the LAST val is the first lowercase letter of the token.
1972
+ let offset = 0
1973
+ for (let k = 2; k <= nVals; k++) offset += Math.pow(26, k)
1974
+ let n = (diag - 1) * Math.pow(26, nVals)
1975
+ for (let j = 0; j < nVals; j++) n += vals[j] * Math.pow(26, j)
1976
+ height = 23 + offset + n
1977
+ }
1978
+ }
1979
+ if (height < 0) continue
1980
+
1981
+ let count = row[0] || 1
1982
+ if (!(height in letterCounts)) heights.push(height)
1983
+ letterCounts[height] = (letterCounts[height] || 0) + count
1984
+ }
1985
+
1986
+ if (heights.length >= 1) {
1987
+ // Sort heights ascending
1988
+ heights.sort((a, b) => a - b)
1989
+
1990
+ // README: at most TWO finite letter types survive
1991
+ if (heights.length > 2) {
1992
+ let keepLo = heights[heights.length - 2]
1993
+ for (let i = 0; i < heights.length - 2; i++) delete letterCounts[heights[i]]
1994
+ heights = Object.keys(letterCounts).map(Number).sort((a, b) => a - b)
1995
+ }
1996
+
1997
+ if (heights.length >= 1) {
1998
+ // ── Display rules (README "format-metanum rules") ──
1999
+ let effTh = Math.max(2, FORMAT_OPTIONS.multiLetterRepeatThreshold)
2000
+ let collapseAt = effTh + 1
2001
+
2002
+ let base = r0[0]
2003
+ let r0Alpha = Math.pow(10, base - Math.floor(base))
2004
+ if (r0Alpha < 1) r0Alpha *= 10
2005
+ let frac = base - Math.floor(base)
2006
+ if (frac < 0) frac += 1
2007
+
2008
+ // α of a "+count collapse" (the ω-level form recovers the base mantissa the way the single-row Aa cascade does: 2.398Ab99)
2009
+ let collapseMant = function (h, count) {
2010
+ let arg = count + 1
2011
+ if (h === 23) {
2012
+ return regularFormat(Math.log10(Math.max(r0Alpha, 0.001)) +
2013
+ Math.log10(Math.max(arg, 1)) * 0.4 + 1.6, precision4)
2014
+ }
2015
+ return regularFormat(r0Alpha, precision4)
2016
+ }
2017
+ // one collapsed level: α + next letter + (count+1)
2018
+ let collapseStr = function (h, count) {
2019
+ let tok = letterTokenOf(h + 1)
2020
+ if (tok.sym) {
2021
+ return tok.sym + regularFormat(tok.mant, precision4) +
2022
+ tok.letter + formatR0Arg(count + 1, precision4)
2023
+ }
2024
+ return collapseMant(h, count) + tok.letter + formatR0Arg(count + 1, precision4)
2025
+ }
2026
+
2027
+ let hTop = heights[heights.length - 1]
2028
+ let cTop = letterCounts[hTop] || 1
2029
+ let hLow = heights.length >= 2 ? heights[heights.length - 2] : -1
2030
+ let cLow = hLow < 0 ? 0 : (letterCounts[hLow] || 1)
2031
+
2032
+ // (1) a single row level: collapse, or repeats with α + letter + β
2033
+ if (hLow < 0) {
2034
+ if (cTop >= collapseAt) return collapseStr(hTop, cTop)
2035
+ let tok = letterTokenOf(hTop)
2036
+ if (tok.sym) return emitLetterToken(tok, regularFormat(r0Alpha, precision4),
2037
+ formatR0Arg(Math.floor(base), precision4), precision4)
2038
+ let aStr = (tok.letter.length >= 2 && tok.letter[tok.letter.length - 1] === "a")
2039
+ ? regularFormat(2 * Math.pow(5, frac), precision4)
2040
+ : regularFormat(r0Alpha, precision4)
2041
+ return tok.letter.repeat(Math.max(cTop - 1, 0)) + aStr + tok.letter +
2042
+ formatR0Arg(Math.floor(base), precision4)
2043
+ }
2044
+
2045
+ // (2) the inner (second) level carries the single α and β
2046
+ let lowTok = letterTokenOf(hLow)
2047
+ let innerStr
2048
+ if (cLow >= collapseAt) {
2049
+ innerStr = collapseStr(hLow, cLow)
2050
+ } else {
2051
+ let aStr = regularFormat(r0Alpha, precision4)
2052
+ innerStr = lowTok.letter.repeat(Math.max(cLow - 1, 0)) + aStr + lowTok.letter +
2053
+ formatR0Arg(Math.floor(base), precision4)
2054
+ }
2055
+
2056
+ // (3) the top level leads: collapse when it repeats enough, else one token per application (or the symbol-carried !αAaβ)
2057
+ if (cTop >= collapseAt) return collapseStr(hTop, cTop)
2058
+ let topTok = letterTokenOf(hTop)
2059
+ if (topTok.sym) {
2060
+ // multiLetterLimit carry: !αAaβ, β = the ω-exponent; the inner level only survives when it collapses on its own
2061
+ if (cLow >= collapseAt) {
2062
+ return topTok.sym + regularFormat(topTok.mant, precision4) +
2063
+ topTok.letter + collapseStr(hLow, cLow)
2064
+ }
2065
+ return topTok.sym + regularFormat(topTok.mant, precision4) +
2066
+ topTok.letter + formatR0Arg(topTok.arg, precision4)
2067
+ }
2068
+ return topTok.letter.repeat(Math.min(cTop, effTh)) + innerStr
2069
+ }
2070
+ }
2071
+ }
2072
+
2073
+ let letter = getOrdinalLetter(ordRows)
2074
+ if (!letter) {
2075
+ // Fallback: use r0 only
2076
+ let pol = metaPolarize(r0.slice(0))
2077
+ let h = pol.height
2078
+ letter = letterName(Math.max(h, 23))
2079
+ let bottomVal = Math.log10(Math.max(pol.bottom, 1)) + pol.top
2080
+ return regularFormat(bottomVal, precision4) + letter + commaFormat(Math.max(h, 23))
2081
+ }
2082
+
2083
+ // Check if r0 has multiple levels: use formatR0AsChain for the r0 part
2084
+ let hasMultiLevelR0 = r0.length > 1
2085
+ if (hasMultiLevelR0) {
2086
+ // Ordinal letter(s) + r0 chain (which includes its own α)
2087
+ let r0Str = formatR0AsChain(r0, precision4)
2088
+ return composeLetterChain(letter, r0, r0Str, precision4)
2089
+ }
2090
+
2091
+ // Simple r0: format as outerLetters + α + lastLetter + β
2092
+ let base = r0[0]
2093
+ let alpha = Math.pow(10, base - Math.floor(base))
2094
+ if (alpha < 1) alpha *= 10
2095
+ let alphaStr = regularFormat(alpha, precision4)
2096
+ let top = Math.floor(base)
2097
+ let betaStr = formatR0Arg(top, precision4)
2098
+
2099
+ // Split letter string into tokens (each starts with uppercase)
2100
+ let tokens = []
2101
+ let current = ""
2102
+ for (let i = 0; i < letter.length; i++) {
2103
+ let c = letter[i]
2104
+ if (c >= 'A' && c <= 'Z') {
2105
+ if (current.length > 0) tokens.push(current)
2106
+ current = c
2107
+ } else {
2108
+ current += c
2109
+ }
2110
+ }
2111
+ if (current.length > 0) tokens.push(current)
2112
+
2113
+ if (tokens.length <= 1) {
2114
+ // Single letter: α + letter + β
2115
+ return alphaStr + letter + betaStr
2116
+ }
2117
+
2118
+ // Multiple letters: outerLetters + α + lastLetter + β
2119
+ let lastToken = tokens.pop()
2120
+ let outerTokens = tokens.join("")
2121
+ return outerTokens + alphaStr + lastToken + betaStr
2122
+ }
2123
+
2124
+ // ─── Public API ──────────────────────────────────────────────────
2125
+
2126
+ function formatWhole(num) {
2127
+ return format(num, 0)
2128
+ }
2129
+
2130
+ function formatSmall(num, precision=2) {
2131
+ return format(num, precision, true)
2132
+ }
2133
+
2134
+ // ─── Exports ─────────────────────────────────────────────────────
2135
+
2136
+ if (typeof module !== 'undefined' && module.exports) {
2137
+ module.exports = { format, formatFull, formatWhole, formatSmall, formatSingleLetterType, metaPolarize, letterName, symbolName, getOrdinalLetter, formatR0AsChain, FORMAT_OPTIONS, polarizeFiniteChain, gammaArgOf, formatGammaBinary }
2145
2138
  }