@slnknrr/str-im 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +75 -0
- package/README.md +299 -0
- package/package.json +66 -0
- package/src/str-im.js +1920 -0
- package/src/tables.js +41 -0
- package/types/str-im.d.ts +222 -0
package/src/str-im.js
ADDED
|
@@ -0,0 +1,1920 @@
|
|
|
1
|
+
//=== LIBRARY-WIDE CONVENTIONS ===
|
|
2
|
+
//
|
|
3
|
+
//1. PHILOSOPHY. str-im adds only what String lacks. Plainly iterating characters is
|
|
4
|
+
// already done by for..of (code points) and str[i] (code units) — nothing to duplicate.
|
|
5
|
+
// So the whole *char family iterates UNIQUE characters, not every character.
|
|
6
|
+
//
|
|
7
|
+
//2. MEMORY. The core runs on NUMBERS (code unit / code point), not on strings.
|
|
8
|
+
// A number < 2^31 in v8 is a Smi — it lives inside the pointer, no allocation at all.
|
|
9
|
+
// Set<number> hashes by value, Set<string> by string contents; the former is cheaper.
|
|
10
|
+
// A string appears exactly once — at the public boundary, in _emit.
|
|
11
|
+
// For cp < 0x10000 String.fromCharCode hits v8's single-character string table
|
|
12
|
+
// (the char is already cached by the engine) => 0 allocations too. Allocation is
|
|
13
|
+
// unavoidable only on a surrogate pair (2 code units, no cache for them).
|
|
14
|
+
//
|
|
15
|
+
//3. REUSE. There are many public methods, but the only real string traversal lives in
|
|
16
|
+
// _units/_runits. Everything else are transducer layers (_points, _where, _uniq, _map,
|
|
17
|
+
// _take, _emit) that take an iterator of numbers and return an iterator of numbers.
|
|
18
|
+
// Any public method = a composition of 2-4 links. No new traversal code appears.
|
|
19
|
+
//
|
|
20
|
+
//4. PLUGGABLE DATA SOURCE. The core never touches src directly — only through an adapter
|
|
21
|
+
// (see _adapter). Out of the box: string, Uint8Array/Buffer (utf-8), Array<number>.
|
|
22
|
+
// Register your own type and the whole method family starts working with it.
|
|
23
|
+
// The adapter is resolved ONCE per call and stored in a local variable, so the hot loop
|
|
24
|
+
// pays neither a Map lookup nor a megamorphic call.
|
|
25
|
+
//
|
|
26
|
+
//5. RETURN CODES of predicates (starts/ends/contains): 0 — no, 1 — yes, -1 — matched in full.
|
|
27
|
+
// -1 is truthy, so if (contains(a,b)) works as expected, yet "contains" and "equals"
|
|
28
|
+
// stay distinguishable without a second call. This is load-bearing, not an accident.
|
|
29
|
+
// NOTE: this is a CORE convention. str-ez wrappers must return a plain boolean outward,
|
|
30
|
+
// otherwise the word "ez" in the name would be a lie.
|
|
31
|
+
//
|
|
32
|
+
//6. ERRORS AND PRIMING. TypeError — wrong type. RangeError — index/length out of range.
|
|
33
|
+
// NotFound — target not found (its own class, so it is caught apart from bugs).
|
|
34
|
+
// A generator's body doesn't run until the first next(), so validation inside it would
|
|
35
|
+
// fire not at call time but whenever, in someone else's stack.
|
|
36
|
+
// The fix is PRIMING, and it is the very "compute one ahead":
|
|
37
|
+
// - the generator does ALL validation and setup before its first yield;
|
|
38
|
+
// - the first yield is a dummy barrier, carrying no value;
|
|
39
|
+
// - the calling method pulls next() once, crossing the barrier, and returns the generator.
|
|
40
|
+
// Result: the exception is thrown synchronously from the call, like an ordinary function,
|
|
41
|
+
// while useful values start at the second yield, so the consumer loses nothing.
|
|
42
|
+
// Cost — one idle yield per call and zero per element.
|
|
43
|
+
// Priming does NOT hinder completion: the barrier is crossed before the consumer pulls.
|
|
44
|
+
// CONSEQUENCE FOR CODE: a public "generator" is an ordinary method returning an
|
|
45
|
+
// already-crossed-barrier generator (return this._prime(this._gxxx(...))). Writing it
|
|
46
|
+
// as function* was impossible: validation would then move into the consumer's stack, i.e.
|
|
47
|
+
// exactly what this point forbids.
|
|
48
|
+
//
|
|
49
|
+
//7. LAZINESS AND max. A generator already stops when the consumer stops pulling, so max is
|
|
50
|
+
// sugar (internal _take), not an optimization. It is still needed: it lets you ask "are
|
|
51
|
+
// there more than N unique characters" and bail without an external counter.
|
|
52
|
+
// max < 1 — we throw: such a call is meaningless and almost always a bug at the call site.
|
|
53
|
+
//
|
|
54
|
+
//8. INTERNAL GENERATORS YIELD INDICES, NOT VALUES.
|
|
55
|
+
// This answers "how do you yield a [char, length] pair without allocation": you don't —
|
|
56
|
+
// so the pair need not be yielded. We yield ONE number, a boundary, and derive the rest:
|
|
57
|
+
// value = element at the index, length = next boundary minus current.
|
|
58
|
+
// Public methods differ only in what they pull out of the boundary.
|
|
59
|
+
// Hence the n suffix in the public API (omitn, splitn) — "give me the raw boundaries".
|
|
60
|
+
// CONSEQUENCE: where one traversal needs both boundaries and values (_runs, _win), the
|
|
61
|
+
// generator takes a mode and yields ONE projection. That is cheaper and more honest than
|
|
62
|
+
// three near-identical generators, and does not break "one number per yield".
|
|
63
|
+
//
|
|
64
|
+
//9. SATURATION. Where we count with a limit (runc, near), on reaching the limit we return
|
|
65
|
+
// Infinity, not the limit itself: an honest "at least this many" that does not get
|
|
66
|
+
// confused with a real result that happens to equal the limit.
|
|
67
|
+
//
|
|
68
|
+
//10. TABLES INSTEAD OF REGEXPS. Not one character-class check uses a regexp:
|
|
69
|
+
// /\p{L}/u.test(s) needs a string, i.e. an allocation per character in a hot loop.
|
|
70
|
+
// Instead — a sorted Int32Array of ranges and a binary search over the number.
|
|
71
|
+
// Tables are generated by an offline script (npm run tables) from Unicode properties, not
|
|
72
|
+
// at runtime, and load lazily: didn't ask about punctuation — its table doesn't exist in memory.
|
|
73
|
+
// HONEST CAVEAT: tables.js source holds STRINGS (25 KB for all of Unicode).
|
|
74
|
+
// A string always exists — it is part of the module text. What is built lazily is the
|
|
75
|
+
// Int32Array, and that is the real memory. Truly "not existing" is unreachable here without
|
|
76
|
+
// async import(), and async inside a generator would mean an async iterator across the
|
|
77
|
+
// whole public API — a price out of all proportion to the gain.
|
|
78
|
+
//
|
|
79
|
+
//11. THE CLASS IS A VTABLE, NOT A BAG OF FUNCTIONS. <<< the architecture's load-bearing decision
|
|
80
|
+
// Every internal call goes ONLY through this._helper(...), never through a direct function
|
|
81
|
+
// reference and never through an import. It looks like needless indirection, but it is
|
|
82
|
+
// exactly what makes str-ez possible: replace one method in a subclass and you replace it
|
|
83
|
+
// in ALL methods that use it, without touching their code. Free functions can't do this —
|
|
84
|
+
// they need a registry or a parameter in every signature, which is costlier and dirtier.
|
|
85
|
+
// Cost: a call through the prototype instead of a direct one. For a monomorphic call site
|
|
86
|
+
// v8 inlines it, so the cost is zero — but only as long as point 12 holds.
|
|
87
|
+
// DEVIATION FROM THE DRAFT: _class/_script/_width/_fold/_cplen were meant to be static,
|
|
88
|
+
// but static can't be called via this, so it can't be overridden in a subclass either.
|
|
89
|
+
// These are exactly the methods most often overridden (a custom width for the terminal,
|
|
90
|
+
// a custom folding for the Turkish i), so they became instance methods. Static remained
|
|
91
|
+
// only use/alphabet/confuse — those are registration, process-wide by nature.
|
|
92
|
+
//
|
|
93
|
+
//12. CONFIGURATIONS MUST BE FEW AND LONG-LIVED.
|
|
94
|
+
// The flip side of point 11: if more than 4 distinct str-im subclasses live in the process,
|
|
95
|
+
// the internal method call sites go from polymorphic to megamorphic, the inline cache
|
|
96
|
+
// degrades into a hash lookup, and all the savings from points 2-3 are wiped out.
|
|
97
|
+
// Hence rules that MUST land in the README in big letters:
|
|
98
|
+
// - _strim(overrides) is called at module load, not on every request
|
|
99
|
+
// - the result is cached by the overrides object (WeakMap); the same object yields
|
|
100
|
+
// literally the same class, not two identical ones
|
|
101
|
+
// - the default path pays nothing at all: the singleton is created once and is not subclassed
|
|
102
|
+
// Dev-build diagnostic: a counter of created configurations, a warning after the 4th.
|
|
103
|
+
|
|
104
|
+
import * as T from './tables.js';
|
|
105
|
+
|
|
106
|
+
export const UNICODE = T.UNICODE;
|
|
107
|
+
|
|
108
|
+
//=========================================================================
|
|
109
|
+
//=== ERRORS (point 6)
|
|
110
|
+
//=========================================================================
|
|
111
|
+
|
|
112
|
+
//target not found. Its own class, not a generic Error: "substring not found" is a
|
|
113
|
+
//routine outcome, caught pointwise, and must not be indistinguishable from a typo in code.
|
|
114
|
+
export class NotFound extends Error {
|
|
115
|
+
constructor(what) {
|
|
116
|
+
super(`str-im: not found: ${what}`);
|
|
117
|
+
this.name = 'NotFound';
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
//=========================================================================
|
|
122
|
+
//=== SOURCE ADAPTERS (point 4)
|
|
123
|
+
//=== dec says how to treat elements: 0 — utf-16 code units, 1 — utf-8 bytes,
|
|
124
|
+
//=== 2 — ready code points. One number instead of three different interfaces:
|
|
125
|
+
//=== the branch on it is taken ONCE before the loop, not per element.
|
|
126
|
+
//=========================================================================
|
|
127
|
+
|
|
128
|
+
const STR = Object.freeze({ size: (s) => s.length, at: (s, i) => s.charCodeAt(i), dec: 0 });
|
|
129
|
+
const U8 = Object.freeze({ size: (b) => b.length, at: (b, i) => b[i], dec: 1 });
|
|
130
|
+
const ARR = Object.freeze({ size: (a) => a.length, at: (a, i) => a[i], dec: 2 });
|
|
131
|
+
|
|
132
|
+
const REG = new Map(); //Map<constructor, adapter> — user sources
|
|
133
|
+
const ALPHA = new Map(); //Map<name, {v: Set<number>, c: Set<number>}>
|
|
134
|
+
const TABS = Object.create(null); //cache of materialized Int32Array
|
|
135
|
+
const ACS = new Map(); //cache of Aho-Corasick automata, see _ac
|
|
136
|
+
const AC_MAX = 32;
|
|
137
|
+
|
|
138
|
+
//base64 -> 6-bit value (inverse of the alphabet from build-tables.js). Uint8Array(128),
|
|
139
|
+
//indexed straight by charCodeAt: no Map, no branches in _decode. `d & 31` — the low
|
|
140
|
+
//5 VLQ bits, `d & 32` — the continuation bit.
|
|
141
|
+
const B64I = (() => {
|
|
142
|
+
const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
|
|
143
|
+
const t = new Uint8Array(128);
|
|
144
|
+
for (let i = 0; i < B64.length; i++) t[B64.charCodeAt(i)] = i;
|
|
145
|
+
return t;
|
|
146
|
+
})();
|
|
147
|
+
|
|
148
|
+
//grapheme cluster break classes (UAX #29). They match G from tools/build-tables.js —
|
|
149
|
+
//these are exactly the numbers stored in the GCB table. LV/LVT are not in the table
|
|
150
|
+
//(Hangul syllables AC00..D7A3 are computed arithmetically in _gcb), so their ids are
|
|
151
|
+
//above the tabular ones: they are born only at runtime and collide with nothing in the
|
|
152
|
+
//table. All values 0..13 fit in 4 bits — the table's high bit 16 is Extended_Pictographic (see _gcb).
|
|
153
|
+
const GCB = Object.freeze({
|
|
154
|
+
OTHER: 0, CR: 1, LF: 2, CTRL: 3, EXTEND: 4, ZWJ: 5, RI: 6, PREPEND: 7,
|
|
155
|
+
SPACING: 8, HL: 9, HV: 10, HT: 11, LV: 12, LVT: 13,
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
class strim {
|
|
159
|
+
|
|
160
|
+
//=========================================================================
|
|
161
|
+
//=== 0. INFRASTRUCTURE. All the real code lives here.
|
|
162
|
+
//=== The public methods below are compositions. Every call goes through this (point 11).
|
|
163
|
+
//=========================================================================
|
|
164
|
+
|
|
165
|
+
//--- 0.1 data source ---
|
|
166
|
+
|
|
167
|
+
//registry of source adapters. Resolved once per public call, the result stored in a
|
|
168
|
+
//local variable and passed onward as the adp parameter.
|
|
169
|
+
_adapter(src) {
|
|
170
|
+
if (typeof src === 'string') return STR;
|
|
171
|
+
if (src instanceof Uint8Array) return U8; //Buffer is a Uint8Array too
|
|
172
|
+
if (Array.isArray(src)) return ARR;
|
|
173
|
+
if (src != null) {
|
|
174
|
+
const a = REG.get(src.constructor);
|
|
175
|
+
if (a) return a;
|
|
176
|
+
}
|
|
177
|
+
throw new TypeError(`str-im: unsupported source ${src === null ? 'null' : typeof src}. Register it via strim.use(ctor, adapter)`);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
//registering your own type. Static, not an instance method: the registry is process-wide,
|
|
181
|
+
//otherwise two instances would see different type sets and point 4 would stop working.
|
|
182
|
+
static use(ctor, adapter) {
|
|
183
|
+
if (typeof ctor !== 'function') throw new TypeError('str-im: use(ctor, adapter) — ctor must be a constructor');
|
|
184
|
+
if (!adapter || typeof adapter.size !== 'function' || typeof adapter.at !== 'function') {
|
|
185
|
+
throw new TypeError('str-im: an adapter must have size(src) and at(src, i)');
|
|
186
|
+
}
|
|
187
|
+
const dec = adapter.dec | 0;
|
|
188
|
+
if (dec < 0 || dec > 2) throw new RangeError('str-im: adapter.dec must be 0 (utf-16), 1 (utf-8) or 2 (code points)');
|
|
189
|
+
REG.set(ctor, Object.freeze({ size: adapter.size, at: adapter.at, dec }));
|
|
190
|
+
return ctor;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
//--- 0.2 traversal (the only two places with an index loop) ---
|
|
194
|
+
|
|
195
|
+
*_units(src, adp) {
|
|
196
|
+
const size = adp.size(src);
|
|
197
|
+
for (let i = 0; i < size; i++) yield adp.at(src, i);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
*_runits(src, adp) {
|
|
201
|
+
for (let i = adp.size(src) - 1; i >= 0; i--) yield adp.at(src, i);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
//code units -> code points. The very "compute one ahead": on seeing a high surrogate
|
|
205
|
+
//(0xD800..0xDBFF) you must peek at the next unit.
|
|
206
|
+
//We keep ONE number in a local variable as a lookahead buffer — not an array, not an object.
|
|
207
|
+
//If there is no next unit or it is not a low surrogate — we yield the lone surrogate as is
|
|
208
|
+
//(we neither fix nor throw on a broken string: it is the user's data, not our business).
|
|
209
|
+
//The extra lookahead doesn't hinder completion: the buffer is flushed after the loop.
|
|
210
|
+
*_points(units) {
|
|
211
|
+
let hi = -1;
|
|
212
|
+
for (const u of units) {
|
|
213
|
+
if (hi >= 0) {
|
|
214
|
+
if (u >= 0xdc00 && u <= 0xdfff) { yield (hi - 0xd800) * 0x400 + u - 0xdc00 + 0x10000; hi = -1; continue; }
|
|
215
|
+
yield hi; //lone high surrogate — yield as is
|
|
216
|
+
hi = -1;
|
|
217
|
+
}
|
|
218
|
+
if (u >= 0xd800 && u <= 0xdbff) { hi = u; continue; }
|
|
219
|
+
yield u;
|
|
220
|
+
}
|
|
221
|
+
if (hi >= 0) yield hi;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
//R->L: mirror image, but you must look back — the LOW surrogate arrives first, then the HIGH.
|
|
225
|
+
*_rpoints(runits) {
|
|
226
|
+
let lo = -1;
|
|
227
|
+
for (const u of runits) {
|
|
228
|
+
if (lo >= 0) {
|
|
229
|
+
if (u >= 0xd800 && u <= 0xdbff) { yield (u - 0xd800) * 0x400 + lo - 0xdc00 + 0x10000; lo = -1; continue; }
|
|
230
|
+
yield lo;
|
|
231
|
+
lo = -1;
|
|
232
|
+
}
|
|
233
|
+
if (u >= 0xdc00 && u <= 0xdfff) { lo = u; continue; }
|
|
234
|
+
yield u;
|
|
235
|
+
}
|
|
236
|
+
if (lo >= 0) yield lo;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
//utf-8 -> code points. Streaming automaton by lead byte: 0xxxxxxx=1, 110=2,
|
|
240
|
+
//1110=3, 11110=4. Broken input doesn't throw, it yields U+FFFD — exactly like TextDecoder,
|
|
241
|
+
//so that "count the characters" never crashes on someone else's data. Whoever needs the
|
|
242
|
+
//error position, not the replacement, calls badn().
|
|
243
|
+
*_u8points(units) {
|
|
244
|
+
let need = 0, cp = 0, min = 0;
|
|
245
|
+
for (const b of units) {
|
|
246
|
+
if (need !== 0 && (b & 0xc0) !== 0x80) { yield 0xfffd; need = 0; } //cut off mid-sequence
|
|
247
|
+
if (need === 0) {
|
|
248
|
+
if (b < 0x80) yield b;
|
|
249
|
+
else if (b < 0xc2) yield 0xfffd; //continuation without a lead, or overlong start
|
|
250
|
+
else if (b < 0xe0) { cp = b & 0x1f; need = 1; min = 0x80; }
|
|
251
|
+
else if (b < 0xf0) { cp = b & 0x0f; need = 2; min = 0x800; }
|
|
252
|
+
else if (b < 0xf5) { cp = b & 0x07; need = 3; min = 0x10000; }
|
|
253
|
+
else yield 0xfffd;
|
|
254
|
+
} else {
|
|
255
|
+
cp = (cp << 6) | (b & 0x3f);
|
|
256
|
+
if (--need === 0) yield (cp < min || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff)) ? 0xfffd : cp;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
if (need) yield 0xfffd; //truncated at end of buffer
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
//utf-8 right to left. Continuations arrive in reverse order, so the first one seen is
|
|
263
|
+
//the LOWEST bits. Three local variables instead of an array.
|
|
264
|
+
*_ru8points(runits) {
|
|
265
|
+
let c1 = 0, c2 = 0, c3 = 0, n = 0;
|
|
266
|
+
for (const b of runits) {
|
|
267
|
+
if ((b & 0xc0) === 0x80) {
|
|
268
|
+
if (n === 3) { yield 0xfffd; n = 0; }
|
|
269
|
+
if (n === 0) c1 = b & 0x3f; else if (n === 1) c2 = b & 0x3f; else c3 = b & 0x3f;
|
|
270
|
+
n++;
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
if (b < 0x80) { if (n) { yield 0xfffd; n = 0; } yield b; continue; }
|
|
274
|
+
let cp = -1, min = 0;
|
|
275
|
+
if (n === 1 && b >= 0xc2 && b < 0xe0) { cp = ((b & 0x1f) << 6) | c1; min = 0x80; }
|
|
276
|
+
else if (n === 2 && b >= 0xe0 && b < 0xf0) { cp = ((b & 0x0f) << 12) | (c2 << 6) | c1; min = 0x800; }
|
|
277
|
+
else if (n === 3 && b >= 0xf0 && b < 0xf5) { cp = ((b & 0x07) << 18) | (c3 << 12) | (c2 << 6) | c1; min = 0x10000; }
|
|
278
|
+
n = 0;
|
|
279
|
+
yield (cp < min || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff)) ? 0xfffd : cp;
|
|
280
|
+
}
|
|
281
|
+
if (n) yield 0xfffd;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
//code points of the source, whatever it is. The branch on dec is taken ONCE, before the loop.
|
|
285
|
+
*_cps(src, adp) {
|
|
286
|
+
if (adp.dec === 1) yield* this._u8points(this._units(src, adp));
|
|
287
|
+
else if (adp.dec === 2) yield* this._units(src, adp);
|
|
288
|
+
else yield* this._points(this._units(src, adp));
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
*_rcps(src, adp) {
|
|
292
|
+
if (adp.dec === 1) yield* this._ru8points(this._runits(src, adp));
|
|
293
|
+
else if (adp.dec === 2) yield* this._runits(src, adp);
|
|
294
|
+
else yield* this._rpoints(this._runits(src, adp));
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
//INDICES of the start of each code point, in source units (point 8).
|
|
298
|
+
//Needed where the answer is a position in the source data, not the character itself:
|
|
299
|
+
//wgram, whas, _graph, wcut. The value at an index is fetched via _at.
|
|
300
|
+
*_pointn(src, adp) {
|
|
301
|
+
const size = adp.size(src);
|
|
302
|
+
if (adp.dec === 1) {
|
|
303
|
+
//in utf-8 the start of a character is any byte other than a continuation. Broken bytes
|
|
304
|
+
//are honestly counted as separate positions, just like in _u8points.
|
|
305
|
+
for (let i = 0; i < size; i++) if ((adp.at(src, i) & 0xc0) !== 0x80) yield i;
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
if (adp.dec === 2) { for (let i = 0; i < size; i++) yield i; return; }
|
|
309
|
+
for (let i = 0; i < size; i++) {
|
|
310
|
+
yield i;
|
|
311
|
+
const u = adp.at(src, i);
|
|
312
|
+
if (u >= 0xd800 && u <= 0xdbff && i + 1 < size) {
|
|
313
|
+
const l = adp.at(src, i + 1);
|
|
314
|
+
if (l >= 0xdc00 && l <= 0xdfff) i++;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
//the code point starting at position i. Companion to _pointn: index -> value (point 8).
|
|
320
|
+
_at(src, adp, i) {
|
|
321
|
+
const size = adp.size(src);
|
|
322
|
+
if (i < 0 || i >= size) return -1;
|
|
323
|
+
if (adp.dec === 2) return adp.at(src, i);
|
|
324
|
+
if (adp.dec === 0) {
|
|
325
|
+
const u = adp.at(src, i);
|
|
326
|
+
if (u >= 0xd800 && u <= 0xdbff && i + 1 < size) {
|
|
327
|
+
const l = adp.at(src, i + 1);
|
|
328
|
+
if (l >= 0xdc00 && l <= 0xdfff) return (u - 0xd800) * 0x400 + l - 0xdc00 + 0x10000;
|
|
329
|
+
}
|
|
330
|
+
return u;
|
|
331
|
+
}
|
|
332
|
+
const b = adp.at(src, i);
|
|
333
|
+
if (b < 0x80) return b;
|
|
334
|
+
let need, cp, min;
|
|
335
|
+
if (b < 0xc2) return 0xfffd;
|
|
336
|
+
else if (b < 0xe0) { cp = b & 0x1f; need = 1; min = 0x80; }
|
|
337
|
+
else if (b < 0xf0) { cp = b & 0x0f; need = 2; min = 0x800; }
|
|
338
|
+
else if (b < 0xf5) { cp = b & 0x07; need = 3; min = 0x10000; }
|
|
339
|
+
else return 0xfffd;
|
|
340
|
+
if (i + need >= size) return 0xfffd; //sequence does not fit in the buffer
|
|
341
|
+
for (let k = 1; k <= need; k++) {
|
|
342
|
+
const c = adp.at(src, i + k);
|
|
343
|
+
if ((c & 0xc0) !== 0x80) return 0xfffd;
|
|
344
|
+
cp = (cp << 6) | (c & 0x3f);
|
|
345
|
+
}
|
|
346
|
+
return (cp < min || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff)) ? 0xfffd : cp;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
//--- 0.3 transducers (take a stream of numbers, return a stream of numbers) ---
|
|
350
|
+
|
|
351
|
+
//deduplication. Set<number>. Returns only first occurrences.
|
|
352
|
+
//This is exactly what replaces the idiom "str.lastIndexOf(c) === i" — that one is O(n^2)
|
|
353
|
+
//and not lazy, whereas Set.add in a loop is O(n) and lets you bail mid-string.
|
|
354
|
+
*_uniq(nums, max = Infinity) {
|
|
355
|
+
const seen = new Set();
|
|
356
|
+
for (const n of nums) {
|
|
357
|
+
if (seen.has(n)) continue;
|
|
358
|
+
seen.add(n);
|
|
359
|
+
yield n;
|
|
360
|
+
if (seen.size >= max) return;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
//filter by a number->boolean predicate. Placed BEFORE _uniq: fewer Set insertions.
|
|
365
|
+
*_where(nums, test) {
|
|
366
|
+
for (const n of nums) if (test(n)) yield n;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
//number->number transform (ichar, ifind: case folding before comparison).
|
|
370
|
+
*_map(nums, fn) {
|
|
371
|
+
for (const n of nums) yield fn(n);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
//count limit. A separate link so max doesn't get smeared across every method.
|
|
375
|
+
*_take(nums, max) {
|
|
376
|
+
if (max === Infinity) { yield* nums; return; }
|
|
377
|
+
let i = 0;
|
|
378
|
+
for (const n of nums) {
|
|
379
|
+
yield n;
|
|
380
|
+
if (++i >= max) return;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
//sliding window of size n. A ring buffer Int32Array(n) is allocated once per call,
|
|
385
|
+
//not per window. mode — which projection of the window is needed (point 8):
|
|
386
|
+
// 0 — ordinal index of the window start
|
|
387
|
+
// 1 — rolling hash of the contents (Rabin-Karp, next from previous in O(1))
|
|
388
|
+
// 2 — value at the window start (needed when the input is a stream of INDICES)
|
|
389
|
+
//Base for n-grams, hash, and n-gram entropy.
|
|
390
|
+
*_win(nums, n, mode = 0) {
|
|
391
|
+
const ring = new Int32Array(n);
|
|
392
|
+
//M — a prime < 2^30, so that h*B and out*Bp are guaranteed to fit in double precision
|
|
393
|
+
const M = 1000000007, B = 131;
|
|
394
|
+
let bp = 1;
|
|
395
|
+
if (mode === 1) for (let k = 1; k < n; k++) bp = (bp * B) % M;
|
|
396
|
+
let i = 0, h = 0;
|
|
397
|
+
for (const v of nums) {
|
|
398
|
+
const slot = i % n;
|
|
399
|
+
const out = ring[slot];
|
|
400
|
+
ring[slot] = v;
|
|
401
|
+
if (mode === 1) {
|
|
402
|
+
h = i < n ? (h * B + v) % M : ((h - out * bp) % M * B + v) % M;
|
|
403
|
+
if (h < 0) h += M;
|
|
404
|
+
}
|
|
405
|
+
i++;
|
|
406
|
+
if (i < n) continue;
|
|
407
|
+
if (mode === 0) yield i - n;
|
|
408
|
+
else if (mode === 1) yield h;
|
|
409
|
+
else yield ring[i % n];
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
//--- 0.4 terminals (fold a stream into a number) ---
|
|
414
|
+
|
|
415
|
+
//count the stream to the end. One method for len/ulen/glen/wlen — the counters themselves
|
|
416
|
+
//differ only in which stream is fed to it.
|
|
417
|
+
_count(nums) {
|
|
418
|
+
let n = 0;
|
|
419
|
+
for (const _ of nums) n++;
|
|
420
|
+
return n;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
//frequencies. The one place in the library where allocation is unavoidable and deliberate:
|
|
424
|
+
//entropy needs all the counters at once, it can't be computed lazily.
|
|
425
|
+
//For the BMP — a lazily growing Int32Array indexed by code point (direct indexing,
|
|
426
|
+
//no hashing); for astral and for n-gram hashes — a Map. A hybrid, not a single Map,
|
|
427
|
+
//because 95% of real inputs fit entirely in the first few hundred array cells.
|
|
428
|
+
_freq(nums) {
|
|
429
|
+
let arr = new Int32Array(256), map = null, total = 0, top = -1;
|
|
430
|
+
for (const n of nums) {
|
|
431
|
+
total++;
|
|
432
|
+
if (n >= 0 && n < 0x10000) {
|
|
433
|
+
if (n >= arr.length) {
|
|
434
|
+
let cap = arr.length;
|
|
435
|
+
while (cap <= n) cap *= 2;
|
|
436
|
+
const a = new Int32Array(cap > 0x10000 ? 0x10000 : cap);
|
|
437
|
+
a.set(arr);
|
|
438
|
+
arr = a;
|
|
439
|
+
}
|
|
440
|
+
arr[n]++;
|
|
441
|
+
if (n > top) top = n;
|
|
442
|
+
} else {
|
|
443
|
+
if (map === null) map = new Map();
|
|
444
|
+
map.set(n, (map.get(n) || 0) + 1);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
return { arr, top, map, total };
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
//THE ONE point where a number becomes a string.
|
|
451
|
+
//cp < 0x10000 -> fromCharCode (0 alloc, v8 cache); otherwise fromCodePoint (alloc unavoidable).
|
|
452
|
+
*_emit(nums) {
|
|
453
|
+
for (const n of nums) yield n < 0x10000 ? String.fromCharCode(n) : String.fromCodePoint(n);
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
//priming (point 6): cross the barrier so that validation inside the generator fires
|
|
457
|
+
//synchronously, in the caller's stack, and not at some later point in the consumer's.
|
|
458
|
+
_prime(g) {
|
|
459
|
+
g.next();
|
|
460
|
+
return g;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
//max validation. A separate method because it is identical across two dozen methods
|
|
464
|
+
//and must not drift apart.
|
|
465
|
+
_max(max) {
|
|
466
|
+
if (typeof max !== 'number' || Number.isNaN(max)) throw new TypeError('str-im: max must be a number');
|
|
467
|
+
if (max < 1) throw new RangeError(`str-im: max must be >= 1, got ${max}`);
|
|
468
|
+
return max;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
//--- 0.5 tables and classification (point 10) ---
|
|
472
|
+
|
|
473
|
+
//base64-VLQ -> Int32Array. arity: 2 — ranges [s,e], 3 — ranges with a value
|
|
474
|
+
//[s,e,v], 0 — a map [from,to] with zigzag on the second number.
|
|
475
|
+
_decode(s, arity) {
|
|
476
|
+
//first pass — only count how many numbers there are, so the Int32Array is the exact
|
|
477
|
+
//size and needs neither to grow nor to be trimmed
|
|
478
|
+
let cnt = 0;
|
|
479
|
+
for (let i = 0; i < s.length; i++) if ((B64I[s.charCodeAt(i)] & 32) === 0) cnt++;
|
|
480
|
+
const out = new Int32Array(cnt);
|
|
481
|
+
let k = 0, acc = 0, shift = 1;
|
|
482
|
+
for (let i = 0; i < s.length; i++) {
|
|
483
|
+
const d = B64I[s.charCodeAt(i)];
|
|
484
|
+
acc += (d & 31) * shift;
|
|
485
|
+
if (d & 32) { shift *= 32; continue; }
|
|
486
|
+
out[k++] = acc;
|
|
487
|
+
acc = 0;
|
|
488
|
+
shift = 1;
|
|
489
|
+
}
|
|
490
|
+
//deltas -> absolute values
|
|
491
|
+
if (arity === 0) {
|
|
492
|
+
let prev = 0;
|
|
493
|
+
for (let i = 0; i < out.length; i += 2) {
|
|
494
|
+
const from = prev + out[i];
|
|
495
|
+
const z = out[i + 1];
|
|
496
|
+
out[i] = from;
|
|
497
|
+
out[i + 1] = from + (z & 1 ? -(z >>> 1) : z >>> 1);
|
|
498
|
+
prev = from;
|
|
499
|
+
}
|
|
500
|
+
} else {
|
|
501
|
+
let prev = -1;
|
|
502
|
+
for (let i = 0; i < out.length; i += arity) {
|
|
503
|
+
const st = prev + out[i] + 1;
|
|
504
|
+
const en = st + out[i + 1];
|
|
505
|
+
out[i] = st;
|
|
506
|
+
out[i + 1] = en;
|
|
507
|
+
prev = en;
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
return out;
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
//lazy range table by name (Lu, Ll, L, M, Nd, P, S, WS, EP, GCB, SCRIPT...).
|
|
514
|
+
//Materialized on first access and lives to the end of the process: the table is immutable,
|
|
515
|
+
//there is no point recreating it, and an Int32Array of a few hundred ranges is a few KB.
|
|
516
|
+
_class(name) {
|
|
517
|
+
const t = TABS[name];
|
|
518
|
+
if (t !== undefined) return t;
|
|
519
|
+
const raw = T[name];
|
|
520
|
+
if (raw === undefined) throw new TypeError(`str-im: no table '${name}'`);
|
|
521
|
+
return (TABS[name] = this._decode(raw, name === 'FOLD' ? 0 : (name === 'SCRIPT' || name === 'GCB') ? 3 : 2));
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
//binary search over [start,end] pairs. Returns the pair index or -1.
|
|
525
|
+
//This is what replaces /\p{...}/u.test(String.fromCodePoint(cp)) in the hot loop.
|
|
526
|
+
_find(tab, cp, arity) {
|
|
527
|
+
let lo = 0, hi = tab.length / arity - 1;
|
|
528
|
+
while (lo <= hi) {
|
|
529
|
+
const mid = (lo + hi) >> 1, k = mid * arity;
|
|
530
|
+
if (cp < tab[k]) hi = mid - 1;
|
|
531
|
+
else if (cp > tab[k + 1]) lo = mid + 1;
|
|
532
|
+
else return k;
|
|
533
|
+
}
|
|
534
|
+
return -1;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
//does cp belong to class name
|
|
538
|
+
_is(name, cp) {
|
|
539
|
+
return this._find(this._class(name), cp, 2) >= 0;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
//the script of a code point -> numeric id (0 — Unknown, including the Private Use Area).
|
|
543
|
+
//The same range table, only the value is not boolean but an id. scr and mix grow from here.
|
|
544
|
+
_script(cp) {
|
|
545
|
+
const tab = this._class('SCRIPT');
|
|
546
|
+
const k = this._find(tab, cp, 3);
|
|
547
|
+
return k < 0 ? 0 : tab[k + 2];
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
//script name by id. The flip side of _script: outward we return a name, inside we run numbers.
|
|
551
|
+
_scriptName(id) {
|
|
552
|
+
return id === 0 ? 'Unknown' : T.SCRIPTS[id - 1];
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
//width in columns: 0 (combining, invisible), 1 (ordinary), 2 (wide CJK, emoji).
|
|
556
|
+
//Zero width is taken from GCB, not from a separate table: Extend and Control are
|
|
557
|
+
//exactly what takes no space, and duplicating them in a list would be a lie about
|
|
558
|
+
//the size of the tables.
|
|
559
|
+
_width(cp) {
|
|
560
|
+
if (cp === 0) return 0;
|
|
561
|
+
const g = this._gcb(cp) & 15;
|
|
562
|
+
if (g === GCB.EXTEND || g === GCB.CTRL || g === GCB.CR || g === GCB.LF || g === GCB.ZWJ) return 0;
|
|
563
|
+
if (g === GCB.HV || g === GCB.HT) return 0; //Hangul V/T are drawn inside the syllable
|
|
564
|
+
return this._find(this._class('WIDE'), cp, 2) >= 0 ? 2 : 1;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
//case folding (simple case folding). By table, not via toLowerCase: the latter needs
|
|
568
|
+
//a string. Needed by ichar, ifind and skel.
|
|
569
|
+
_fold(cp) {
|
|
570
|
+
const tab = this._class('FOLD');
|
|
571
|
+
let lo = 0, hi = tab.length / 2 - 1;
|
|
572
|
+
while (lo <= hi) {
|
|
573
|
+
const mid = (lo + hi) >> 1, k = mid * 2;
|
|
574
|
+
if (cp < tab[k]) hi = mid - 1;
|
|
575
|
+
else if (cp > tab[k]) lo = mid + 1;
|
|
576
|
+
else return tab[k + 1];
|
|
577
|
+
}
|
|
578
|
+
return cp;
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
//how many bytes a code point takes in utf-8. Pure range arithmetic, no encoding.
|
|
582
|
+
//Base for blen and bcut.
|
|
583
|
+
_cplen(cp) {
|
|
584
|
+
return cp < 0x80 ? 1 : cp < 0x800 ? 2 : cp < 0x10000 ? 3 : 4;
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
//grapheme cluster break class + bit 16 (Extended_Pictographic).
|
|
588
|
+
//Hangul AC00..D7A3 is computed arithmetically, not by table: 11172 syllables would give
|
|
589
|
+
//~800 ranges for the sake of one modulo.
|
|
590
|
+
_gcb(cp) {
|
|
591
|
+
if (cp >= 0xac00 && cp <= 0xd7a3) return (cp - 0xac00) % 28 === 0 ? GCB.LV : GCB.LVT;
|
|
592
|
+
const tab = this._class('GCB');
|
|
593
|
+
const k = this._find(tab, cp, 3);
|
|
594
|
+
return k < 0 ? GCB.OTHER : tab[k + 2];
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
//alphabets for vowels/consonants. They can't be expressed via Unicode: this is a property
|
|
598
|
+
//of the language, not of the character. Stored as Set<number> of code points.
|
|
599
|
+
//By default — Latin + Cyrillic. y/й/ы/ь are contentious, moved into a separate
|
|
600
|
+
//'semivowel' set so the user decides where to put them.
|
|
601
|
+
static alphabet(name, vowels, consonants) {
|
|
602
|
+
if (typeof name !== 'string') throw new TypeError('str-im: alphabet(name, vowels, consonants) — name must be a string');
|
|
603
|
+
if (vowels === undefined && consonants === undefined) {
|
|
604
|
+
const a = ALPHA.get(name);
|
|
605
|
+
if (!a) throw new NotFound(`alphabet '${name}'`);
|
|
606
|
+
return a;
|
|
607
|
+
}
|
|
608
|
+
const set = (s) => {
|
|
609
|
+
const out = new Set();
|
|
610
|
+
for (const ch of String(s ?? '')) out.add(ch.codePointAt(0));
|
|
611
|
+
return out;
|
|
612
|
+
};
|
|
613
|
+
const a = Object.freeze({ v: set(vowels), c: set(consonants) });
|
|
614
|
+
ALPHA.set(name, a);
|
|
615
|
+
return a;
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
//the active alphabet. A separate method so a subclass can switch language with a single
|
|
619
|
+
//override, without touching vchar/cchar (point 11).
|
|
620
|
+
_alphabet() {
|
|
621
|
+
return ALPHA.get('default');
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
//--- 0.6 automata ---
|
|
625
|
+
|
|
626
|
+
//boundaries of runs of identical elements. THE CORE of the whole cons family and flat.
|
|
627
|
+
//State is one number (the previous value), memory O(1) regardless of input length.
|
|
628
|
+
//mode (point 8): 0 — start index of the run, 1 — run value, 2 — run length.
|
|
629
|
+
//That is why cons/consc/consg/flat/style contain no logic of their own at all.
|
|
630
|
+
*_runs(nums, mode = 0) {
|
|
631
|
+
let prev = 0, start = 0, i = 0;
|
|
632
|
+
for (const n of nums) {
|
|
633
|
+
if (i === 0) prev = n;
|
|
634
|
+
else if (n !== prev) {
|
|
635
|
+
yield mode === 0 ? start : mode === 1 ? prev : i - start;
|
|
636
|
+
prev = n;
|
|
637
|
+
start = i;
|
|
638
|
+
}
|
|
639
|
+
i++;
|
|
640
|
+
}
|
|
641
|
+
if (i > 0) yield mode === 0 ? start : mode === 1 ? prev : i - start;
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
//grapheme cluster boundaries per UAX #29. Yields INDICES IN SOURCE UNITS
|
|
645
|
+
//(point 8): 0, the start of each next cluster, and size at the end as the closing
|
|
646
|
+
//boundary. Cluster i = [b(i), b(i+1)). Base for glen, gchar, dlen, wcut and wrap.
|
|
647
|
+
//
|
|
648
|
+
//Rules: GB3 CR×LF, GB4/5 break around Control, GB6-8 Hangul, GB9 ×Extend,
|
|
649
|
+
//GB9a ×SpacingMark, GB9b Prepend×, GB11 emoji ZWJ emoji, GB12/13 pairs of
|
|
650
|
+
//regional indicators, otherwise GB999 break.
|
|
651
|
+
*_graph(src, adp) {
|
|
652
|
+
const size = adp.size(src);
|
|
653
|
+
if (size === 0) return;
|
|
654
|
+
let prev = -1, ri = 0, pict = false, first = true;
|
|
655
|
+
for (const i of this._pointn(src, adp)) {
|
|
656
|
+
const raw = this._gcb(this._at(src, adp, i));
|
|
657
|
+
const cls = raw & 15;
|
|
658
|
+
if (first) {
|
|
659
|
+
yield 0;
|
|
660
|
+
first = false;
|
|
661
|
+
} else if (this._gbreak(prev, cls, ri, pict)) {
|
|
662
|
+
yield i;
|
|
663
|
+
}
|
|
664
|
+
//state for GB12/13: length of the current chain of regional indicators
|
|
665
|
+
ri = cls === GCB.RI ? ri + 1 : 0;
|
|
666
|
+
//state for GB11: "saw a pictograph, then only Extend, then ZWJ"
|
|
667
|
+
if (raw & 16) pict = true;
|
|
668
|
+
else if (cls !== GCB.EXTEND && cls !== GCB.ZWJ) pict = false;
|
|
669
|
+
prev = cls;
|
|
670
|
+
}
|
|
671
|
+
yield size;
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
//whether to break between class a and class b. Extracted from _graph as a separate method
|
|
675
|
+
//so the rules can be overridden (point 11) — e.g. to glue emoji tags together.
|
|
676
|
+
_gbreak(a, b, ri, pict) {
|
|
677
|
+
if (a === GCB.CR && b === GCB.LF) return false; //GB3
|
|
678
|
+
if (a === GCB.CTRL || a === GCB.CR || a === GCB.LF) return true; //GB4
|
|
679
|
+
if (b === GCB.CTRL || b === GCB.CR || b === GCB.LF) return true; //GB5
|
|
680
|
+
if (a === GCB.HL && (b === GCB.HL || b === GCB.HV || b === GCB.LV || b === GCB.LVT)) return false; //GB6
|
|
681
|
+
if ((a === GCB.LV || a === GCB.HV) && (b === GCB.HV || b === GCB.HT)) return false; //GB7
|
|
682
|
+
if ((a === GCB.LVT || a === GCB.HT) && b === GCB.HT) return false; //GB8
|
|
683
|
+
if (b === GCB.EXTEND || b === GCB.ZWJ) return false; //GB9
|
|
684
|
+
if (b === GCB.SPACING) return false; //GB9a
|
|
685
|
+
if (a === GCB.PREPEND) return false; //GB9b
|
|
686
|
+
if (a === GCB.ZWJ && pict) return false; //GB11 — decision made from the pict flag
|
|
687
|
+
if (a === GCB.RI && b === GCB.RI && ri % 2 === 1) return false; //GB12/13
|
|
688
|
+
return true; //GB999
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
//normalize a needle set to an array of Int32Array code units + a cache key.
|
|
692
|
+
//Accepts a string, a number (code point), or an iterable of those.
|
|
693
|
+
_needles(target, fold) {
|
|
694
|
+
const list = [];
|
|
695
|
+
const one = (t) => {
|
|
696
|
+
if (typeof t === 'number') t = String.fromCodePoint(t);
|
|
697
|
+
if (typeof t !== 'string') throw new TypeError('str-im: a needle must be a string or a code point');
|
|
698
|
+
if (t.length === 0) return; //an empty needle would match everywhere and hang the automaton
|
|
699
|
+
const a = new Int32Array(t.length);
|
|
700
|
+
for (let i = 0; i < t.length; i++) a[i] = fold ? this._fold(t.charCodeAt(i)) : t.charCodeAt(i);
|
|
701
|
+
list.push(a);
|
|
702
|
+
};
|
|
703
|
+
if (typeof target === 'string' || typeof target === 'number') one(target);
|
|
704
|
+
else if (target && typeof target[Symbol.iterator] === 'function') for (const t of target) one(t);
|
|
705
|
+
else throw new TypeError('str-im: target must be a string, a code point, or an iterable of them');
|
|
706
|
+
if (list.length === 0) throw new TypeError('str-im: empty needle set');
|
|
707
|
+
return list;
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
//Aho-Corasick: one pass over the input, searching all needles of the set at once.
|
|
711
|
+
//Built once per set and CACHED by it, because the same set is almost always used in a
|
|
712
|
+
//loop over many strings.
|
|
713
|
+
//Storage — flat Int32Array: a tree of objects would allocate per node and destroy all
|
|
714
|
+
//the savings. Transitions are kept sorted by character and searched by binary search —
|
|
715
|
+
//that is O(log k) per step without a 64K string per node.
|
|
716
|
+
//The core for find, lfind, ifind, omit, omitn, clear, split, splitn.
|
|
717
|
+
//For a single needle the automaton degenerates into KMP, no separate code needed.
|
|
718
|
+
_ac(needles) {
|
|
719
|
+
//cache key — the needles themselves. as a separator is safe: empty needles are dropped
|
|
720
|
+
let key = '';
|
|
721
|
+
for (const n of needles) { key += ' '; for (let i = 0; i < n.length; i++) key += String.fromCharCode(n[i]); }
|
|
722
|
+
const hit = ACS.get(key);
|
|
723
|
+
if (hit) { ACS.delete(key); ACS.set(key, hit); return hit; } //LRU: refresh
|
|
724
|
+
//--- build the trie on temporary Maps (build stage only) ---
|
|
725
|
+
const kids = [new Map()];
|
|
726
|
+
const len = [0];
|
|
727
|
+
let maxLen = 0;
|
|
728
|
+
for (const n of needles) {
|
|
729
|
+
let node = 0;
|
|
730
|
+
for (let i = 0; i < n.length; i++) {
|
|
731
|
+
const ch = n[i];
|
|
732
|
+
let nxt = kids[node].get(ch);
|
|
733
|
+
if (nxt === undefined) {
|
|
734
|
+
nxt = kids.length;
|
|
735
|
+
kids.push(new Map());
|
|
736
|
+
len.push(0);
|
|
737
|
+
kids[node].set(ch, nxt);
|
|
738
|
+
}
|
|
739
|
+
node = nxt;
|
|
740
|
+
}
|
|
741
|
+
if (n.length > len[node]) len[node] = n.length;
|
|
742
|
+
if (n.length > maxLen) maxLen = n.length;
|
|
743
|
+
}
|
|
744
|
+
const n = kids.length;
|
|
745
|
+
const fail = new Int32Array(n);
|
|
746
|
+
const out = new Int32Array(n); //length of the needle ending here; 0 — none ends here
|
|
747
|
+
const outNext = new Int32Array(n).fill(-1); //chain of shorter matches
|
|
748
|
+
for (let i = 0; i < n; i++) out[i] = len[i];
|
|
749
|
+
//--- BFS: fail links ---
|
|
750
|
+
const queue = new Int32Array(n);
|
|
751
|
+
let qh = 0, qt = 0;
|
|
752
|
+
for (const [, v] of kids[0]) { fail[v] = 0; queue[qt++] = v; }
|
|
753
|
+
while (qh < qt) {
|
|
754
|
+
const u = queue[qh++];
|
|
755
|
+
outNext[u] = out[fail[u]] ? fail[u] : outNext[fail[u]];
|
|
756
|
+
for (const [ch, v] of kids[u]) {
|
|
757
|
+
let f = fail[u];
|
|
758
|
+
for (;;) {
|
|
759
|
+
const t = kids[f].get(ch);
|
|
760
|
+
if (t !== undefined) { fail[v] = t; break; }
|
|
761
|
+
if (f === 0) { fail[v] = 0; break; }
|
|
762
|
+
f = fail[f];
|
|
763
|
+
}
|
|
764
|
+
queue[qt++] = v;
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
//--- flatten: Map -> three Int32Array, transitions sorted by character ---
|
|
768
|
+
let total = 0;
|
|
769
|
+
for (let i = 0; i < n; i++) total += kids[i].size;
|
|
770
|
+
const start = new Int32Array(n + 1);
|
|
771
|
+
const chars = new Int32Array(total);
|
|
772
|
+
const nodes = new Int32Array(total);
|
|
773
|
+
let k = 0;
|
|
774
|
+
for (let i = 0; i < n; i++) {
|
|
775
|
+
start[i] = k;
|
|
776
|
+
const pairs = [...kids[i].entries()].sort((a, b) => a[0] - b[0]);
|
|
777
|
+
for (const [ch, v] of pairs) { chars[k] = ch; nodes[k] = v; k++; }
|
|
778
|
+
}
|
|
779
|
+
start[n] = k;
|
|
780
|
+
const ac = Object.freeze({ start, chars, nodes, fail, out, outNext, maxLen });
|
|
781
|
+
if (ACS.size >= AC_MAX) ACS.delete(ACS.keys().next().value);
|
|
782
|
+
ACS.set(key, ac);
|
|
783
|
+
return ac;
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
//one automaton step: from node `node` on character ch. Descend the fail links until
|
|
787
|
+
//a transition is found or we hit the root.
|
|
788
|
+
_step(ac, node, ch) {
|
|
789
|
+
for (;;) {
|
|
790
|
+
const lo0 = ac.start[node], hi0 = ac.start[node + 1];
|
|
791
|
+
let lo = lo0, hi = hi0 - 1;
|
|
792
|
+
while (lo <= hi) {
|
|
793
|
+
const mid = (lo + hi) >> 1, c = ac.chars[mid];
|
|
794
|
+
if (ch < c) hi = mid - 1;
|
|
795
|
+
else if (ch > c) lo = mid + 1;
|
|
796
|
+
else return ac.nodes[mid];
|
|
797
|
+
}
|
|
798
|
+
if (node === 0) return 0;
|
|
799
|
+
node = ac.fail[node];
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
//ALL matches, including nested and overlapping.
|
|
804
|
+
//mode: 0 — start index, 1 — end index (exclusive), 2 — needle length.
|
|
805
|
+
//Indices are in source units, because the automaton runs over code units.
|
|
806
|
+
*_hits(src, adp, ac, mode = 0) {
|
|
807
|
+
const size = adp.size(src);
|
|
808
|
+
let node = 0;
|
|
809
|
+
for (let i = 0; i < size; i++) {
|
|
810
|
+
node = this._step(ac, node, adp.at(src, i));
|
|
811
|
+
for (let o = ac.out[node] ? node : ac.outNext[node]; o >= 0; o = ac.outNext[o]) {
|
|
812
|
+
const l = ac.out[o];
|
|
813
|
+
yield mode === 0 ? i + 1 - l : mode === 1 ? i + 1 : l;
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
//the GAPS between matches — a flat stream of boundaries (point 8):
|
|
819
|
+
//start0, end0, start1, end1, ... Matches are taken non-nested and left to right
|
|
820
|
+
//(leftmost-longest), because for "drop" and "cut" there is no other way:
|
|
821
|
+
//two overlapping matches cannot be removed at once.
|
|
822
|
+
//This single generator underlies omit, omitn, clear, split and splitn.
|
|
823
|
+
*_seg(src, adp, ac) {
|
|
824
|
+
const size = adp.size(src);
|
|
825
|
+
let node = 0, gap = 0;
|
|
826
|
+
for (let i = 0; i < size; i++) {
|
|
827
|
+
node = this._step(ac, node, adp.at(src, i));
|
|
828
|
+
//the longest match ending here and not reaching into the previous cut
|
|
829
|
+
let best = 0;
|
|
830
|
+
for (let o = ac.out[node] ? node : ac.outNext[node]; o >= 0; o = ac.outNext[o]) {
|
|
831
|
+
const l = ac.out[o];
|
|
832
|
+
if (l > best && i + 1 - l >= gap) best = l;
|
|
833
|
+
}
|
|
834
|
+
if (best === 0) continue;
|
|
835
|
+
yield gap;
|
|
836
|
+
yield i + 1 - best;
|
|
837
|
+
gap = i + 1;
|
|
838
|
+
node = 0; //after a cut we restart matching — matches don't overlap
|
|
839
|
+
}
|
|
840
|
+
yield gap;
|
|
841
|
+
yield size;
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
//quote and escape automaton: yields a bit mask for each position.
|
|
845
|
+
//Base for pair, pairb, quote-respecting split and unesc.
|
|
846
|
+
//Bits: 1 — position inside quotes, 2 — the quote itself, 4 — an escaped literal,
|
|
847
|
+
//8 — the escape character. One number per position, no allocations.
|
|
848
|
+
*_quote(units, opts) {
|
|
849
|
+
const q = opts?.quotes ?? '"\'';
|
|
850
|
+
const e = opts?.esc ?? '\\';
|
|
851
|
+
const nest = opts?.nest === true;
|
|
852
|
+
const qs = new Set();
|
|
853
|
+
for (const ch of q) qs.add(ch.codePointAt(0));
|
|
854
|
+
const ec = e === '' || e == null ? -1 : e.codePointAt(0);
|
|
855
|
+
let open = -1, depth = 0, esc = false;
|
|
856
|
+
for (const u of units) {
|
|
857
|
+
if (esc) { esc = false; yield 4 | (depth > 0 ? 1 : 0); continue; }
|
|
858
|
+
if (u === ec) { esc = true; yield 8 | (depth > 0 ? 1 : 0); continue; }
|
|
859
|
+
if (qs.has(u)) {
|
|
860
|
+
if (depth === 0) { open = u; depth = 1; yield 2; continue; }
|
|
861
|
+
if (u === open) {
|
|
862
|
+
if (nest) { depth--; yield depth === 0 ? 2 : 3; continue; }
|
|
863
|
+
depth = 0;
|
|
864
|
+
yield 2;
|
|
865
|
+
continue;
|
|
866
|
+
}
|
|
867
|
+
//a foreign quote inside one's own — an ordinary character, not a boundary
|
|
868
|
+
yield 1;
|
|
869
|
+
continue;
|
|
870
|
+
}
|
|
871
|
+
if (nest && depth > 0 && u === open) { depth++; yield 3; continue; }
|
|
872
|
+
yield depth > 0 ? 1 : 0;
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
//--- 0.7 argument parsing ---
|
|
877
|
+
|
|
878
|
+
//parse the target argument for the substr family.
|
|
879
|
+
//ONE method for all four, otherwise divergence is inevitable (see the starts/ends history).
|
|
880
|
+
//Rule: target is a string => search; target is a number => it is already a position.
|
|
881
|
+
//You must check typeof, NOT target?.length > 0: the latter matches any object with a
|
|
882
|
+
//length field, and it silently drifts into indexOf and fails as "not found" instead of TypeError.
|
|
883
|
+
//An empty string is a valid target, it matches at position 0, not an error.
|
|
884
|
+
_target(str, target, last) {
|
|
885
|
+
if (typeof str !== 'string') throw new TypeError(`str-im: str must be a string, got ${typeof str}`);
|
|
886
|
+
if (typeof target === 'number') {
|
|
887
|
+
if (!Number.isInteger(target)) throw new TypeError(`str-im: a numeric target must be an integer, got ${target}`);
|
|
888
|
+
if (target < 0 || target > str.length) throw new RangeError(`str-im: position ${target} out of range 0..${str.length}`);
|
|
889
|
+
return target;
|
|
890
|
+
}
|
|
891
|
+
if (typeof target !== 'string') throw new TypeError(`str-im: target must be a string or a position, got ${typeof target}`);
|
|
892
|
+
const i = last ? str.lastIndexOf(target) : str.indexOf(target);
|
|
893
|
+
if (i < 0) throw new NotFound(JSON.stringify(target));
|
|
894
|
+
return i;
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
//offset check. NaN, non-number, negative — all TypeError/RangeError.
|
|
898
|
+
//A negative offset must throw: substring silently swaps its arguments when start > end,
|
|
899
|
+
//so substr(s,'h',-1) would return the text BEFORE the target. A silently wrong result
|
|
900
|
+
//is worse than an exception. For the same reason we cut with slice, not substring.
|
|
901
|
+
_offset(offset) {
|
|
902
|
+
if (typeof offset !== 'number' || Number.isNaN(offset)) throw new TypeError('str-im: offset must be a number');
|
|
903
|
+
if (offset < 0) throw new RangeError(`str-im: offset must be >= 0, got ${offset}`);
|
|
904
|
+
if (offset !== Infinity && !Number.isInteger(offset)) throw new TypeError(`str-im: offset must be an integer, got ${offset}`);
|
|
905
|
+
return offset;
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
//length comparison. The numeric branch of starts/ends/contains is exactly this,
|
|
909
|
+
//and it is identical for all three: it has nothing to do with "starts"/"ends"/"contains".
|
|
910
|
+
_lencmp(str, n) {
|
|
911
|
+
if (typeof str !== 'string') throw new TypeError(`str-im: str must be a string, got ${typeof str}`);
|
|
912
|
+
if (!Number.isInteger(n) || n < 0) throw new RangeError(`str-im: length must be an integer >= 0, got ${n}`);
|
|
913
|
+
return str.length === n ? -1 : str.length > n ? 1 : 0;
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
|
|
917
|
+
//=========================================================================
|
|
918
|
+
//=== 1. SLICES RELATIVE TO A TARGET
|
|
919
|
+
//=== l = last (search from the end), b = back (take the piece BEFORE the target).
|
|
920
|
+
//=========================================================================
|
|
921
|
+
|
|
922
|
+
//target length in code units: a numeric target is a position, its "length" is 0.
|
|
923
|
+
_tlen(target) { return typeof target === 'number' ? 0 : target.length; }
|
|
924
|
+
|
|
925
|
+
//the piece AFTER the occurrence, of length offset. slice itself clamps the tail and Infinity.
|
|
926
|
+
substr(str, target, offset = Infinity) {
|
|
927
|
+
offset = this._offset(offset);
|
|
928
|
+
const start = this._target(str, target, false) + this._tlen(target);
|
|
929
|
+
return str.slice(start, start + offset);
|
|
930
|
+
}
|
|
931
|
+
lsubstr(str, target, offset = Infinity) {
|
|
932
|
+
offset = this._offset(offset);
|
|
933
|
+
const start = this._target(str, target, true) + this._tlen(target);
|
|
934
|
+
return str.slice(start, start + offset);
|
|
935
|
+
}
|
|
936
|
+
//the piece BEFORE the occurrence. end = target position; start is clamped to zero.
|
|
937
|
+
substrb(str, target, offset = Infinity) {
|
|
938
|
+
offset = this._offset(offset);
|
|
939
|
+
const end = this._target(str, target, false);
|
|
940
|
+
return str.slice(offset === Infinity ? 0 : Math.max(0, end - offset), end);
|
|
941
|
+
}
|
|
942
|
+
lsubstrb(str, target, offset = Infinity) {
|
|
943
|
+
offset = this._offset(offset);
|
|
944
|
+
const end = this._target(str, target, true);
|
|
945
|
+
return str.slice(offset === Infinity ? 0 : Math.max(0, end - offset), end);
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
|
|
949
|
+
//=========================================================================
|
|
950
|
+
//=== 2. PREDICATES. Return 0 / 1 / -1 (point 5). Numeric target — shared _lencmp.
|
|
951
|
+
//=========================================================================
|
|
952
|
+
|
|
953
|
+
//shared type check for the string branch of the predicates
|
|
954
|
+
_pstr(str, target) {
|
|
955
|
+
if (typeof str !== 'string') throw new TypeError(`str-im: str must be a string, got ${typeof str}`);
|
|
956
|
+
if (typeof target !== 'string') throw new TypeError(`str-im: target must be a string or a number, got ${typeof target}`);
|
|
957
|
+
}
|
|
958
|
+
//full match first, otherwise it drowns in startsWith/endsWith/includes.
|
|
959
|
+
starts(str, target) {
|
|
960
|
+
if (typeof target === 'number') return this._lencmp(str, target);
|
|
961
|
+
this._pstr(str, target);
|
|
962
|
+
return str === target ? -1 : str.startsWith(target) ? 1 : 0;
|
|
963
|
+
}
|
|
964
|
+
ends(str, target) {
|
|
965
|
+
if (typeof target === 'number') return this._lencmp(str, target);
|
|
966
|
+
this._pstr(str, target);
|
|
967
|
+
return str === target ? -1 : str.endsWith(target) ? 1 : 0;
|
|
968
|
+
}
|
|
969
|
+
contains(str, target) {
|
|
970
|
+
if (typeof target === 'number') return this._lencmp(str, target);
|
|
971
|
+
this._pstr(str, target);
|
|
972
|
+
return str === target ? -1 : str.includes(target) ? 1 : 0;
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
|
|
976
|
+
//=========================================================================
|
|
977
|
+
//=== 3. COUNTERS. Each is a _count/sum over its own stream, nothing is materialized.
|
|
978
|
+
//=========================================================================
|
|
979
|
+
|
|
980
|
+
//number of characters = code points. For a string .length coincides only on the BMP;
|
|
981
|
+
//the honest answer goes through the adapter, so it is correct for a utf-8 buffer too.
|
|
982
|
+
len(buf) { return this._count(this._cps(buf, this._adapter(buf))); }
|
|
983
|
+
//number of "wide" characters (cp >= 0x10000) — those that take a surrogate pair in utf-16.
|
|
984
|
+
//For a string this is exactly the number of surrogate pairs; subtract it from the length
|
|
985
|
+
//in code units (str.length) to get the length in code points in a single pass.
|
|
986
|
+
wlen(buf) {
|
|
987
|
+
const adp = this._adapter(buf);
|
|
988
|
+
return this._count(this._where(this._cps(buf, adp), (cp) => cp >= 0x10000));
|
|
989
|
+
}
|
|
990
|
+
//number of unique characters, without producing strings.
|
|
991
|
+
ulen(buf) { const adp = this._adapter(buf); return this._count(this._uniq(this._cps(buf, adp))); }
|
|
992
|
+
//how many bytes it takes in utf-8, without encoding. Already a utf-8 buffer — that is its length.
|
|
993
|
+
blen(buf) {
|
|
994
|
+
const adp = this._adapter(buf);
|
|
995
|
+
if (adp.dec === 1) return adp.size(buf);
|
|
996
|
+
let n = 0;
|
|
997
|
+
for (const cp of this._cps(buf, adp)) n += this._cplen(cp);
|
|
998
|
+
return n;
|
|
999
|
+
}
|
|
1000
|
+
//number of grapheme clusters. _graph yields C starts + the closing boundary size,
|
|
1001
|
+
//so the cluster count is exactly (number of boundaries − 1), and 0 on empty input.
|
|
1002
|
+
glen(buf) {
|
|
1003
|
+
const c = this._count(this._graph(buf, this._adapter(buf)));
|
|
1004
|
+
return c === 0 ? 0 : c - 1;
|
|
1005
|
+
}
|
|
1006
|
+
//visual width in columns: width is taken for the cluster as a whole (by its base
|
|
1007
|
+
//code point); combining marks inside give 0 and don't enter the sum.
|
|
1008
|
+
dlen(buf) {
|
|
1009
|
+
const adp = this._adapter(buf);
|
|
1010
|
+
let w = 0, prev = -1;
|
|
1011
|
+
for (const b of this._graph(buf, adp)) {
|
|
1012
|
+
if (prev >= 0) w += this._width(this._at(buf, adp, prev));
|
|
1013
|
+
prev = b;
|
|
1014
|
+
}
|
|
1015
|
+
return w;
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
//=========================================================================
|
|
1019
|
+
//=== 4. DROPPING CHARACTERS. All three sit on _seg (leftmost-longest boundaries).
|
|
1020
|
+
//=========================================================================
|
|
1021
|
+
|
|
1022
|
+
//step in source units from the start of a code point to the start of the next.
|
|
1023
|
+
_adv(adp, cp) { return adp.dec === 1 ? this._cplen(cp) : (adp.dec === 0 && cp >= 0x10000 ? 2 : 1); }
|
|
1024
|
+
|
|
1025
|
+
//lazily yields the characters of str, skipping occurrences of omits. _seg yields a flat
|
|
1026
|
+
//stream of boundaries keepStart,keepEnd,keepStart,keepEnd,...,size — we drop what's between.
|
|
1027
|
+
omit(str, omits) { return this._prime(this._gomit(str, omits)); }
|
|
1028
|
+
*_gomit(str, omits) {
|
|
1029
|
+
const adp = this._adapter(str);
|
|
1030
|
+
const ac = this._ac(this._needles(omits, false));
|
|
1031
|
+
yield; //barrier (point 6): validation of the source and needles has already happened
|
|
1032
|
+
const seg = this._seg(str, adp, ac);
|
|
1033
|
+
for (let s = seg.next(); !s.done; s = seg.next()) {
|
|
1034
|
+
const e = seg.next();
|
|
1035
|
+
if (e.done) break;
|
|
1036
|
+
for (let i = s.value; i < e.value;) {
|
|
1037
|
+
const cp = this._at(str, adp, i);
|
|
1038
|
+
yield cp < 0x10000 ? String.fromCharCode(cp) : String.fromCodePoint(cp);
|
|
1039
|
+
i += this._adv(adp, cp);
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
//the same, but yields the INDICES of the dropped characters. What's dropped lies between
|
|
1044
|
+
//the keepEnd of one pair and the keepStart of the next.
|
|
1045
|
+
omitn(str, omits) { return this._prime(this._gomitn(str, omits)); }
|
|
1046
|
+
*_gomitn(str, omits) {
|
|
1047
|
+
const adp = this._adapter(str);
|
|
1048
|
+
const ac = this._ac(this._needles(omits, false));
|
|
1049
|
+
yield;
|
|
1050
|
+
const seg = this._seg(str, adp, ac);
|
|
1051
|
+
let prevEnd = -1;
|
|
1052
|
+
for (let s = seg.next(); !s.done; s = seg.next()) {
|
|
1053
|
+
const e = seg.next();
|
|
1054
|
+
if (e.done) break;
|
|
1055
|
+
if (prevEnd >= 0) for (let i = prevEnd; i < s.value;) {
|
|
1056
|
+
yield i;
|
|
1057
|
+
i += this._adv(adp, this._at(str, adp, i));
|
|
1058
|
+
}
|
|
1059
|
+
prevEnd = e.value;
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
//non-lazy: a new string without omits. No match at all (_seg yielded a single pair
|
|
1063
|
+
//[0,size)) -> return the original string by reference, building nothing.
|
|
1064
|
+
clear(str, omits) {
|
|
1065
|
+
if (typeof str !== 'string') throw new TypeError(`str-im: str must be a string, got ${typeof str}`);
|
|
1066
|
+
const adp = this._adapter(str);
|
|
1067
|
+
const ac = this._ac(this._needles(omits, false));
|
|
1068
|
+
const seg = this._seg(str, adp, ac);
|
|
1069
|
+
const parts = [];
|
|
1070
|
+
let pairs = 0;
|
|
1071
|
+
for (let s = seg.next(); !s.done; s = seg.next()) {
|
|
1072
|
+
const e = seg.next();
|
|
1073
|
+
if (e.done) break;
|
|
1074
|
+
pairs++;
|
|
1075
|
+
if (e.value > s.value) parts.push(str.slice(s.value, e.value));
|
|
1076
|
+
}
|
|
1077
|
+
return pairs <= 1 ? str : parts.join('');
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
|
|
1081
|
+
//=========================================================================
|
|
1082
|
+
//=== 5. THE *char FAMILY — ITERATORS OF UNIQUE CHARACTERS
|
|
1083
|
+
//=== Each is a composition source -> [map] -> [where] -> uniq -> emit.
|
|
1084
|
+
//=== kind: 0 units L→R, 1 units R→L, 2 cps L→R, 3 cps R→L.
|
|
1085
|
+
//=========================================================================
|
|
1086
|
+
|
|
1087
|
+
*_uchain(str, max, kind, map, test) {
|
|
1088
|
+
const adp = this._adapter(str);
|
|
1089
|
+
max = this._max(max);
|
|
1090
|
+
yield; //barrier (point 6)
|
|
1091
|
+
let s = kind === 0 ? this._units(str, adp)
|
|
1092
|
+
: kind === 1 ? this._runits(str, adp)
|
|
1093
|
+
: kind === 3 ? this._rcps(str, adp)
|
|
1094
|
+
: this._cps(str, adp);
|
|
1095
|
+
if (map) s = this._map(s, map);
|
|
1096
|
+
if (test) s = this._where(s, test);
|
|
1097
|
+
yield* this._emit(this._uniq(s, max));
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
char(str, max = Infinity) { return this._prime(this._uchain(str, max, 0, null, null)); }
|
|
1101
|
+
wchar(str, max = Infinity) { return this._prime(this._uchain(str, max, 2, null, null)); }
|
|
1102
|
+
rchar(str, max = Infinity) { return this._prime(this._uchain(str, max, 1, null, null)); }
|
|
1103
|
+
//case-insensitive: folding BEFORE _uniq, so 'A' and 'a' collapse into one folded value.
|
|
1104
|
+
ichar(str, max = Infinity) { return this._prime(this._uchain(str, max, 2, (cp) => this._fold(cp), null)); }
|
|
1105
|
+
//vowels/consonants — membership in the active alphabet's Set (resolved once).
|
|
1106
|
+
vchar(str, max = Infinity) { const a = this._alphabet(); return this._prime(this._uchain(str, max, 2, null, (cp) => a.v.has(cp))); }
|
|
1107
|
+
cchar(str, max = Infinity) { const a = this._alphabet(); return this._prime(this._uchain(str, max, 2, null, (cp) => a.c.has(cp))); }
|
|
1108
|
+
//class filters on \p{...} tables — a binary search instead of a regexp.
|
|
1109
|
+
schar(str, max = Infinity) { return this._prime(this._uchain(str, max, 2, null, (cp) => this._is('S', cp))); }
|
|
1110
|
+
pchar(str, max = Infinity) { return this._prime(this._uchain(str, max, 2, null, (cp) => this._is('P', cp))); }
|
|
1111
|
+
nchar(str, max = Infinity) { return this._prime(this._uchain(str, max, 2, null, (cp) => this._is('Nd', cp))); }
|
|
1112
|
+
mchar(str, max = Infinity) { return this._prime(this._uchain(str, max, 2, null, (cp) => this._is('M', cp))); }
|
|
1113
|
+
uchar(str, max = Infinity) { return this._prime(this._uchain(str, max, 2, null, (cp) => this._is('Lu', cp))); }
|
|
1114
|
+
lchar(str, max = Infinity) { return this._prime(this._uchain(str, max, 2, null, (cp) => this._is('Ll', cp))); }
|
|
1115
|
+
//invisible and control: \p{Cc} ∪ \p{Cf} (zero-width and bidi-override are entirely in Cf).
|
|
1116
|
+
zchar(str, max = Infinity) { return this._prime(this._uchain(str, max, 2, null, (cp) => this._is('Cc', cp) || this._is('Cf', cp))); }
|
|
1117
|
+
//unique grapheme clusters. The only family member with a multi-character element,
|
|
1118
|
+
//so deduplication is by cluster CONTENT (a string key), not by a single number.
|
|
1119
|
+
gchar(str, max = Infinity) { return this._prime(this._ggchar(str, max)); }
|
|
1120
|
+
*_ggchar(str, max) {
|
|
1121
|
+
const adp = this._adapter(str);
|
|
1122
|
+
max = this._max(max);
|
|
1123
|
+
yield;
|
|
1124
|
+
const seen = new Set();
|
|
1125
|
+
let prev = -1;
|
|
1126
|
+
for (const b of this._graph(str, adp)) {
|
|
1127
|
+
if (prev >= 0) {
|
|
1128
|
+
const g = str.slice(prev, b);
|
|
1129
|
+
if (!seen.has(g)) { seen.add(g); yield g; if (seen.size >= max) return; }
|
|
1130
|
+
}
|
|
1131
|
+
prev = b;
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
|
|
1136
|
+
//=========================================================================
|
|
1137
|
+
//=== 6. THE *cons FAMILY — CONSECUTIVE. All on _runs, except flat (it needs both
|
|
1138
|
+
//=== the run value and length at once — per point 8 that is done by a direct pass).
|
|
1139
|
+
//=========================================================================
|
|
1140
|
+
|
|
1141
|
+
//length of the first run from the left; on reaching max — Infinity (saturation, point 9).
|
|
1142
|
+
consc(str, max = Infinity) { return this._consc(str, max, false); }
|
|
1143
|
+
rconsc(str, max = Infinity) { return this._consc(str, max, true); }
|
|
1144
|
+
_consc(str, max, rev) {
|
|
1145
|
+
const adp = this._adapter(str);
|
|
1146
|
+
max = this._max(max);
|
|
1147
|
+
let prev = 0, i = 0;
|
|
1148
|
+
for (const cp of rev ? this._rcps(str, adp) : this._cps(str, adp)) {
|
|
1149
|
+
if (i === 0) prev = cp;
|
|
1150
|
+
else if (cp !== prev) return i;
|
|
1151
|
+
if (++i >= max) return Infinity;
|
|
1152
|
+
}
|
|
1153
|
+
return i;
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
//shared generator for cons/rcons (run character, mode 1) and consg/rconsg (length, mode 2).
|
|
1157
|
+
*_gruns(str, max, rev, mode) {
|
|
1158
|
+
const adp = this._adapter(str);
|
|
1159
|
+
max = this._max(max);
|
|
1160
|
+
yield;
|
|
1161
|
+
let n = 0;
|
|
1162
|
+
for (const v of this._runs(rev ? this._rcps(str, adp) : this._cps(str, adp), mode)) {
|
|
1163
|
+
yield mode === 1 ? (v < 0x10000 ? String.fromCharCode(v) : String.fromCodePoint(v)) : v;
|
|
1164
|
+
if (++n >= max) return;
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
cons(str, max = Infinity) { return this._prime(this._gruns(str, max, false, 1)); }
|
|
1168
|
+
rcons(str, max = Infinity) { return this._prime(this._gruns(str, max, true, 1)); }
|
|
1169
|
+
consg(str, max = Infinity) { return this._prime(this._gruns(str, max, false, 2)); }
|
|
1170
|
+
rconsg(str, max = Infinity) { return this._prime(this._gruns(str, max, true, 2)); }
|
|
1171
|
+
|
|
1172
|
+
//runs, but a run on an already-seen character is skipped: 'aabbaa' -> a, b.
|
|
1173
|
+
ucons(str, max = Infinity) { return this._prime(this._gucons(str, max, false)); }
|
|
1174
|
+
urcons(str, max = Infinity) { return this._prime(this._gucons(str, max, true)); }
|
|
1175
|
+
*_gucons(str, max, rev) {
|
|
1176
|
+
const adp = this._adapter(str);
|
|
1177
|
+
max = this._max(max);
|
|
1178
|
+
yield;
|
|
1179
|
+
const seen = new Set();
|
|
1180
|
+
for (const v of this._runs(rev ? this._rcps(str, adp) : this._cps(str, adp), 1)) {
|
|
1181
|
+
if (seen.has(v)) continue;
|
|
1182
|
+
seen.add(v);
|
|
1183
|
+
yield v < 0x10000 ? String.fromCharCode(v) : String.fromCodePoint(v);
|
|
1184
|
+
if (seen.size >= max) return;
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
//collapse repeats: 'aaabbb' -> 'ab'. keep — how many repeats to keep.
|
|
1189
|
+
//chars — an optional set (collapse only its characters). Collapsed nothing
|
|
1190
|
+
//-> the original string by reference. The run value and length are needed together,
|
|
1191
|
+
//so the pass is its own, not through a single _runs projection (point 8).
|
|
1192
|
+
flat(str, chars, keep = 1) {
|
|
1193
|
+
if (typeof str !== 'string') throw new TypeError(`str-im: str must be a string, got ${typeof str}`);
|
|
1194
|
+
keep = this._max(keep);
|
|
1195
|
+
const adp = this._adapter(str);
|
|
1196
|
+
let set = null;
|
|
1197
|
+
if (chars != null) { set = new Set(); for (const ch of String(chars)) set.add(ch.codePointAt(0)); }
|
|
1198
|
+
const out = [];
|
|
1199
|
+
let changed = false, prev = -1, run = 0;
|
|
1200
|
+
const flush = () => {
|
|
1201
|
+
if (prev < 0) return;
|
|
1202
|
+
const n = (set === null || set.has(prev)) ? Math.min(run, keep) : run;
|
|
1203
|
+
if (n < run) changed = true;
|
|
1204
|
+
const ch = prev < 0x10000 ? String.fromCharCode(prev) : String.fromCodePoint(prev);
|
|
1205
|
+
for (let k = 0; k < n; k++) out.push(ch);
|
|
1206
|
+
};
|
|
1207
|
+
for (const cp of this._cps(str, adp)) {
|
|
1208
|
+
if (prev < 0 || cp !== prev) { flush(); prev = cp; run = 1; }
|
|
1209
|
+
else run++;
|
|
1210
|
+
}
|
|
1211
|
+
flush();
|
|
1212
|
+
return changed ? out.join('') : str;
|
|
1213
|
+
}
|
|
1214
|
+
|
|
1215
|
+
//=========================================================================
|
|
1216
|
+
//=== 7. ACCESS BY TARGET
|
|
1217
|
+
//=========================================================================
|
|
1218
|
+
|
|
1219
|
+
//has(str,+n)/has(str,-n) — code unit by index (from the end for -n), out of range -> undefined.
|
|
1220
|
+
//has(str,char) — the character itself if it is present in the string, else undefined.
|
|
1221
|
+
has(str, target) {
|
|
1222
|
+
if (typeof str !== 'string') throw new TypeError(`str-im: str must be a string, got ${typeof str}`);
|
|
1223
|
+
if (typeof target === 'number') {
|
|
1224
|
+
if (!Number.isInteger(target)) throw new TypeError(`str-im: a numeric index must be an integer, got ${target}`);
|
|
1225
|
+
const i = target < 0 ? str.length + target : target;
|
|
1226
|
+
return i < 0 || i >= str.length ? undefined : str[i];
|
|
1227
|
+
}
|
|
1228
|
+
if (typeof target !== 'string') throw new TypeError(`str-im: target must be an index or a character, got ${typeof target}`);
|
|
1229
|
+
return str.includes(target) ? target : undefined;
|
|
1230
|
+
}
|
|
1231
|
+
//the same, but indexed in code points; a negative index means a pass from the end (_rcps).
|
|
1232
|
+
whas(str, target) {
|
|
1233
|
+
if (typeof str !== 'string') throw new TypeError(`str-im: str must be a string, got ${typeof str}`);
|
|
1234
|
+
if (typeof target === 'number') {
|
|
1235
|
+
if (!Number.isInteger(target)) throw new TypeError(`str-im: a numeric index must be an integer, got ${target}`);
|
|
1236
|
+
const adp = this._adapter(str);
|
|
1237
|
+
const emit = (cp) => cp < 0x10000 ? String.fromCharCode(cp) : String.fromCodePoint(cp);
|
|
1238
|
+
if (target >= 0) { let i = 0; for (const cp of this._cps(str, adp)) if (i++ === target) return emit(cp); return undefined; }
|
|
1239
|
+
let i = -1;
|
|
1240
|
+
for (const cp of this._rcps(str, adp)) { if (i-- === target) return emit(cp); }
|
|
1241
|
+
return undefined;
|
|
1242
|
+
}
|
|
1243
|
+
if (typeof target !== 'string') throw new TypeError(`str-im: target must be an index or a character, got ${typeof target}`);
|
|
1244
|
+
return str.includes(target) ? target : undefined;
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
|
|
1248
|
+
//=========================================================================
|
|
1249
|
+
//=== 8. BYTES AND BOUNDARIES. Working with a utf-8 buffer without materializing a string.
|
|
1250
|
+
//=========================================================================
|
|
1251
|
+
|
|
1252
|
+
//index of the first invalid utf-8 byte, or -1. The same automaton as in _u8points,
|
|
1253
|
+
//but here the error POSITION matters, not the replacement with U+FFFD.
|
|
1254
|
+
badn(buf) {
|
|
1255
|
+
if (!(buf instanceof Uint8Array)) throw new TypeError('str-im: badn — utf-8 buffer (Uint8Array) only');
|
|
1256
|
+
const size = buf.length;
|
|
1257
|
+
for (let i = 0; i < size;) {
|
|
1258
|
+
const b = buf[i];
|
|
1259
|
+
if (b < 0x80) { i++; continue; }
|
|
1260
|
+
let need, min, cp;
|
|
1261
|
+
if (b < 0xc2) return i; //continuation without a lead, or overlong start C0/C1
|
|
1262
|
+
else if (b < 0xe0) { need = 1; min = 0x80; cp = b & 0x1f; }
|
|
1263
|
+
else if (b < 0xf0) { need = 2; min = 0x800; cp = b & 0x0f; }
|
|
1264
|
+
else if (b < 0xf5) { need = 3; min = 0x10000; cp = b & 0x07; }
|
|
1265
|
+
else return i; //lead byte > F4
|
|
1266
|
+
if (i + need >= size) return i; //sequence does not fit in the buffer
|
|
1267
|
+
for (let k = 1; k <= need; k++) {
|
|
1268
|
+
const c = buf[i + k];
|
|
1269
|
+
if ((c & 0xc0) !== 0x80) return i;
|
|
1270
|
+
cp = (cp << 6) | (c & 0x3f);
|
|
1271
|
+
}
|
|
1272
|
+
if (cp < min || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff)) return i; //overlong / out of range / surrogate
|
|
1273
|
+
i += need + 1;
|
|
1274
|
+
}
|
|
1275
|
+
return -1;
|
|
1276
|
+
}
|
|
1277
|
+
//whether there is a BOM and how many BYTES it takes (0 — none). utf-32 is checked before
|
|
1278
|
+
//utf-16, otherwise FF FE 00 00 is falsely recognized as utf-16 LE.
|
|
1279
|
+
bom(buf) {
|
|
1280
|
+
if (buf instanceof Uint8Array) {
|
|
1281
|
+
const b = buf, n = b.length;
|
|
1282
|
+
if (n >= 3 && b[0] === 0xef && b[1] === 0xbb && b[2] === 0xbf) return 3;
|
|
1283
|
+
if (n >= 4 && b[0] === 0xff && b[1] === 0xfe && b[2] === 0 && b[3] === 0) return 4;
|
|
1284
|
+
if (n >= 4 && b[0] === 0 && b[1] === 0 && b[2] === 0xfe && b[3] === 0xff) return 4;
|
|
1285
|
+
if (n >= 2 && ((b[0] === 0xff && b[1] === 0xfe) || (b[0] === 0xfe && b[1] === 0xff))) return 2;
|
|
1286
|
+
return 0;
|
|
1287
|
+
}
|
|
1288
|
+
if (typeof buf === 'string') return buf.charCodeAt(0) === 0xfeff ? 1 : 0;
|
|
1289
|
+
throw new TypeError('str-im: bom — string or Uint8Array');
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1292
|
+
//[start, end, cp] triples for each code point. Needed by cut/bcut: both the slice
|
|
1293
|
+
//boundaries and the value for _cplen.
|
|
1294
|
+
*_cpwalk(src, adp) {
|
|
1295
|
+
const size = adp.size(src);
|
|
1296
|
+
let prev = -1;
|
|
1297
|
+
for (const i of this._pointn(src, adp)) {
|
|
1298
|
+
if (prev >= 0) yield [prev, i, this._at(src, adp, prev)];
|
|
1299
|
+
prev = i;
|
|
1300
|
+
}
|
|
1301
|
+
if (prev >= 0) yield [prev, size, this._at(src, adp, prev)];
|
|
1302
|
+
}
|
|
1303
|
+
//truncate to max units without cutting a compound character in half. mode: 0 — code points
|
|
1304
|
+
//(cut), 1 — utf-8 bytes (bcut), 2 — grapheme clusters (wcut). ell — the trailing ellipsis,
|
|
1305
|
+
//its weight in the same units is subtracted from the limit. Everything fit — the source by reference.
|
|
1306
|
+
cut(src, max, ell) { return this._cut(src, max, ell, 0); }
|
|
1307
|
+
bcut(src, max, ell) { return this._cut(src, max, ell, 1); }
|
|
1308
|
+
wcut(src, max, ell) { return this._cut(src, max, ell, 2); }
|
|
1309
|
+
_cut(src, max, ell, mode) {
|
|
1310
|
+
max = this._max(max);
|
|
1311
|
+
const adp = this._adapter(src);
|
|
1312
|
+
const ellW = ell == null ? 0 : (mode === 0 ? this.len(ell) : mode === 1 ? this.blen(ell) : this.glen(ell));
|
|
1313
|
+
const limit = max - ellW;
|
|
1314
|
+
let wsum = 0, cutIdx = 0, fits = true;
|
|
1315
|
+
if (mode === 2) {
|
|
1316
|
+
let prev = -1;
|
|
1317
|
+
for (const b of this._graph(src, adp)) {
|
|
1318
|
+
if (prev >= 0) {
|
|
1319
|
+
if (wsum + 1 > max) { fits = false; break; }
|
|
1320
|
+
wsum += 1;
|
|
1321
|
+
if (wsum <= limit) cutIdx = b;
|
|
1322
|
+
}
|
|
1323
|
+
prev = b;
|
|
1324
|
+
}
|
|
1325
|
+
} else {
|
|
1326
|
+
for (const [, end, cp] of this._cpwalk(src, adp)) {
|
|
1327
|
+
const w = mode === 1 ? this._cplen(cp) : 1;
|
|
1328
|
+
if (wsum + w > max) { fits = false; break; }
|
|
1329
|
+
wsum += w;
|
|
1330
|
+
if (wsum <= limit) cutIdx = end;
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
if (fits) return src;
|
|
1334
|
+
if (typeof src === 'string') return src.slice(0, cutIdx) + (ell == null ? '' : String(ell));
|
|
1335
|
+
if (src instanceof Uint8Array) {
|
|
1336
|
+
const head = src.subarray(0, cutIdx);
|
|
1337
|
+
if (ell == null) return head;
|
|
1338
|
+
const et = ell instanceof Uint8Array ? ell : new TextEncoder().encode(String(ell));
|
|
1339
|
+
const out = new Uint8Array(head.length + et.length);
|
|
1340
|
+
out.set(head); out.set(et, head.length);
|
|
1341
|
+
return out;
|
|
1342
|
+
}
|
|
1343
|
+
const head = src.slice(0, cutIdx); //Array<number>
|
|
1344
|
+
if (ell == null) return head;
|
|
1345
|
+
for (const ch of String(ell)) head.push(ch.codePointAt(0));
|
|
1346
|
+
return head;
|
|
1347
|
+
}
|
|
1348
|
+
|
|
1349
|
+
|
|
1350
|
+
//=========================================================================
|
|
1351
|
+
//=== 9. SEARCH AND COMPARE
|
|
1352
|
+
//=========================================================================
|
|
1353
|
+
|
|
1354
|
+
//all occurrences lazily, indices in code units. rev — right to left (needles are reversed,
|
|
1355
|
+
//the input is read via _runits — the whole string is not materialized). fold — case-insensitive.
|
|
1356
|
+
//all — yield ALL (including nested) matches; otherwise non-nested (leftmost-longest,
|
|
1357
|
+
//for rev — rightmost-longest).
|
|
1358
|
+
find(str, target, opts) { return this._prime(this._gfind(str, target, false, false, opts?.all === true)); }
|
|
1359
|
+
lfind(str, target, opts) { return this._prime(this._gfind(str, target, true, false, opts?.all === true)); }
|
|
1360
|
+
ifind(str, target, opts) { return this._prime(this._gfind(str, target, false, true, opts?.all === true)); }
|
|
1361
|
+
*_gfind(str, target, rev, fold, all) {
|
|
1362
|
+
const adp = this._adapter(str);
|
|
1363
|
+
let needles = this._needles(target, fold);
|
|
1364
|
+
if (rev) needles = needles.map((a) => Int32Array.from(a).reverse());
|
|
1365
|
+
const ac = this._ac(needles);
|
|
1366
|
+
yield; //barrier (point 6)
|
|
1367
|
+
const size = adp.size(str);
|
|
1368
|
+
const foldable = fold && adp.dec !== 1;
|
|
1369
|
+
let node = 0, gap = 0, k = 0;
|
|
1370
|
+
for (let u of rev ? this._runits(str, adp) : this._units(str, adp)) {
|
|
1371
|
+
if (foldable) u = this._fold(u);
|
|
1372
|
+
node = this._step(ac, node, u);
|
|
1373
|
+
if (all) {
|
|
1374
|
+
for (let o = ac.out[node] ? node : ac.outNext[node]; o >= 0; o = ac.outNext[o]) {
|
|
1375
|
+
const L = ac.out[o];
|
|
1376
|
+
yield rev ? size - 1 - k : k + 1 - L;
|
|
1377
|
+
}
|
|
1378
|
+
} else {
|
|
1379
|
+
let best = 0;
|
|
1380
|
+
for (let o = ac.out[node] ? node : ac.outNext[node]; o >= 0; o = ac.outNext[o]) {
|
|
1381
|
+
const L = ac.out[o];
|
|
1382
|
+
if (L > best && k + 1 - L >= gap) best = L;
|
|
1383
|
+
}
|
|
1384
|
+
if (best) { yield rev ? size - 1 - k : k + 1 - best; gap = k + 1; node = 0; }
|
|
1385
|
+
}
|
|
1386
|
+
k++;
|
|
1387
|
+
}
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
//bounded edit distance: the distance, or Infinity if it exceeds max (point 9).
|
|
1391
|
+
//A band of width 2*max+1 (cells outside the band = big, guaranteed > max), early exit
|
|
1392
|
+
//on the row minimum. opts.damerau — count transposition of adjacent characters.
|
|
1393
|
+
near(a, b, max = Infinity, opts) {
|
|
1394
|
+
if (typeof a !== 'string' || typeof b !== 'string') throw new TypeError('str-im: near(a, b) — both must be strings');
|
|
1395
|
+
if (typeof max !== 'number' || Number.isNaN(max) || max < 0 || (max !== Infinity && !Number.isInteger(max))) {
|
|
1396
|
+
throw new RangeError(`str-im: max must be an integer >= 0 or Infinity, got ${max}`);
|
|
1397
|
+
}
|
|
1398
|
+
if (a === b) return 0;
|
|
1399
|
+
const damerau = opts?.damerau === true;
|
|
1400
|
+
const A = Array.from(a, (c) => c.codePointAt(0));
|
|
1401
|
+
const B = Array.from(b, (c) => c.codePointAt(0));
|
|
1402
|
+
const n = A.length, m = B.length;
|
|
1403
|
+
if (Math.abs(n - m) > max) return Infinity;
|
|
1404
|
+
const big = max === Infinity ? n + m + 1 : max + 1;
|
|
1405
|
+
let prev2 = new Array(m + 1).fill(big);
|
|
1406
|
+
let prev = new Array(m + 1);
|
|
1407
|
+
for (let j = 0; j <= m; j++) prev[j] = j <= max ? j : big;
|
|
1408
|
+
for (let i = 1; i <= n; i++) {
|
|
1409
|
+
const cur = new Array(m + 1).fill(big);
|
|
1410
|
+
const jlo = max === Infinity ? 1 : Math.max(1, i - max);
|
|
1411
|
+
const jhi = max === Infinity ? m : Math.min(m, i + max);
|
|
1412
|
+
cur[0] = i <= max ? i : big;
|
|
1413
|
+
let rowMin = cur[0];
|
|
1414
|
+
for (let j = jlo; j <= jhi; j++) {
|
|
1415
|
+
const cost = A[i - 1] === B[j - 1] ? 0 : 1;
|
|
1416
|
+
let v = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + cost);
|
|
1417
|
+
if (damerau && i > 1 && j > 1 && A[i - 1] === B[j - 2] && A[i - 2] === B[j - 1]) v = Math.min(v, prev2[j - 2] + 1);
|
|
1418
|
+
cur[j] = v;
|
|
1419
|
+
if (v < rowMin) rowMin = v;
|
|
1420
|
+
}
|
|
1421
|
+
if (rowMin > max) return Infinity;
|
|
1422
|
+
prev2 = prev; prev = cur;
|
|
1423
|
+
}
|
|
1424
|
+
const d = prev[m];
|
|
1425
|
+
return d > max ? Infinity : d;
|
|
1426
|
+
}
|
|
1427
|
+
|
|
1428
|
+
//length of the common prefix/suffix in code points. b — a string or an iterable of strings:
|
|
1429
|
+
//we walk them all at once and bail on the first divergence, so the cost is the answer length.
|
|
1430
|
+
com(a, b) { return this._com(a, b, false); }
|
|
1431
|
+
comb(a, b) { return this._com(a, b, true); }
|
|
1432
|
+
_com(a, b, back) {
|
|
1433
|
+
if (typeof a !== 'string') throw new TypeError(`str-im: com(a, b) — a must be a string, got ${typeof a}`);
|
|
1434
|
+
const targets = typeof b === 'string' ? [b] : [...b];
|
|
1435
|
+
if (targets.length === 0) throw new TypeError('str-im: empty target set');
|
|
1436
|
+
const mk = (s) => {
|
|
1437
|
+
if (typeof s !== 'string') throw new TypeError('str-im: a target must be a string or an iterable of strings');
|
|
1438
|
+
return (back ? this._rcps(s, this._adapter(s)) : this._cps(s, this._adapter(s)))[Symbol.iterator]();
|
|
1439
|
+
};
|
|
1440
|
+
const ai = mk(a);
|
|
1441
|
+
const its = targets.map(mk);
|
|
1442
|
+
let count = 0;
|
|
1443
|
+
for (;;) {
|
|
1444
|
+
const an = ai.next();
|
|
1445
|
+
if (an.done) break;
|
|
1446
|
+
let ok = true;
|
|
1447
|
+
for (const it of its) { const bn = it.next(); if (bn.done || bn.value !== an.value) { ok = false; break; } }
|
|
1448
|
+
if (!ok) break;
|
|
1449
|
+
count++;
|
|
1450
|
+
}
|
|
1451
|
+
return count;
|
|
1452
|
+
}
|
|
1453
|
+
|
|
1454
|
+
//=========================================================================
|
|
1455
|
+
//=== 10. SEGMENTATION AND PARSING
|
|
1456
|
+
//=========================================================================
|
|
1457
|
+
|
|
1458
|
+
//whether to respect quotes/escaping per opts
|
|
1459
|
+
_quoteOn(opts) { return !!(opts && (opts.quote === true || opts.quotes != null || opts.esc != null)); }
|
|
1460
|
+
|
|
1461
|
+
//LAZY split. sep — a string, a set of strings (via _ac), or absent (cut on line breaks
|
|
1462
|
+
//\r\n|\n|\r as ONE boundary). opts.quotes/esc — don't cut inside quotes (via _quote in
|
|
1463
|
+
//lockstep). opts.limit — no more than N pieces, the remainder as one piece.
|
|
1464
|
+
split(str, sep, opts) { return this._prime(this._gsplit(str, sep, opts, true)); }
|
|
1465
|
+
//boundaries instead of pieces: a flat stream start0,end0,start1,end1,... Parsing with no allocations.
|
|
1466
|
+
splitn(str, sep, opts) { return this._prime(this._gsplit(str, sep, opts, false)); }
|
|
1467
|
+
*_gsplit(str, sep, opts, pieces) {
|
|
1468
|
+
const adp = this._adapter(str);
|
|
1469
|
+
const quoteOn = this._quoteOn(opts);
|
|
1470
|
+
const limit = opts?.limit;
|
|
1471
|
+
if (limit != null && (!Number.isInteger(limit) || limit < 1)) throw new RangeError(`str-im: limit must be an integer >= 1, got ${limit}`);
|
|
1472
|
+
const ac = sep == null ? null : this._ac(this._needles(sep, false));
|
|
1473
|
+
yield; //barrier (point 6)
|
|
1474
|
+
const size = adp.size(str);
|
|
1475
|
+
const qit = quoteOn ? this._quote(this._units(str, adp), opts)[Symbol.iterator]() : null;
|
|
1476
|
+
let node = 0, start = 0, count = 0;
|
|
1477
|
+
for (let i = 0; i < size; i++) {
|
|
1478
|
+
const u = adp.at(str, i);
|
|
1479
|
+
const q = qit ? qit.next().value : 0;
|
|
1480
|
+
let mStart = -1, mEnd = -1;
|
|
1481
|
+
if (!quoteOn || q === 0) {
|
|
1482
|
+
if (ac === null) {
|
|
1483
|
+
//line breaks: \r\n as one boundary — the only case that needs a lookahead
|
|
1484
|
+
if (u === 13) { mStart = i; mEnd = (i + 1 < size && adp.at(str, i + 1) === 10) ? i + 2 : i + 1; }
|
|
1485
|
+
else if (u === 10) { mStart = i; mEnd = i + 1; }
|
|
1486
|
+
} else {
|
|
1487
|
+
node = this._step(ac, node, u);
|
|
1488
|
+
let best = 0;
|
|
1489
|
+
for (let o = ac.out[node] ? node : ac.outNext[node]; o >= 0; o = ac.outNext[o]) {
|
|
1490
|
+
const L = ac.out[o];
|
|
1491
|
+
if (L > best && i + 1 - L >= start) best = L;
|
|
1492
|
+
}
|
|
1493
|
+
if (best) { mStart = i + 1 - best; mEnd = i + 1; }
|
|
1494
|
+
}
|
|
1495
|
+
}
|
|
1496
|
+
if (mStart >= 0) {
|
|
1497
|
+
if (limit != null && count >= limit - 1) break; //the remainder as the last piece
|
|
1498
|
+
if (pieces) yield str.slice(start, mStart); else { yield start; yield mStart; }
|
|
1499
|
+
count++;
|
|
1500
|
+
start = mEnd;
|
|
1501
|
+
node = 0;
|
|
1502
|
+
if (mEnd > i + 1) { if (qit) for (let z = i + 1; z < mEnd; z++) qit.next(); i = mEnd - 1; } //skip the \n of \r\n without desyncing the quote mask
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
if (pieces) yield str.slice(start, size); else { yield start; yield size; }
|
|
1506
|
+
}
|
|
1507
|
+
|
|
1508
|
+
//bracket pair maps: open->close and close->open. Default () [] {} <>.
|
|
1509
|
+
_pairs(opts) {
|
|
1510
|
+
const fwd = new Map(), bwd = new Map();
|
|
1511
|
+
const add = (o, c) => { fwd.set(o, c); bwd.set(c, o); };
|
|
1512
|
+
const p = opts?.pairs;
|
|
1513
|
+
if (p) {
|
|
1514
|
+
const it = Array.isArray(p) ? p : Object.entries(p);
|
|
1515
|
+
for (const [o, c] of it) add(String(o).codePointAt(0), String(c).codePointAt(0));
|
|
1516
|
+
} else { add(40, 41); add(91, 93); add(123, 125); add(60, 62); }
|
|
1517
|
+
return { fwd, bwd };
|
|
1518
|
+
}
|
|
1519
|
+
//given the index of the OPENING bracket, return the index of the closing one, respecting
|
|
1520
|
+
//nesting and quotes. Not found -> -1.
|
|
1521
|
+
pair(str, i, opts) {
|
|
1522
|
+
if (typeof str !== 'string') throw new TypeError(`str-im: str must be a string, got ${typeof str}`);
|
|
1523
|
+
if (!Number.isInteger(i) || i < 0 || i >= str.length) throw new RangeError(`str-im: position ${i} out of range 0..${str.length - 1}`);
|
|
1524
|
+
const adp = this._adapter(str);
|
|
1525
|
+
const openU = str.charCodeAt(i);
|
|
1526
|
+
const closeU = this._pairs(opts).fwd.get(openU);
|
|
1527
|
+
if (closeU === undefined) throw new RangeError(`str-im: no opening bracket at position ${i}`);
|
|
1528
|
+
const quoteOn = this._quoteOn(opts);
|
|
1529
|
+
const qit = quoteOn ? this._quote(this._units(str, adp), opts)[Symbol.iterator]() : null;
|
|
1530
|
+
let depth = 0, j = 0;
|
|
1531
|
+
for (const u of this._units(str, adp)) {
|
|
1532
|
+
const q = qit ? qit.next().value : 0;
|
|
1533
|
+
if (j === i) depth = 1;
|
|
1534
|
+
else if (j > i && (!quoteOn || q === 0)) {
|
|
1535
|
+
if (u === openU) depth++;
|
|
1536
|
+
else if (u === closeU && --depth === 0) return j;
|
|
1537
|
+
}
|
|
1538
|
+
j++;
|
|
1539
|
+
}
|
|
1540
|
+
return -1;
|
|
1541
|
+
}
|
|
1542
|
+
//given the index of the CLOSING bracket, return the index of the opening one (a pass backward).
|
|
1543
|
+
pairb(str, i, opts) {
|
|
1544
|
+
if (typeof str !== 'string') throw new TypeError(`str-im: str must be a string, got ${typeof str}`);
|
|
1545
|
+
if (!Number.isInteger(i) || i < 0 || i >= str.length) throw new RangeError(`str-im: position ${i} out of range 0..${str.length - 1}`);
|
|
1546
|
+
const adp = this._adapter(str);
|
|
1547
|
+
const closeU = str.charCodeAt(i);
|
|
1548
|
+
const openU = this._pairs(opts).bwd.get(closeU);
|
|
1549
|
+
if (openU === undefined) throw new RangeError(`str-im: no closing bracket at position ${i}`);
|
|
1550
|
+
const quoteOn = this._quoteOn(opts);
|
|
1551
|
+
let mask = null;
|
|
1552
|
+
if (quoteOn) { mask = []; for (const q of this._quote(this._units(str, adp), opts)) mask.push(q); }
|
|
1553
|
+
let depth = 0;
|
|
1554
|
+
for (let j = i; j >= 0; j--) {
|
|
1555
|
+
if (j === i) { depth = 1; continue; }
|
|
1556
|
+
if (quoteOn && mask[j] !== 0) continue;
|
|
1557
|
+
const u = str.charCodeAt(j);
|
|
1558
|
+
if (u === closeU) depth++;
|
|
1559
|
+
else if (u === openU && --depth === 0) return j;
|
|
1560
|
+
}
|
|
1561
|
+
return -1;
|
|
1562
|
+
}
|
|
1563
|
+
|
|
1564
|
+
//indentation analysis: {char, size, min, mixed}. Empty lines don't enter min.
|
|
1565
|
+
//size — the step (GCD of non-zero indents), mixed — spaces and tabs are mixed somewhere.
|
|
1566
|
+
ind(str) {
|
|
1567
|
+
if (typeof str !== 'string') throw new TypeError(`str-im: str must be a string, got ${typeof str}`);
|
|
1568
|
+
const gcd = (a, b) => { while (b) { const t = a % b; a = b; b = t; } return a; };
|
|
1569
|
+
let min = Infinity, spaces = false, tabs = false, mixed = false, step = 0;
|
|
1570
|
+
for (const line of str.split('\n')) {
|
|
1571
|
+
let sp = 0, tb = 0, k = 0;
|
|
1572
|
+
for (; k < line.length; k++) { const c = line.charCodeAt(k); if (c === 32) sp++; else if (c === 9) tb++; else break; }
|
|
1573
|
+
if (k === line.length) continue; //empty or whitespace-only — skip
|
|
1574
|
+
if (sp) spaces = true;
|
|
1575
|
+
if (tb) tabs = true;
|
|
1576
|
+
if (sp && tb) mixed = true;
|
|
1577
|
+
const indent = sp + tb;
|
|
1578
|
+
if (indent < min) min = indent;
|
|
1579
|
+
if (indent > 0) step = step ? gcd(step, indent) : indent;
|
|
1580
|
+
}
|
|
1581
|
+
if (spaces && tabs) mixed = true;
|
|
1582
|
+
return { char: tabs && !spaces ? '\t' : ' ', size: step, min: min === Infinity ? 0 : min, mixed };
|
|
1583
|
+
}
|
|
1584
|
+
//strip the common indent: the longest common whitespace prefix of non-empty lines.
|
|
1585
|
+
dedent(str) {
|
|
1586
|
+
if (typeof str !== 'string') throw new TypeError(`str-im: str must be a string, got ${typeof str}`);
|
|
1587
|
+
const lines = str.split('\n');
|
|
1588
|
+
let prefix = null;
|
|
1589
|
+
for (const line of lines) {
|
|
1590
|
+
let k = 0;
|
|
1591
|
+
for (; k < line.length; k++) { const c = line.charCodeAt(k); if (c !== 32 && c !== 9) break; }
|
|
1592
|
+
if (k === line.length) continue; //an empty line doesn't constrain the common prefix
|
|
1593
|
+
const ws = line.slice(0, k);
|
|
1594
|
+
if (prefix === null) prefix = ws;
|
|
1595
|
+
else { let j = 0; while (j < prefix.length && j < ws.length && prefix[j] === ws[j]) j++; prefix = prefix.slice(0, j); }
|
|
1596
|
+
if (prefix === '') return str;
|
|
1597
|
+
}
|
|
1598
|
+
if (!prefix) return str;
|
|
1599
|
+
return lines.map((l) => l.startsWith(prefix) ? l.slice(prefix.length) : l).join('\n');
|
|
1600
|
+
}
|
|
1601
|
+
|
|
1602
|
+
//escape dangerous characters with the escape character (\ by default). The escape character
|
|
1603
|
+
//itself is escaped too. Found nothing -> the original string by reference.
|
|
1604
|
+
esc(str, chars, opts) {
|
|
1605
|
+
if (typeof str !== 'string') throw new TypeError(`str-im: str must be a string, got ${typeof str}`);
|
|
1606
|
+
const e = opts?.esc ?? '\\';
|
|
1607
|
+
const set = new Set();
|
|
1608
|
+
for (const ch of String(chars ?? '')) set.add(ch.codePointAt(0));
|
|
1609
|
+
set.add(e.codePointAt(0));
|
|
1610
|
+
let out = null;
|
|
1611
|
+
for (let i = 0; i < str.length;) {
|
|
1612
|
+
const cp = str.codePointAt(i);
|
|
1613
|
+
const w = cp > 0xffff ? 2 : 1;
|
|
1614
|
+
if (set.has(cp)) { if (out === null) out = str.slice(0, i); out += e + String.fromCodePoint(cp); }
|
|
1615
|
+
else if (out !== null) out += String.fromCodePoint(cp);
|
|
1616
|
+
i += w;
|
|
1617
|
+
}
|
|
1618
|
+
return out === null ? str : out;
|
|
1619
|
+
}
|
|
1620
|
+
//remove escaping: the escape character is dropped, the next character is taken as a literal.
|
|
1621
|
+
//A trailing lone escape is preserved. No escape at all -> the original string.
|
|
1622
|
+
unesc(str, opts) {
|
|
1623
|
+
if (typeof str !== 'string') throw new TypeError(`str-im: str must be a string, got ${typeof str}`);
|
|
1624
|
+
const e = opts?.esc ?? '\\';
|
|
1625
|
+
if (!str.includes(e)) return str;
|
|
1626
|
+
const ec = e.codePointAt(0);
|
|
1627
|
+
let out = '';
|
|
1628
|
+
for (let i = 0; i < str.length;) {
|
|
1629
|
+
const cp = str.codePointAt(i);
|
|
1630
|
+
const w = cp > 0xffff ? 2 : 1;
|
|
1631
|
+
if (cp === ec && i + w < str.length) {
|
|
1632
|
+
const nx = str.codePointAt(i + w);
|
|
1633
|
+
out += String.fromCodePoint(nx);
|
|
1634
|
+
i += w + (nx > 0xffff ? 2 : 1);
|
|
1635
|
+
} else { out += String.fromCodePoint(cp); i += w; }
|
|
1636
|
+
}
|
|
1637
|
+
return out;
|
|
1638
|
+
}
|
|
1639
|
+
|
|
1640
|
+
//trim with a customizable set (\p{White_Space} by default). Works from the edges only,
|
|
1641
|
+
//stopping at the first non-matching character. trim — both edges, rtrim — the right one.
|
|
1642
|
+
trim(str, chars) { return this._trim(str, chars, true, true); }
|
|
1643
|
+
rtrim(str, chars) { return this._trim(str, chars, false, true); }
|
|
1644
|
+
_trimtest(chars) {
|
|
1645
|
+
if (chars == null) return (cp) => this._is('WS', cp);
|
|
1646
|
+
const set = new Set();
|
|
1647
|
+
for (const ch of String(chars)) set.add(ch.codePointAt(0));
|
|
1648
|
+
return (cp) => set.has(cp);
|
|
1649
|
+
}
|
|
1650
|
+
_trim(str, chars, left, right) {
|
|
1651
|
+
if (typeof str !== 'string') throw new TypeError(`str-im: str must be a string, got ${typeof str}`);
|
|
1652
|
+
const test = this._trimtest(chars);
|
|
1653
|
+
let a = 0, b = str.length;
|
|
1654
|
+
if (left) while (a < b) { const cp = str.codePointAt(a); if (!test(cp)) break; a += cp > 0xffff ? 2 : 1; }
|
|
1655
|
+
if (right) while (b > a) {
|
|
1656
|
+
let s = b - 1, cp = str.charCodeAt(s);
|
|
1657
|
+
if (cp >= 0xdc00 && cp <= 0xdfff && s - 1 >= a) { const hi = str.charCodeAt(s - 1); if (hi >= 0xd800 && hi <= 0xdbff) { cp = (hi - 0xd800) * 0x400 + cp - 0xdc00 + 0x10000; s--; } }
|
|
1658
|
+
if (!test(cp)) break;
|
|
1659
|
+
b = s;
|
|
1660
|
+
}
|
|
1661
|
+
return a === 0 && b === str.length ? str : str.slice(a, b);
|
|
1662
|
+
}
|
|
1663
|
+
|
|
1664
|
+
//=========================================================================
|
|
1665
|
+
//=== 11. UNICODE ANALYSIS. The same scheme of unique iterators, but the element is a
|
|
1666
|
+
//=== property of the character, not the character itself. The pipeline is reused entirely.
|
|
1667
|
+
//=========================================================================
|
|
1668
|
+
|
|
1669
|
+
//unique scripts of the string (names), in order of first appearance.
|
|
1670
|
+
scr(str, max = Infinity) { return this._prime(this._gscr(str, max)); }
|
|
1671
|
+
*_gscr(str, max) {
|
|
1672
|
+
const adp = this._adapter(str);
|
|
1673
|
+
max = this._max(max);
|
|
1674
|
+
yield; //barrier (point 6)
|
|
1675
|
+
const seen = new Set();
|
|
1676
|
+
for (const cp of this._cps(str, adp)) {
|
|
1677
|
+
const id = this._script(cp);
|
|
1678
|
+
if (seen.has(id)) continue;
|
|
1679
|
+
seen.add(id);
|
|
1680
|
+
yield this._scriptName(id);
|
|
1681
|
+
if (seen.size >= max) return;
|
|
1682
|
+
}
|
|
1683
|
+
}
|
|
1684
|
+
//whether scripts are mixed. Common/Inherited/Unknown are ignored: digits and punctuation
|
|
1685
|
+
//are everywhere and are not a mixture. Return (point 5): 0 — one script, 1 — a mixture, -1 — none at all.
|
|
1686
|
+
mix(str) {
|
|
1687
|
+
const adp = this._adapter(str);
|
|
1688
|
+
const common = T.SCRIPTS.indexOf('Common') + 1;
|
|
1689
|
+
const inherited = T.SCRIPTS.indexOf('Inherited') + 1;
|
|
1690
|
+
let found = -1;
|
|
1691
|
+
for (const cp of this._cps(str, adp)) {
|
|
1692
|
+
const id = this._script(cp);
|
|
1693
|
+
if (id === 0 || id === common || id === inherited) continue;
|
|
1694
|
+
if (found === -1) found = id;
|
|
1695
|
+
else if (id !== found) return 1;
|
|
1696
|
+
}
|
|
1697
|
+
return found === -1 ? -1 : 0;
|
|
1698
|
+
}
|
|
1699
|
+
//register your own confusables (TR39). map — an object/Map char->char|string.
|
|
1700
|
+
//A process-wide static, like use/alphabet: the registry is one per process.
|
|
1701
|
+
static confuse(map) {
|
|
1702
|
+
if (!map) throw new TypeError('str-im: confuse(map) — an object or a Map is required');
|
|
1703
|
+
const it = map instanceof Map ? map.entries() : Object.entries(map);
|
|
1704
|
+
for (const [k, v] of it) CONFUSE.set(String(k).codePointAt(0), String(v));
|
|
1705
|
+
return strim;
|
|
1706
|
+
}
|
|
1707
|
+
//TR39 skeleton: the visually indistinguishable collapses to one representative. There is no
|
|
1708
|
+
//full confusables table in the package, hence: NFKD (removes fullwidth, ligatures,
|
|
1709
|
+
//compatibility), then a built-in set of cross-script homoglyphs (Cyrillic/Greek -> Latin)
|
|
1710
|
+
//and the user's from confuse(), dropping combining marks and case folding.
|
|
1711
|
+
skel(str) {
|
|
1712
|
+
if (typeof str !== 'string') throw new TypeError(`str-im: str must be a string, got ${typeof str}`);
|
|
1713
|
+
let out = '';
|
|
1714
|
+
for (const ch of str.normalize('NFKD')) {
|
|
1715
|
+
const cp = ch.codePointAt(0);
|
|
1716
|
+
const c = CONFUSE.get(cp);
|
|
1717
|
+
if (c !== undefined) { for (const cc of c) out += String.fromCodePoint(this._fold(cc.codePointAt(0))); continue; }
|
|
1718
|
+
if (this._is('M', cp)) continue; //a combining mark — doesn't affect the skeleton
|
|
1719
|
+
out += String.fromCodePoint(this._fold(cp));
|
|
1720
|
+
}
|
|
1721
|
+
return out;
|
|
1722
|
+
}
|
|
1723
|
+
//strip diacritics: NFD, drop everything in \p{M}, NFC. A composition, not an algorithm.
|
|
1724
|
+
deburr(str) {
|
|
1725
|
+
if (typeof str !== 'string') throw new TypeError(`str-im: str must be a string, got ${typeof str}`);
|
|
1726
|
+
let out = '';
|
|
1727
|
+
for (const ch of str.normalize('NFD')) if (!this._is('M', ch.codePointAt(0))) out += ch;
|
|
1728
|
+
return out.normalize('NFC');
|
|
1729
|
+
}
|
|
1730
|
+
|
|
1731
|
+
|
|
1732
|
+
//=========================================================================
|
|
1733
|
+
//=== 12. METRICS
|
|
1734
|
+
//=========================================================================
|
|
1735
|
+
|
|
1736
|
+
//Shannon entropy over _freq. base: 2 — bits, Math.E — nats. n>1 — over n-grams
|
|
1737
|
+
//(the rolling hash as a window identifier), so meaningful text is better told from noise.
|
|
1738
|
+
ent(str, base = 2, n = 1) {
|
|
1739
|
+
if (typeof base !== 'number' || Number.isNaN(base) || base <= 0 || base === 1) throw new RangeError(`str-im: base must be > 0 and != 1, got ${base}`);
|
|
1740
|
+
const adp = this._adapter(str);
|
|
1741
|
+
n = this._max(n);
|
|
1742
|
+
const freq = n === 1 ? this._freq(this._cps(str, adp)) : this._freq(this._win(this._cps(str, adp), n, 1));
|
|
1743
|
+
const total = freq.total;
|
|
1744
|
+
if (total === 0) return 0;
|
|
1745
|
+
let H = 0;
|
|
1746
|
+
const acc = (c) => { if (c > 0) { const p = c / total; H -= p * Math.log(p); } };
|
|
1747
|
+
for (let i = 0; i <= freq.top; i++) if (freq.arr[i]) acc(freq.arr[i]);
|
|
1748
|
+
if (freq.map) for (const c of freq.map.values()) acc(c);
|
|
1749
|
+
return H / Math.log(base);
|
|
1750
|
+
}
|
|
1751
|
+
//N-GRAMS: the window start index in source units (not a substring — the consumer slices).
|
|
1752
|
+
//gram — by code units, wgram — by code points (the window doesn't cut a surrogate pair).
|
|
1753
|
+
gram(str, n = 2) { return this._prime(this._ggram(str, n, false)); }
|
|
1754
|
+
wgram(str, n = 2) { return this._prime(this._ggram(str, n, true)); }
|
|
1755
|
+
*_ggram(str, n, wide) {
|
|
1756
|
+
const adp = this._adapter(str);
|
|
1757
|
+
n = this._max(n);
|
|
1758
|
+
yield; //barrier (point 6)
|
|
1759
|
+
//wide: a stream of code-point INDICES -> the window yields the index of its first (mode 2);
|
|
1760
|
+
//otherwise the window over code units yields the ordinal start index (mode 0 == unit index).
|
|
1761
|
+
if (wide) yield* this._win(this._pointn(str, adp), n, 2);
|
|
1762
|
+
else yield* this._win(this._units(str, adp), n, 0);
|
|
1763
|
+
}
|
|
1764
|
+
//rolling hash (Rabin-Karp) over the same window by code points: the next one from the
|
|
1765
|
+
//previous in O(1). Content-defined chunking, dedup, repeat detection.
|
|
1766
|
+
hash(str, n = 2) { return this._prime(this._ghash(str, n)); }
|
|
1767
|
+
*_ghash(str, n) {
|
|
1768
|
+
const adp = this._adapter(str);
|
|
1769
|
+
n = this._max(n);
|
|
1770
|
+
yield; //barrier (point 6)
|
|
1771
|
+
yield* this._win(this._cps(str, adp), n, 1);
|
|
1772
|
+
}
|
|
1773
|
+
|
|
1774
|
+
|
|
1775
|
+
//=========================================================================
|
|
1776
|
+
//=== 13. SECOND TIER. The niche is taken, but it's useful.
|
|
1777
|
+
//=========================================================================
|
|
1778
|
+
|
|
1779
|
+
//glob without a regexp: * ? [abc] [a-z] [!neg] with two-pointer backtracking (O(1) memory
|
|
1780
|
+
//by position, code points put into arrays for astral correctness). opts.nocase.
|
|
1781
|
+
glob(str, pattern, opts) {
|
|
1782
|
+
if (typeof str !== 'string' || typeof pattern !== 'string') throw new TypeError('str-im: glob(str, pattern) — both must be strings');
|
|
1783
|
+
const S = Array.from(str, (c) => c.codePointAt(0));
|
|
1784
|
+
const P = Array.from(pattern, (c) => c.codePointAt(0));
|
|
1785
|
+
const fold = opts?.nocase ? (cp) => this._fold(cp) : (cp) => cp;
|
|
1786
|
+
//match the class [..] against code point c, starting at P[k]='['. -> [ok, nextK] or null.
|
|
1787
|
+
const klass = (k, c) => {
|
|
1788
|
+
let j = k + 1, neg = false;
|
|
1789
|
+
if (P[j] === 33 || P[j] === 94) { neg = true; j++; }
|
|
1790
|
+
let hit = false, firstIn = true;
|
|
1791
|
+
while (j < P.length && (P[j] !== 93 || firstIn)) {
|
|
1792
|
+
firstIn = false;
|
|
1793
|
+
if (P[j + 1] === 45 && j + 2 < P.length && P[j + 2] !== 93) {
|
|
1794
|
+
if (c >= fold(P[j]) && c <= fold(P[j + 2])) hit = true;
|
|
1795
|
+
j += 3;
|
|
1796
|
+
} else { if (fold(P[j]) === c) hit = true; j++; }
|
|
1797
|
+
}
|
|
1798
|
+
if (j >= P.length) return null; //unterminated [ — treat '[' as a literal
|
|
1799
|
+
return [hit !== neg, j + 1];
|
|
1800
|
+
};
|
|
1801
|
+
let si = 0, pi = 0, star = -1, ss = 0;
|
|
1802
|
+
while (si < S.length) {
|
|
1803
|
+
const c = fold(S[si]);
|
|
1804
|
+
if (pi < P.length && P[pi] === 63) { si++; pi++; }
|
|
1805
|
+
else if (pi < P.length && P[pi] === 91 && klass(pi, c) !== null) {
|
|
1806
|
+
const r = klass(pi, c);
|
|
1807
|
+
if (r[0]) { si++; pi = r[1]; }
|
|
1808
|
+
else if (star >= 0) { pi = star + 1; si = ++ss; }
|
|
1809
|
+
else return false;
|
|
1810
|
+
}
|
|
1811
|
+
else if (pi < P.length && P[pi] === 42) { star = pi++; ss = si; }
|
|
1812
|
+
else if (pi < P.length && fold(P[pi]) === c) { si++; pi++; }
|
|
1813
|
+
else if (star >= 0) { pi = star + 1; si = ++ss; }
|
|
1814
|
+
else return false;
|
|
1815
|
+
}
|
|
1816
|
+
while (pi < P.length && P[pi] === 42) pi++;
|
|
1817
|
+
return pi === P.length;
|
|
1818
|
+
}
|
|
1819
|
+
//naming style: 'camel','pascal','snake','screaming','kebab','dot','mixed','lower','unknown'.
|
|
1820
|
+
//Several different separators at once -> 'mixed'. Determined by separators and case.
|
|
1821
|
+
style(str) {
|
|
1822
|
+
if (typeof str !== 'string') throw new TypeError(`str-im: str must be a string, got ${typeof str}`);
|
|
1823
|
+
const hasU = str.includes('_'), hasD = str.includes('-'), hasDot = str.includes('.');
|
|
1824
|
+
if ((hasU ? 1 : 0) + (hasD ? 1 : 0) + (hasDot ? 1 : 0) > 1) return 'mixed';
|
|
1825
|
+
let upper = 0, lower = 0, letters = 0;
|
|
1826
|
+
for (const cp of this._cps(str, this._adapter(str))) {
|
|
1827
|
+
if (this._is('Lu', cp)) { upper++; letters++; }
|
|
1828
|
+
else if (this._is('Ll', cp)) { lower++; letters++; }
|
|
1829
|
+
else if (this._is('L', cp)) letters++;
|
|
1830
|
+
}
|
|
1831
|
+
if (hasDot) return 'dot';
|
|
1832
|
+
if (hasD) return 'kebab';
|
|
1833
|
+
if (hasU) return upper > 0 && lower === 0 ? 'screaming' : 'snake';
|
|
1834
|
+
if (letters === 0) return 'unknown';
|
|
1835
|
+
if (upper > 0 && lower === 0) return 'screaming';
|
|
1836
|
+
if (this._is('Lu', str.codePointAt(0))) return 'pascal';
|
|
1837
|
+
return upper > 0 ? 'camel' : 'lower';
|
|
1838
|
+
}
|
|
1839
|
+
//wrap by WIDTH (dlen), not by length: CJK and emoji don't break the layout. ANSI-CSI
|
|
1840
|
+
//is not counted as width. Explicit \n are preserved. Break on spaces (hyphens — later,
|
|
1841
|
+
//UAX #14 is a separate large table). A long word overflows the line, it isn't split.
|
|
1842
|
+
wrap(str, width, opts) { return this._prime(this._gwrap(str, width, opts)); }
|
|
1843
|
+
*_gwrap(str, width, opts) {
|
|
1844
|
+
if (typeof str !== 'string') throw new TypeError(`str-im: str must be a string, got ${typeof str}`);
|
|
1845
|
+
if (!Number.isInteger(width) || width < 1) throw new RangeError(`str-im: width must be an integer >= 1, got ${width}`);
|
|
1846
|
+
yield; //barrier (point 6)
|
|
1847
|
+
for (const para of str.split('\n')) {
|
|
1848
|
+
let line = '', lineW = 0, first = true;
|
|
1849
|
+
for (const word of para.split(' ')) {
|
|
1850
|
+
const ww = this._vwidth(word);
|
|
1851
|
+
if (first) { line = word; lineW = ww; first = false; }
|
|
1852
|
+
else if (lineW + 1 + ww <= width) { line += ' ' + word; lineW += 1 + ww; }
|
|
1853
|
+
else { yield line; line = word; lineW = ww; }
|
|
1854
|
+
}
|
|
1855
|
+
yield line;
|
|
1856
|
+
}
|
|
1857
|
+
}
|
|
1858
|
+
//visual width of a string in columns, stripping ANSI-CSI (ESC '[' … final byte @-~).
|
|
1859
|
+
_vwidth(s) {
|
|
1860
|
+
const adp = this._adapter(s);
|
|
1861
|
+
const cps = [...this._cps(s, adp)];
|
|
1862
|
+
let w = 0;
|
|
1863
|
+
for (let i = 0; i < cps.length; i++) {
|
|
1864
|
+
if (cps[i] === 0x1b) { i++; if (cps[i] === 0x5b) { i++; while (i < cps.length && !(cps[i] >= 0x40 && cps[i] <= 0x7e)) i++; } continue; }
|
|
1865
|
+
w += this._width(cps[i]);
|
|
1866
|
+
}
|
|
1867
|
+
return w;
|
|
1868
|
+
}
|
|
1869
|
+
}
|
|
1870
|
+
|
|
1871
|
+
//a built-in set of cross-script homoglyphs for skel: Cyrillic and Greek characters that
|
|
1872
|
+
//look identical to Latin ones -> Latin. There is no full TR39 table in the package;
|
|
1873
|
+
//this is a practical minimum for catching fake domains/handles. Extended via confuse().
|
|
1874
|
+
const CONFUSE = new Map();
|
|
1875
|
+
{
|
|
1876
|
+
//the left string (homoglyphs) maps character-by-character to the right one (Latin). The
|
|
1877
|
+
//lengths MUST match — otherwise the whole tail shifts; in skel the target is also case-folded.
|
|
1878
|
+
const from = 'аеорсух' + 'АВЕКМНОРСТХ' + 'ѕіј' + 'ϲοαρ' + 'ΑΒΕΗΙΚΜΝΟΡΤΧΥ';
|
|
1879
|
+
const to = 'aeopcyx' + 'ABEKMHOPCTX' + 'sij' + 'coap' + 'ABEHIKMNOPTXY';
|
|
1880
|
+
for (let i = 0; i < from.length; i++) CONFUSE.set(from.charCodeAt(i), to[i]);
|
|
1881
|
+
}
|
|
1882
|
+
|
|
1883
|
+
//registry of factory configurations (point 12): the same overrides object -> the same class.
|
|
1884
|
+
const CONFIGS = new WeakMap();
|
|
1885
|
+
|
|
1886
|
+
//THE FACTORY (points 11-12). With no argument — the base singleton, for free. With overrides —
|
|
1887
|
+
//a subclass instance cached by the object, with the listed methods replaced. An unknown method
|
|
1888
|
+
//name in overrides — we throw (point 6): otherwise a typo turns into silently dead code.
|
|
1889
|
+
export function _strim(overrides) {
|
|
1890
|
+
if (!overrides || Object.keys(overrides).length === 0) return SINGLETON;
|
|
1891
|
+
const hit = CONFIGS.get(overrides);
|
|
1892
|
+
if (hit) return hit;
|
|
1893
|
+
for (const k of Object.keys(overrides)) {
|
|
1894
|
+
if (typeof overrides[k] !== 'function') throw new TypeError(`str-im: overrides.${k} must be a function`);
|
|
1895
|
+
if (!(k in strim.prototype)) throw new TypeError(`str-im: unknown method '${k}' in overrides`);
|
|
1896
|
+
}
|
|
1897
|
+
//KEY POINT: super.method() inside an object-literal method resolves as
|
|
1898
|
+
//Object.getPrototypeOf([[HomeObject]]).method, and the method's HomeObject is the
|
|
1899
|
+
//overrides object itself. We set its prototype to strim.prototype — and super reaches the
|
|
1900
|
+
//original, without copying methods (a copy would keep the old HomeObject and super would break).
|
|
1901
|
+
Object.setPrototypeOf(overrides, strim.prototype);
|
|
1902
|
+
const inst = Object.create(overrides); //inst -> overrides -> strim.prototype: instanceof works
|
|
1903
|
+
Object.freeze(inst);
|
|
1904
|
+
CONFIGS.set(overrides, inst);
|
|
1905
|
+
return inst;
|
|
1906
|
+
}
|
|
1907
|
+
|
|
1908
|
+
//DEFAULT ALPHABET (point 0.5): Latin + Cyrillic. The contentious y/й/ы/ь are moved into a
|
|
1909
|
+
//separate 'semivowel' set so vchar/cchar don't impose their classification. Registration is
|
|
1910
|
+
//process-wide, done once at module load.
|
|
1911
|
+
strim.alphabet('default',
|
|
1912
|
+
'aeiouAEIOU' + 'аеёиоуэюяАЕЁИОУЭЮЯ',
|
|
1913
|
+
'bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ' + 'бвгджзклмнпрстфхцчшщБВГДЖЗКЛМНПРСТФХЦЧШЩ');
|
|
1914
|
+
strim.alphabet('semivowel', 'yYйЙыЫ', '');
|
|
1915
|
+
|
|
1916
|
+
//the default instance (singleton). An ordinary user needs no new (points 11-12):
|
|
1917
|
+
//the default export is a ready instance, the class is available as a named export for str-ez.
|
|
1918
|
+
const SINGLETON = new strim();
|
|
1919
|
+
export default SINGLETON;
|
|
1920
|
+
export { strim };
|