-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy path$$.PageRange.jsxlib
841 lines (729 loc) · 37.1 KB
/
$$.PageRange.jsxlib
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
/*******************************************************************************
Name: PageRange
Desc: Page range parser and formatter.
Path: /etc/$$.PageRange.jsxlib
Require: ---
Encoding: ÛȚF8
Core: NO
Kind: Module
API: =format() getFormatter() parse() normalize() count()
DOM-access: NO
Todo: ---
Created: 180429 (YYMMDD)
Modified: 230109 (YYMMDD)
*******************************************************************************/
;$$.hasOwnProperty('PageRange') || eval(__(MODULE, $$, 'PageRange', 230109, 'format'))
//==========================================================================
// BACKGROUND
//==========================================================================
/*
Range elision:
'None' 10-12 42-45 100-102 103-109 132-136 210-211 352-365 1021-1023 1491-1560
'FinalThreeDigits' 10-12 42-45 100-102 103-109 132-136 210-211 352-365 1021-1023* 1491-560
'FinalTwoDigits' 10-12 42-45 100-102* 103-109* 132-36 210-11 352-65 1021-23 1491-560
'Chicago' 10-12 42-45 100-102 103-9 132-36 210-11 352-65 1021-23 1491-560 [ADD230109]
'Oxford' 10-12 42-5 100-2 103-9 132-6 210-11 352-65 1021-3 1491-560
'FewestFigures' 10-2 42-5 100-2 103-9 132-6 210-1 352-65 1021-3 1491-560
* The suffix part cannot start with '0'.
[REF] WADDINGHAM - "New Hart's Rules - The Oxford Style Guide" (2014, p. 189)
“Numbers at either end of a range are linked with an en rule. A span of numbers
is often elided to the fewest figures possible:
30–1 42–3 132–6 1841–5
but retain as many digits as necessary where they change across the range:
65–71 352–62 1491–560 89,999–90,000
In any event, do not elide digits in (or ending with) the group 10 to 19 because
of the way they are read or spoken:
10–12 15–19 114–18 310–11
However, some editorial styles vary greatly in their treatment: for example some
require no elision, some elide to the final two digits, and some don’t elide
multiples of 10 or 100 (30–32; 100–101).”
[REF] RITTER - "Oxford Guide to Style" (2002, p. 169)
“For a span of numbers generally, use an en rule, eliding to the fewest number of
figures possible: 30-1, 42-3, 132-6, 1841-5. But in each hundred do not elide
digits in the group 10 to 19, as these represent single rather than compound
numbers: 10-12, 15-19, 114-18, 214-15, 310-11.”
“(W)here (it) is impossible (to provide exact page extents,) print 51 f. if the
reference extends only to page 52, but 51 ff. if the reference is to more than
one following page.”
[REF] UNIVERSITY OF CHICAGO - "Chicago Manual Of Style" (2010, p. 816)
FIRST NUMBER SECOND NUMBER EXAMPLES
-------------------------------------------------------------------------------
Less than 100 Use all digits 3-10, 71-72, 96-117
-------------------------------------------------------------------------------
100 or multiples of 100 Use all digits 100-104, 1100-1113
-------------------------------------------------------------------------------
101 through 109, Use changed part only 101-8, 808-33, 1103-4
201 through 209, etc.
-------------------------------------------------------------------------------
110 through 199, Use two digits unless 321-28, 498-532,
210 through 299, etc. more are needed to include 1087-89, 1496-500
all changed parts 11564-615, 12991-3001
-------------------------------------------------------------------------------
[REF] WELLISCH - "Indexing from A to Z" (1995, p. 278)
“More or less elaborate schemes have been proposed, such as not to abbreviate any
locator below 100, to omit only the first digit from three-digit numbers (e.g.,
183-95), and two digits from four-digit numbers, (e.g., 1293-95) but not 197-02
for 197-202 or 1293-07 for 1293-1307, and several other variations on this
theme. It is, however, doubtful whether the saving of one or two digits is worth
the potential confusion of users, especially since the various abbreviation
"rules" are often not applied consistently. BS3700, 5.4.3.1, ISO 999, 7.4.3.1,
and NISO Z39.4 do not permit any abbreviation of locators indicating a sequence
of pages, columns, or any other alphanumeric sequence, except for very long
final numbers exceeding 5 digits, for which only the last 2 or 3 digits may be
given if space is limited.”
*/
//==========================================================================
// TOOLS
//==========================================================================
[PRIVATE]
({
UI32: function(/*str2*/HiLo){ return ((HiLo.charCodeAt(0)<<16)|HiLo.charCodeAt(1))>>>0 },
LOAD: function(/*{<start> => <end>}&*/q,/*uint[]*/a,/*int*/dx,/*?str*/sgl, s,i,k,S,E,t,c,p)
//----------------------------------
// (Load-Array.) Feeds q :: { <start> => <end> } based on the array
// of numbers `a` and the offset `dx` and returns the ordered start
// values in a string ; each uint16 `x` being represented by `CHR(x)`.
// Algo: indiscripts.com/post/2013/10/page-range-formatter
// [REM] All numbers (keys, values, characters) are primarily shifted
// by +dx (possibly zero), so `a` may contain uints out of the range
// [1,0xFFFF] provided that `dx` satisfies `1 <= a[i]+dx <= 0xFFFF`.
// Hence it is still required that max(a)-min(a) < 0xFFFF.
// ---
// [ADD220212] If provided, the string `sgl` contains a sorted sequence
// of UTF16 chars (already shifted by dx) that specifies elements that
// MUST remain isolated (even in case they'd be part of range.) Those
// 'singletons' are post-processed by looping in `sgl`, rewriting both
// `q` and the retval `s` such that for every singleton e present in
// the input set,
// 1. e is promoted as a 'starter' in s
// 2. q[e]=e
// 3. no other range x..q[x] contains e.
// ---
// => str
{
const CHR = String.fromCharCode;
for( s='', i=a.length ; i-- ; )
{
// Requirement: 1 <= x <= 0xFFFF
// ---
k = (dx+a[i])>>>0; // The caller should guarantee 1 <= k <= 0xFFFF but
if( 1 > k || k > 0xFFFF ) continue; // we may still have to skip out-of-range values.
if( q[k] ) continue; // If state `k` is already defined then k belongs to some known range.
(S=q[k-1]) // If state `k-1` is already defined, then the range {S:k-1,k-1:S} expects a right-extension.
|| (s+=CHR(k)); // Otherwise, `k` must be registered right now as a new starter in `s`.
(E=q[k+1]) // If state `k+1` is already defined, then the range {k+1:E,E:k+1} expects a left-extension
&& (s=s.replace(CHR(k+1),'')); // and CHR(k+1) no longer makes sense as a starter in `s`.
( S&&E ) ?
( q[k]=k, q[S]=E, q[E]=S ) : // If both S and E are defined, MERGE the states {S:k-1,k-1:S} and {k+1:E,E:k+1} into {S:E,E:S}
( (t=S||E)?( q[t]=k, q[k]=t ):(q[k]=k) ); // If either S or E is defined, EXTEND the state as expected ; otherwise register the singleton {k:k}
}
(s.length) && (s=s.split('').sort().join(''));
// [ADD220212] Manage exceptions (forced singletons.)
// sgl :: Ordered sequence of unique UTF16.
// ---
if( sgl ) for( p=i=-1 ; ++i < sgl.length ; )
{
c = sgl.slice(i,1+i);
k = c.charCodeAt(0);
// Is c already a starter in s?
// ---
if( 0 <= (t=s.indexOf(c,1+p)) )
{
p = t; // Only look after this index from now (better perf is s is huge.)
t = q[k]; // Endpoint of the range: k=>t
if( t==k ) continue; // Already a singleton: nothing to do! :)
s = s.slice(0,1+p)+CHR(1+k)+s.slice(1+p); // s :: ...<k>... --> ...<k><k+1>...
q[1+k]=t, q[k]=k; // Split k=>t into { k=>k, k+1=>t }
continue;
}
// Boring case: find the range S=>E that contains k (if any!)
// ---
for
(
E=false, t=p ;
(S=s.charCodeAt(++t)) < k && (E=q[S]) < k ;
E=false
);
if( false===E ) continue; // Failure: c is an outsider -> ignore it!
p = t; // Only look after this index from now (better perf is s is huge.)
// ---
// Now we have S <= k-1 < k <= E
// Warning: the case k===E may occur!
// ---
if( k===E )
{
s = s.slice(0,1+p)+CHR(k)+s.slice(1+p); // s :: ...<S>... --> ...<S><k=E>...
q[S]=k-1, q[k]=k; // Split S=>E into { S=>k-1, k=>(E=k) }
}
else
{
s = s.slice(0,1+p)+CHR(k,1+k)+s.slice(1+p); // s :: ...<S>... --> ...<S><k><k+1>...
q[S]=k-1, q[k]=k, q[1+k]=E; // Split S=>E into { S=>k-1, k=>k, k+1=>E }
}
}
return s;
},
FRMT: function(/*str*/s,/*{}*/q,/*int*/dx,/*uint>=1*/mn,/*uint>=1*/gp,/*str*/sp,/*str*/jn,/*str*/eli,/*str|falsy*/sgl,/*str*/sty,/*str*/pfx,/*?{pair:str,more:str}*/rdx, L,R,M,SFX,e0,e1,e2,a,z,i,iMax,x0,x1,nx,t)
//----------------------------------
// (Format.) Formats the ranges {start=>end} in `q` with respect to
// start locators in `s` and additional options. See µ.format() for
// more detail.
// [ADD220212] If `sgl` is truthy, it contains the ordered sequence
// of singletons (as UTF16 chars) that have been already 'isolated'
// in `s` and `q`. This argument is still required here to prevent
// the `gp` option from reintroducing forbidden ranges.
// [ADD220609] If `rdx` is a `{pair:str,more:str}` object, it defines
// a special suffix for either pairs (`rdx.pair`) or more consecutive
// elems (`rdx.more`) that `mn` prevents from forming a range. Hence,
// `mn` should be set accordingly: at least 2 to use `rdx.pair`,
// at least 3 to use `rdx.more`, which then operates up to (mn-1).
// [REM230109] `eli` must contain one of the valid `ELI_...` keys, i.e.
// ELI_FINALTHREEDIGITS | ELI_FINALTWODIGITS | ELI_OXFORD | ELI_CHICAGO
// | ELI_FEWESTFIGURES
// ---
// => str
{
const CHR = String.fromCharCode; // [CHG220609] Needed anyway.
// [CHG220213] Style support.
// ---
L = R = M = callee.hasOwnProperty(t='STY_'+sty) ? callee[t] : String;
if( callee.hasOwnProperty(t='ELI_'+eli) && callee.CAN_ELIDE.test(R.name) )
{
t = callee[t];
e0 = t[0]; // 1|2|3 ; `MIN` arg of the `ELI` routine.
e1 = t[1]; // 0|1 ; `NO_TENS` arg of the `ELI` routine (Oxford flag.)
e2 = t[2]; // 0|1 ; `NO_HUND` arg of the `ELI` routine (Chicago flag.)
R = callee.ELI;
}
// [ADD220609] Redux suffixes.
// ---
SFX = false;
if( rdx && mn > 1 )
{
SFX = ['', '']; // 0-uple and 1-uple -> no suffix
SFX.push(t=rdx.pair||''); // pair (2-uple) -> rdx.pair suffix (may be empty, not a problem.)
t = rdx.more||t; // n-uple -> rdx.more suffix (fallback: rdx.pair.)
for( i=2 ; ++i <= mn ; SFX.push(t) );
}
for( a=[], z=0, iMax=s.length-1, x0=nx=s.charCodeAt(0), i=-1 ; ++i <= iMax ; )
{
x1 = q[nx]; // Current end.
nx = i < iMax ? s.charCodeAt(1+i) : 1/0; // Next start | +Infinity.
// Small gap -> enlarge the range from x0.
if( gp >= nx-x1 && !(sgl && (0<=sgl.indexOf(CHR(nx))||0<=sgl.indexOf(CHR(x0)))) ) continue;
// [REM] Suppose gp==1 and mn==4. Then data like `2..3` and `5`
// shall temporarily produce a segment `2..5` (x0=2, x1=5). Now,
// since `x1-x0 < mn` (i.e 3 < 4) it is required to output that
// segment in 'split' form. But the string `2,3,4,5` would be a
// mistake because 4 is not present in the input. (The expected
// result is `2,3,5` here.) For that reason, the split process
// must check that EVERY intermediate value is registered in `q`.
// Add x0..x1 value(s).
// ---
if( x1-x0 >= mn )
a[z++] = pfx + L(t=dx+x0) + jn + R(dx+x1,t,e0,e1,e2); // Range `x0-x1` [dx] ; [CHG230109] Added `e2`.
else if( (!SFX) || x0===x1 )
for(; x0 <= x1 ; (q[x0]&&(a[z++]=pfx+M(dx+x0))),++x0 ); // Split non-range elems into `x0, etc, x1` [dx]
else
{
// [ADD220609] Split non-range elems into `x0, etc, x1` [dx] while
// formatting nuple suffixes like (5,6)->`5f.` | (5,6,7)->`5ff.` etc
// ---
for
(
t='' ; x0 <= x1 ;
( q[x0] ? ( t+=CHR(x0) ) : ( a[z++]=pfx+M(dx+t.charCodeAt(0))+SFX[t.length],t='' ) ),
++x0
);
// Pending group?
// ---
t.length && (a[z++]=pfx+M(dx+t.charCodeAt(0))+SFX[t.length]);
}
x0 = nx;
}
return a.length ? a.join(sp) : '';
}
.setup
({
// [ADD220213] Style formatters that supports elision.
// ---
CAN_ELIDE: /^String|ONEZ|TWOZ|THRZ$/,
ELI: function(/*uint_last*/y,/*uint_first*/x,/*uint*/MIN,/*bool*/NO_TENS,/*bool*/NO_HUND, n,t,z,i)
//----------------------------------
// [ADD230109] Added Chicago rules (MIN==2 && NO_HUND==1), that is:
// #1 x < 100 --> keep all digits (hence MIN==2) ; e.g 3-10, 71-72, 96-117
// #2 x ends with '00' --> keep all digits ; e.g 100-104, 1100-1113
// #3 x :: 101..109, 201..209, etc --> drop *all* common digits ; e.g 101-8, 808-33, 1103-4
// #4 x :: 110..199, 210..299, etc --> keep at least two digits ; e.g 321-28, 498-532, 1087-89, 1496-500, 12991-3001
{
// Initial step: coerce y and x to strings and compare their lengths.
// If lengths are different (e.g '106' vs. '31') , returns `y` as is ('106').
// (Note: by design y is always greater than x, numerically.)
// If the length `n` is <= MIN, returns `y` as is.
// ---
if( (x=''+x).length != (n=(y=''+y).length) || n <= MIN ) return y;
// ---
// From then, `y` and `x` (as strings) have the same length n and n > MIN.
// ---
if( NO_HUND ) // [ADD230109] Chicago Manual of Style rules #2-#4.
{
if( '00'===(t=x.slice(-2)) ) return y; // #2 Do not drop digits if x has the form '...00'.
0x30===t.charCodeAt(0) && (MIN=1); // #3 Special redux of 101..109, 201..209 allowed,
// #4 otherwise the default algo w/ MIN=2 is OK.
}
for( z=n-MIN, i=-1 ; ++i < z && x.charCodeAt(i)==y.charCodeAt(i) ; ); // 0 <= i <= z ; i is the 'change digit' index in y, w.r.t to MIN.
for( ; 0 <= i && 0x30 == y.charCodeAt(i) ; i-- ); // Always prevents '0' as starter ; y[i] is now guaranteed to be non-0.
NO_TENS && 0 < i && i==n-1 && 0x31==y.charCodeAt(i-1) && --i; // Prevents elision within ###10-###19 (Oxford). Note: the issue cannot occur in Chicago since MIN=1 -> x ends with '0#'
return 0 < i ? y.slice(i) : y;
},
// MIN NO_TENS NO_HUND
ELI_FINALTHREEDIGITS: [ 3, 0, 0 ],
ELI_FINALTWODIGITS: [ 2, 0, 0 ],
ELI_OXFORD: [ 1, 1, 0 ],
ELI_CHICAGO: [ 2, 0, 1 ], // [ADD230109] Note: MIN=2 is the default setting; it can dynamically reduce to 1 in special case.
ELI_FEWESTFIGURES: [ 1, 0, 0 ],
STY_ONEZ: function ONEZ(/*uint>0*/z)
//----------------------------------
// SINGLE_LEADING_ZEROS Numbering Style
// => str
{
return 10 > z ? ('0'+z) : z.toString();
},
STY_TWOZ: function TWOZ(/*uint>0*/z)
//----------------------------------
// DOUBLE_LEADING_ZEROS Numbering Style
// => str
{
return 100 < z ? z.toString() : ('00'+z).slice(-3);
},
STY_THRZ : function THRZ(/*uint>0*/z)
//----------------------------------
// TRIPLE_LEADING_ZEROS Numbering Style
// => str
{
return 1000 < z ? z.toString() : ('000'+z).slice(-4);
},
STY_UROM: function UROM(/*uint>0*/z, r,k)
//----------------------------------
// UPPER_ROMAN Numbering Style
// => str
{
const MF = Math.floor;
r = '';
if( 1000 <= z )
{
k = MF(z/1000);
r = 5 <= k ? callee(k) : 'MMMM'.slice(-k);
z %= 1000;
}
100 <= z && ( (r+=['C','CC','CCC','CD','D','DC','DCC','DCCC','CM'][-1+MF(z/100)]),(z %= 100) );
10 <= z && ( (r+=['X','XX','XXX','XL','L','LX','LXX','LXXX','XC'][-1+MF(z/10)]), (z %= 10) );
1 <= z && ( r+=['I','II','III','IV','V','VI','VII','VIII','IX'][-1+z] );
return r;
},
STY_LROM: function LROM(/*uint>0*/z, r,k)
//----------------------------------
// LOWER_ROMAN Numbering Style
// => str
{
const MF = Math.floor;
r = '';
if( 1000 <= z )
{
k = MF(z/1000);
r = 5 <= k ? callee(k) : 'mmmm'.slice(-k);
z %= 1000;
}
100 <= z && ( (r+=['c','cc','ccc','cd','d','dc','dcc','dccc','cm'][-1+MF(z/100)]),(z %= 100) );
10 <= z && ( (r+=['x','xx','xxx','xl','l','lx','lxx','lxxx','xc'][-1+MF(z/10)]), (z %= 10) );
1 <= z && ( r+=['i','ii','iii','iv','v','vi','vii','viii','ix'][-1+z] );
return r;
},
STY_ULET: function ULET(/*uint>0*/z)
//----------------------------------
// UPPER_LETTERS Numbering Style
// => str
{
return (--z >= 26 ? callee(Math.floor(z/26)) : '') + String.fromCharCode(0x41 + (z%26));
},
STY_LLET: function LLET(/*uint>0*/z)
//----------------------------------
// LOWER_LETTERS Numbering Style
// => str
{
return (--z >= 26 ? callee(Math.floor(z/26)) : '') + String.fromCharCode(0x61 + (z%26));
},
}),
PRSE: function(/*str*/seq,/*str*/sp,/*str*/jn, r,re,ERR,i,t,p,x,y,k,d)
//----------------------------------
// (Parse.) Pre-parse the sequence and return an ordered rich array of start
// numbers formatted as `<Hi><Lo>` strings (2 chars). Each start number
// associated to a nonzero range also produces a key _<start> => dist,
// where `dist` is the highest distance from `start` (in case of duplicates
// like "12-15, 12-23".)
// [REM] This routine alone does not prevent overlaps or duplicates in
// the returned array, but it guarantees increasing start numbers and
// provides maximum distances for ranges.
// ---
// => new [{}] ; idx => <startHi><startLo> + `_<start>` => dist>0
{
r = seq.split(sp);
re = callee.RE_NUM;
const CHR = String.fromCharCode;
for( ERR=callee.ARR_FALSE, i=r.length ; i-- ; )
{
t = r[i]; // `123` | `123-456` ; may contain extra characters
0 <= (p=t.indexOf(jn))
? ( x=(t.slice(0,p).match(re)||ERR)[0], y=(t.slice(1+p).match(re)||ERR)[0] )
: ( x=(t.match(re)||ERR)[0], y=false );
if( false===x && false===y ){ r.splice(i,1); continue; }
x = false===y
? ( y=parseInt(x,10) )
: ( y=parseInt(y,10), (false===x ? y : parseInt(x,10)) );
if( x!==x>>>0 || y!==y>>>0 ){ r.splice(i,1); continue; } // Skip high numbers > 0xFFFFFFFF
if( y < x )
{
// In case of elisions like "42-5", "100-2", "210-11", etc, try to
// restore the full form, but only if the resulting order is consis-
// tent (e.g "22-7" -> 22-27). Otherwise, reverse: "27-2" -> 2-27.
// ---
t = 0 < ( t=(''+x).length-(''+y).length ) && parseInt((''+x).slice(0,t)+y, 10);
false !== t && x < t
? ( y=t ) // Restore a from valid elision ; "22-7" -> 22-27
: ( t=y, y=x, x=t ); // Fallback: reverse the range ; "27-2" -> 2-27
}
0xFFFF > (d=y-x) || error(__("Too many numbers in the sequence!"),callee); // Quick test.
r[i] = CHR(x>>>16, 0xFFFF&x);
if( !d ) continue;
// [REM] NEVER USE A *KEY* THAT OWNS \0
// Hence we use `_<plainNumber>`.
// ---
k = '_' + x;
(r[k]||0) < d && (r[k]=d);
}
r.sort();
return r;
}
.setup
({
RE_NUM: /\d+/,
ARR_FALSE: [false],
}),
SEQS: function(/*(uint|any)[]*/arr,/*int*/dx, r,i,x)
//----------------------------------
// (Sequence-String.) Extract each integer x from arr and put
// x+dx (as a UTF16 character) in the output string, sorted and
// without duplicates. NaN and out-of-range numbers are ignored.
// ---
// => str ; e.g "\x02\x03\x08\x0A..."
{
const CHR = String.fromCharCode;
for
(
r='', i=-1 ; ++i < arr.length ;
1 <= (x=(dx+arr[i])>>>0) && x <= 0xFFFF
&& -1 == r.indexOf(x=CHR(x)) && (r+=x)
);
return r.length ? r.split('').sort().join('') : '';
},
})
//==========================================================================
// API
//==========================================================================
[PUBLIC]
({
format : function format_A_õ_S(/*(uint|str)[]*/numbers,/*?{}=auto*/options, dx,sp,jn,gp,mn,rxp,rxm,eli,sgl,sty,pfx,I,q,s,t)
//----------------------------------
// Formats an array of positive integers into an ordered sequence
// of single numbers and/or ranges. Returns the formatted string.
// E.g µ([1000,3,6,8,5,12,9,5,999]) => "3, 5-6, 8-9, 12, 999-1000"
// [ADD210817] New version providing range elision option (see below.)
// [ADD220211] Added the `singletons` option (see below.)
// [ADD220213] Added the `style` and `prefix` options.
// [ADD220609] Added the `reduxPair` and `reduxMore` options.
// --------------------------------------------------------------------
// <numbers> The page numbers to format. Array of positive integers
// or strings that coerce into positive integers.
// Supports empty array, unsorted items, duplicates.
// Numbers can be greater than 65,535 as long as the
// difference (maxValue-minValue) doesn't exceed 65,535.
// --------------------------------------------------------------------
// <options> Set of formatting options:
// .separator (str) String to be inserted between results. Default: ', '.
// E.g µ([4,1,3,8,9,6], {separator:' | '})
// => "1 | 3-4 | 6 | 8-9"
// .joiner (str) Range formatting separator. Default: '-'
// E.g µ([4,1,3,8,9,6], {joiner: '_'})
// => "1, 3_4, 6, 8_9"
// .minRange (uint) Minimum distance (>=1) between the 1st and the last
// value in a range. Default: 1 if !reduxPair ; 2 if reduxPair
// AND !reduxMore ; 3 if reduxPair AND reduxMore.
// E.g µ([1,2,4,5,6,8,9,10,11], {minRange:1})
// => "1-2, 4-6, 8-11"
// µ([1,2,4,5,6,8,9,10,11], {minRange:2})
// => "1, 2, 4-6, 8-11"
// µ([1,2,4,5,6,8,9,10,11], {minRange:3})
// => "1, 2, 4, 5, 6, 8-11"
// reduxPair (str) Special suffix for formatting pairs if minRange > 1.
// (`minRange` is set to at least 2 if not supplied.)
// Note: If reduxPair is missing while reduxMore is
// non-empty, assume reduxPair=reduxMore.
// E.g µ([1,2,4,5,6,10,11,15], {reduxPair:"f."})
// => "1f., 4-6, 10f., 15" ; implied minRange=2
// WARNING reduxPair operates whatever the `style` option, which
// might lead to Roman numbers (i, ii, iii...) or alpha-
// betic sequences (a, b, c...) The client code is res-
// ponsible for adjusting the redux string accordingly.
// reduxMore (str) Special suffix for formatting N consecutive numbers
// from N=3 to N=minRange, provided that reduxPair is
// defined. (`minRange` is set to 3 if not supplied.)
// E.g µ([1,2,4,5,6,10,11,15], {reduxPair:"f.", reduxMore:"ff."})
// => "1f., 4ff., 10f., 15" ; implied minRange=3
// WARNING reduxMore operates whatever the `style` option, which
// might lead to Roman numbers (i, ii, iii...) or alpha-
// betic sequences (a, b, c...) The client code is res-
// ponsible for adjusting the redux string accordingly.
// .gap (uint) Number of allowed missing numbers in a range. Default: 0.
// E.g µ([2,3,5,8,12,17,23], {gap:0})
// => "2-3, 5, 8, 12, 17, 23"
// µ([2,3,5,8,12,17,23], {gap:1})
// => "2-5, 8, 12, 17, 23"
// µ([2,3,5,8,12,17,23], {gap:2})
// => "2-8, 12, 17, 23"
// .elision (str) One of the following strings (case-insensitive):
// 'None' Do not elide ranges (default).
// E.g 10-12, 42-45, 100-102, 132-136, 210-211, 352-365, 1491-1560
// 'FinalThreeDigits' Preserve at least three final digits:
// E.g 10-12, 42-45, 100-102, 1021-1023*, 1491-560, 10150-302
// 'FinalTwoDigits' Preserve at least two final digits:
// E.g 10-12, 42-45, 100-102*, 132-36, 210-11, 352-65, 1021-23, 1491-560
// 'Chicago' [ADD230109] Applies the 'Chicago Manual of Style' rules.
// E.g 10-12, 42-45, 100-102, 103-8, 132-36, 210-11, 352-65, 1021-23, 1491-560
// 'Oxford' Minimal form, except if final digits range in 10..19.
// E.g 10-12, 42-5, 100-2, 132-6, 210-11, 352-65, 1021-3, 1491-560
// 'FewestFigures' Strictly minimal form:
// E.g 10-2, 42-5, 100-2, 132-6, 210-1, 352-65, 1021-3, 1491-560
// *[REM] `0` is not allowed as elision starter, so `1021-1023` cannot be reduced to "1021-023".
// .singletons (uint[]) If supplied, array of positive numbers (typically a
// subset of the incoming `numbers` array) that cannot be part
// of a range. This option allows you to arbitrarily exclude
// specific numbers -- e.g [10,11,12] -- from ranges.
// Every singleton that belongs to the input array will appear
// isolated in the final string, e.g "... 10, 11, 12 ...",
// disregarding other rules and formatting options.
// [REM] A number specified in `singletons` but not present in the
// original input array is simply ignored.
// E.g µ([1,2,4,5,6,8,9,10,11], {minRange:2, singletons:[4,11]})
// => "1, 2, 4, 5, 6, 8-10, 11" ; instead of "1, 2, 4-6, 8-11"
// [REM] It is assumed here that `singletons` (if supplied) is a rela-
// tively short data stream that supports basic loop/sort procedures
// with no critical performance costs. In particular, if your original
// set of numbers has to be entirely formatted as an ordered sequence
// of singletons, there's no interest in using $$.PageRange since much
// direct algorithms can achieve the desired task very quickly.
// .style (?str) One of the following strings (case-insensitive):
// 'ARAB' : 1, 2, 3, 4... (default.)
// 'ONEZ' : 01, 02, 03, 04...
// 'TWOZ' : 001, 002, 003, 004...
// 'THRZ' : 0001, 0002, 0003, 0004...
// 'UROM' : I, II, III, IV...
// 'LROM' : i, ii, iii, iv...
// 'ULET' : A, B, C, D, ... AA, AB...
// 'LLET' : a, b, c, d, ... aa, ab...
// E.g µ([1,2,4,5,6,8,9,10,11], {minRange:2, style:'LROM'})
// => "i, ii, iv-vi, viii-xi"
// E.g µ([10,11,12,59,60,61,210,211,212], {elision:'Oxford', style:'THRZ'})
// => "0010-12, 0059-61, 0210-12"
// [REM] The `elision` option only applies if `style` is
// 'ARAB', 'ONEZ', 'TWOZ', or 'THRZ'. If `elision` is 'None',
// styles involving leading zeros ('ONEZ', 'TWOZ', 'THRZ')
// will output ranges in full format, e.g "0012-0013".
// .prefix (str) Optional prefix added before every single element and range.
// E.g µ([4,1,3,8,9,6], {prefix: 'II.'})
// => "II.1, II.3-4, II.6, II.8-9"
// ---
// => str
{
// Checkpoint.
// ---
( numbers && numbers instanceof Array )
|| error(__("Invalid `numbers` argument (%1). Should be an array.", numbers && numbers.__class__),callee);
( isNaN( dx=Math.min.apply(0,numbers) ) || 0 > dx )
&& error(__("Invalid `numbers` argument. Some elements are not positive numbers."),callee);
dx = 1-dx; // shift
I = callee.µ['~'];
// Options :: { ?separator:str, ?joiner:str, ?minRange:uint, ?gap:uint, ?elision:str, ?singletons:uint[] }
// ---
options===Object(options) || (options=0);
('string' == typeof(sp=options.separator) && sp.length) || (sp = ', ');
('string' == typeof(jn=options.joiner) && jn.length) || (jn = '-');
// ---
'string' == typeof(rxm=options.reduxMore) || (rxm=''); // [ADD220609]
'string' == typeof(rxp=options.reduxPair) || (rxp=rxm); // Fallback: reduxPair=reduxMore.
t = 2*(0<rxm.length) || 1*(0<rxp.length); // 0=NO_REDUX | 1=REDUX_PAIR_ONLY | 2=REDUX_MORE
// ---
(mn=options.minRange>>>0) || (mn=1+t); // [CHG220609] Adjust mn to redux (if mn falsy.)
(gp=options.gap>>>0) || (gp=0);
eli = String(options.elision||'').toUpperCase(); // checked from ~.FRMT
sgl = (t=options.singletons) && t instanceof Array && I.SEQS(t,dx); // [ADD220211] Singletons (as a string.)
sty = String(options.style||'').toUpperCase(); // [ADD220213] checked from ~.FRMT
('string' == typeof(pfx=options.prefix)) || (pfx = ''); // [ADD220213]
// Ranges: q :: { start => end } ; s :: CHR(start0,start1...) ; all shifted by `dx`.
// ---
s = I.LOAD(q={}, numbers, dx, sgl);
if( !s.length ) return '';
// Format.
// ---
t = (rxp.length||rxm.length) ? {pair:rxp, more:rxm} : false;
return I.FRMT(s,q,-dx,mn,1+gp,sp,jn,eli,sgl,sty,pfx,t);
},
getFormatter : function getFormatter_S_F(/*str*/style)
//----------------------------------
// Return the formatter associated to that style, if any.
// As a fallback, the String function is returned.
// style :: One of ARAB|ONEZ|TWOZ|THRZ|UROM|LROM|ULET|LLET
// ---
// => fct [OK]
{
return callee.µ['~'].FRMT['STY_'+style] || String;
},
parse : function parse_S_õ_oaf_A(/*str*/seq,/*?{separator:str,joiner:str}=auto*/options,/*?{num=>any}|fct*/map, sp,jn,xLast,a,r,z,i,x,d)
//----------------------------------
// Parses a formatted sequence of positive integers and/or ranges
// into an ordered array of positive numbers. The incoming sequence
// doesn't need to have ordered elements (e.g "17, 5, 11-13"). Also,
// elided ranges like "200-10" are interpreted "200-210".
// If supplied, `map` (array, object, or function) will translate each
// resulting number `x` into its match `map[x]` -- or `map(x)`.
// [REM] Warning: for security reasons this routine doesn't support
// ranges having more than 65,535 elements, although it still allows
// the resulting array to have a higher length. In such event, the
// `format` method wouldn't be able to restore the original sequence.
// [REM] It is the responsability of the caller to make sure that
// `separator` and `joiner` DO NOT CONTAIN DIGITS!
// --------------------------------------------------------------------
// <options> Set of parsing options:
// .separator (str) String used for separating elements. Default: ','.
// .joiner (str) String used for declaring a range. Default: '-'
// [REM] Other non-digit characters are ignored.
// ---
// E.g µ.parse("8, 16-21, 25, 51-70") => [8,16,17,18,19,20,21,25,51,...70]
// µ.parse("1-1000000") => ERROR ("Too many numbers")
// ---
// => uint[] | any[] ; any[] if a map is provided
{
// Checkpoint.
// ---
( 'string' == typeof seq )
|| error(__("Invalid `seq` argument (%1). Should be a string.", $.global[callee.µ.__root__].JSON(seq,1)).trunc(100),callee);
// Options :: { ?separator:str, ?joiner:str }
// ---
options===Object(options) || (options=0);
('string' == typeof(sp=options.separator) && sp.length) || (sp = ',');
('string' == typeof(jn=options.joiner) && jn.length) || (jn = '-');
// [CHG211112] Supports `map` as a function or object.
// ---
'function' == typeof map
|| ( map===Object(map) && (callee.MAPF.Q=map, map=callee.MAPF) )
|| ( map=callee.IDEN );
a = callee.µ['~'].PRSE(seq,sp,jn); // idx => <startHi><startLo> + `_<start>` => dist>0
const U32 = callee.µ['~'].UI32;
for( r=[], xLast=-1/0, z=0, i=-1 ; ++i < a.length ; )
{
x = U32(a[i]); // `<Hi><Lo>` -> uint32
x > xLast && ( xLast=x, r[z++]=map(xLast) );
if( !(d=a['_'+x]) ) continue;
for( x+=d ; xLast < x ; ++xLast, r[z++]=map(xLast) );
}
callee.MAPF.Q && delete callee.MAPF.Q; // Free up reference.
return r;
}
.setup
({
MAPF: function(/*uint*/x){ return callee.Q[x] },
IDEN: function(/*uint*/x){ return x },
}),
normalize : function normalize_S_õ_oaf_S(/*str*/seq,/*?{separator:str,joiner:str}=auto*/options,/*?{num=>any}|fct*/map, sp,jn,a,r,z,i,x,x0,x1,t)
//----------------------------------
// Similar to `parse`, this method optimizes the incoming sequence
// and returns a new sequence properly ordered and free of duplicates
// or overlaps. This is quite equivalent, although faster, than
// `µ.format(µ.parse(seq))`
// If supplied, `map` (array, object, or function) will translate each
// resulting number `x` into its match `map[x]` -- or `map(x)`.
// --------------------------------------------------------------------
// <options> Set of parsing/formatting options:
// .separator (str) String used for separating elements. Default: ','.
// .joiner (str) String used for declaring a range. Default: '-'
// [REM] Other non-digit characters are ignored.
// ---
// => str ; e.g µ.normalize("8, 5, 7-10") => "5,7-10"
{
// Checkpoint.
// ---
( 'string' == typeof seq )
|| error(__("Invalid `seq` argument (%1). Should be a string.", $.global[callee.µ.__root__].JSON(seq,1)).trunc(100),callee);
// Options :: { ?separator:str, ?joiner:str }
// ---
options===Object(options) || (options=0);
('string' == typeof(sp=options.separator) && sp.length) || (sp = ',');
('string' == typeof(jn=options.joiner) && jn.length) || (jn = '-');
a = callee.µ['~'].PRSE(seq,sp,jn); // idx => <startHi><startLo> + `_<start>` => dist>0
if( !a.length ) return '';
// [CHG211112] Supports `map` as a function or object.
// ---
'function' == typeof map
|| ( map===Object(map) && (callee.MAPF.Q=map, map=callee.MAPF) )
|| ( map=callee.IDEN );
const U32 = callee.µ['~'].UI32;
x1 = (x0=U32(a[0])) + (0|a['_'+x0]); // [x0=x1] | [x0..x1]
for( r=[], z=0, i=0 ; ++i < a.length ; )
{
x = U32(a[i]); // New value x ; x0 <= x
t = x+(0|a['_'+x]); // New term t=x+dist ; x <= t
if( t <= x1 ) continue;
if( x <= 1+x1 ){ x1=t; continue; }
// ---
// x0 <= x1 << x <= t
// ---
r[z++] = x0 < x1 ? ( map(x0) + jn + map(x1) ) : map(x0);
x0 = x; x1 = t;
}
r[z++] = x0 < x1 ? ( map(x0) + jn + map(x1) ) : map(x0);
callee.MAPF.Q && delete callee.MAPF.Q; // Free up reference.
return r.join(sp);
}
.setup
({
MAPF: function(/*uint*/x){ return callee.Q[x] },
IDEN: function(/*uint*/x){ return x },
}),
count : function count_S_õ_I(/*str*/seq,/*?{separator:str,joiner:str}=auto*/options, sp,jn,xLast,a,z,i,x,d)
//----------------------------------
// Similar to `parse`, this method just calculates the *length*
// of the resulting array without building an actual JS Array.
// Equivalent but faster than `µ.parse(seq).length`.
// ---
// => uint ; e.g µ.count("5, 16-21, 17, 25") => 8
{
// Checkpoint.
// ---
( 'string' == typeof seq )
|| error(__("Invalid `seq` argument (%1). Should be a string.", $.global[callee.µ.__root__].JSON(seq,1)).trunc(100),callee);
// Options :: { ?separator:str, ?joiner:str }
// ---
options===Object(options) || (options=0);
('string' == typeof(sp=options.separator) && sp.length) || (sp = ',');
('string' == typeof(jn=options.joiner) && jn.length) || (jn = '-');
a = callee.µ['~'].PRSE(seq,sp,jn); // idx => <startHi><startLo> + `_<start>` => dist>0
const U32 = callee.µ['~'].UI32;
for( xLast=-1/0, z=0, i=-1 ; ++i < a.length ; )
{
x = U32(a[i]); // `<Hi><Lo>` -> uint32
x > xLast && ( xLast=x, ++z );
if( !(d=a['_'+x]) ) continue;
xLast < (x+=d) && ( z+=(x-xLast), xLast=x );
}
return z;
},
})