dsh-spell-check 0.0.0-stage → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/engine.js ADDED
@@ -0,0 +1,981 @@
1
+ /**
2
+ * The correction engine, shared by the host half and its tests.
3
+ *
4
+ * Pure functions and plain data only: no fs, no DOM, no network. The host loads
5
+ * the word list from disk once and hands it to `createEngine`; the browser half
6
+ * does all of its matching against the arrays this file produces.
7
+ *
8
+ * WHY A RANKED LIST AND NOT A BIG UNORDERED SET
9
+ *
10
+ * A set answers "is this a word", which is half the job. The other half is
11
+ * "which word did they mean", and that is decided almost entirely by how common
12
+ * the candidate is: `theh` sits one edit from `the`, `teh`, `eth` and a dozen
13
+ * rare tokens, and only frequency ordering puts `the` on top where a Tab press
14
+ * will accept it.
15
+ *
16
+ * @module dsh-spell-check/engine
17
+ */
18
+
19
+ /**
20
+ * Misspellings frequent enough to answer without any edit-distance search.
21
+ *
22
+ * Kept separate from the ranked list on purpose: these are the corrections a
23
+ * user expects to be instant and unambiguous, and several of them (`wont`,
24
+ * `cant`, `dont`) are only misspellings in the aphetic sense — the apostrophe
25
+ * is missing, not a letter.
26
+ */
27
+ export const TYPO_MAP = {
28
+ teh: 'the',
29
+ hte: 'the',
30
+ th: 'the',
31
+ theh: 'the',
32
+ rhe: 'the',
33
+ tthe: 'the',
34
+ adn: 'and',
35
+ nad: 'and',
36
+ anc: 'and',
37
+ ahev: 'have',
38
+ hvae: 'have',
39
+ jsut: 'just',
40
+ juts: 'just',
41
+ taht: 'that',
42
+ thta: 'that',
43
+ thsi: 'this',
44
+ tihs: 'this',
45
+ wiht: 'with',
46
+ waht: 'what',
47
+ hwat: 'what',
48
+ yuo: 'you',
49
+ yuor: 'your',
50
+ fro: 'for',
51
+ ofr: 'for',
52
+ fomr: 'from',
53
+ from: 'from',
54
+ ot: 'to',
55
+ nto: 'not',
56
+ ntoe: 'note',
57
+ woudl: 'would',
58
+ wuold: 'would',
59
+ coudl: 'could',
60
+ shoudl: 'should',
61
+ shuold: 'should',
62
+ abotu: 'about',
63
+ baout: 'about',
64
+ whcih: 'which',
65
+ wich: 'which',
66
+ hwihc: 'which',
67
+ becuase: 'because',
68
+ becasue: 'because',
69
+ beacuse: 'because',
70
+ becouse: 'because',
71
+ ther: 'there',
72
+ thier: 'their',
73
+ thier: 'their',
74
+ tehre: 'there',
75
+ thre: 'there',
76
+ recieve: 'receive',
77
+ recieved: 'received',
78
+ recieving: 'receiving',
79
+ beleive: 'believe',
80
+ belive: 'believe',
81
+ wieght: 'weight',
82
+ freind: 'friend',
83
+ freinds: 'friends',
84
+ feild: 'field',
85
+ gard: 'guard',
86
+ huose: 'house',
87
+ seperate: 'separate',
88
+ seperated: 'separated',
89
+ seperately: 'separately',
90
+ definately: 'definitely',
91
+ definatly: 'definitely',
92
+ defintely: 'definitely',
93
+ occured: 'occurred',
94
+ occuring: 'occurring',
95
+ ocurred: 'occurred',
96
+ succesful: 'successful',
97
+ successfull: 'successful',
98
+ sucessful: 'successful',
99
+ neccessary: 'necessary',
100
+ necesary: 'necessary',
101
+ neccessarily: 'necessarily',
102
+ accomodate: 'accommodate',
103
+ acommodate: 'accommodate',
104
+ adress: 'address',
105
+ adres: 'address',
106
+ arguement: 'argument',
107
+ begining: 'beginning',
108
+ begining: 'beginning',
109
+ calender: 'calendar',
110
+ commited: 'committed',
111
+ comming: 'coming',
112
+ completly: 'completely',
113
+ concious: 'conscious',
114
+ curiousity: 'curiosity',
115
+ exsistance: 'existence',
116
+ existance: 'existence',
117
+ familar: 'familiar',
118
+ finaly: 'finally',
119
+ foriegn: 'foreign',
120
+ gaurd: 'guard',
121
+ goverment: 'government',
122
+ guarentee: 'guarantee',
123
+ happend: 'happened',
124
+ hieght: 'height',
125
+ immediatly: 'immediately',
126
+ independant: 'independent',
127
+ intresting: 'interesting',
128
+ knowlege: 'knowledge',
129
+ liesure: 'leisure',
130
+ maintainance: 'maintenance',
131
+ milisecond: 'millisecond',
132
+ miliseconds: 'milliseconds',
133
+ millisecond: 'millisecond',
134
+ neice: 'niece',
135
+ noticable: 'noticeable',
136
+ occassion: 'occasion',
137
+ ocassion: 'occasion',
138
+ oppurtunity: 'opportunity',
139
+ oportunity: 'opportunity',
140
+ paralel: 'parallel',
141
+ parliment: 'parliament',
142
+ perseverence: 'perseverance',
143
+ posession: 'possession',
144
+ prefered: 'preferred',
145
+ priviledge: 'privilege',
146
+ probaly: 'probably',
147
+ probally: 'probably',
148
+ proccess: 'process',
149
+ proces: 'process',
150
+ pronounciation: 'pronunciation',
151
+ publically: 'publicly',
152
+ questionaire: 'questionnaire',
153
+ reccomend: 'recommend',
154
+ recomend: 'recommend',
155
+ refered: 'referred',
156
+ relevent: 'relevant',
157
+ religous: 'religious',
158
+ rember: 'remember',
159
+ rememberance: 'remembrance',
160
+ resistence: 'resistance',
161
+ responsability: 'responsibility',
162
+ rythm: 'rhythm',
163
+ scedule: 'schedule',
164
+ shedule: 'schedule',
165
+ schedual: 'schedule',
166
+ sieze: 'seize',
167
+ similiar: 'similar',
168
+ sincerly: 'sincerely',
169
+ speach: 'speech',
170
+ strentgh: 'strength',
171
+ succesfully: 'successfully',
172
+ suprise: 'surprise',
173
+ supress: 'suppress',
174
+ temperture: 'temperature',
175
+ tendancy: 'tendency',
176
+ threshhold: 'threshold',
177
+ tommorow: 'tomorrow',
178
+ tomorow: 'tomorrow',
179
+ tounge: 'tongue',
180
+ truely: 'truly',
181
+ twelth: 'twelfth',
182
+ tyrany: 'tyranny',
183
+ unecessary: 'unnecessary',
184
+ unfortunatly: 'unfortunately',
185
+ untill: 'until',
186
+ useable: 'usable',
187
+ vaccum: 'vacuum',
188
+ vehical: 'vehicle',
189
+ visable: 'visible',
190
+ wether: 'whether',
191
+ wheter: 'whether',
192
+ wierd: 'weird',
193
+ wihch: 'which',
194
+ writting: 'writing',
195
+ writen: 'written',
196
+ yeild: 'yield',
197
+ // Keyboard-adjacency and transposition slips common when typing fast.
198
+ atuo: 'auto',
199
+ autp: 'auto',
200
+ auot: 'auto',
201
+ conntextion: 'connection',
202
+ connecton: 'connection',
203
+ conection: 'connection',
204
+ connetion: 'connection',
205
+ contection: 'connection',
206
+ trype: 'type',
207
+ tyep: 'type',
208
+ tpye: 'type',
209
+ yuor: 'your',
210
+ foce: 'force',
211
+ focre: 'force',
212
+ foramtting: 'formatting',
213
+ formating: 'formatting',
214
+ compnent: 'component',
215
+ componet: 'component',
216
+ compnents: 'components',
217
+ compont: 'component',
218
+ modle: 'model',
219
+ modul: 'module',
220
+ moduels: 'modules',
221
+ fitler: 'filter',
222
+ filtet: 'filter',
223
+ seach: 'search',
224
+ serach: 'search',
225
+ sarach: 'search',
226
+ sesion: 'session',
227
+ sesssion: 'session',
228
+ settngs: 'settings',
229
+ setings: 'settings',
230
+ writng: 'writing',
231
+ renderng: 'rendering',
232
+ bulid: 'build',
233
+ buidl: 'build',
234
+ updatng: 'updating',
235
+ instaled: 'installed',
236
+ instal: 'install',
237
+ plugn: 'plugin',
238
+ plugni: 'plugin',
239
+ plguin: 'plugin',
240
+ pkg: 'package',
241
+ pakage: 'package',
242
+ packge: 'package',
243
+ importat: 'important',
244
+ importnat: 'important',
245
+ definintion: 'definition',
246
+ defualt: 'default',
247
+ defualts: 'defaults',
248
+ defalut: 'default',
249
+ retrun: 'return',
250
+ reutrn: 'return',
251
+ retun: 'return',
252
+ funciton: 'function',
253
+ fucntion: 'function',
254
+ functoin: 'function',
255
+ paramter: 'parameter',
256
+ paramaters: 'parameters',
257
+ paramters: 'parameters',
258
+ vlaue: 'value',
259
+ vaule: 'value',
260
+ vaue: 'value',
261
+ strign: 'string',
262
+ stirng: 'string',
263
+ strng: 'string',
264
+ arary: 'array',
265
+ arrya: 'array',
266
+ ojbect: 'object',
267
+ objetc: 'object',
268
+ oject: 'object',
269
+ prpoerty: 'property',
270
+ proprty: 'property',
271
+ porperty: 'property',
272
+ evnet: 'event',
273
+ evet: 'event',
274
+ keyboad: 'keyboard',
275
+ keybaord: 'keyboard',
276
+ defualty: 'default',
277
+ resposne: 'response',
278
+ reponse: 'response',
279
+ reqeust: 'request',
280
+ requets: 'request',
281
+ reqest: 'request',
282
+ errror: 'error',
283
+ erro: 'error',
284
+ excpetion: 'exception',
285
+ exeption: 'exception',
286
+ acount: 'account',
287
+ achive: 'archive',
288
+ alos: 'also',
289
+ alwyas: 'always',
290
+ awlays: 'always',
291
+ alywas: 'always',
292
+ aroudn: 'around',
293
+ aroud: 'around',
294
+ bacause: 'because',
295
+ bceause: 'because',
296
+ begn: 'begin',
297
+ belwo: 'below',
298
+ betwen: 'between',
299
+ betweeen: 'between',
300
+ bufery: 'buffer',
301
+ bufffer: 'buffer',
302
+ becnh: 'bench',
303
+ cetner: 'center',
304
+ chekc: 'check',
305
+ chek: 'check',
306
+ chiuld: 'child',
307
+ chidl: 'child',
308
+ cleaer: 'clear',
309
+ cler: 'clear',
310
+ cnahge: 'change',
311
+ chagne: 'change',
312
+ chnaged: 'changed',
313
+ cofnig: 'config',
314
+ cofig: 'config',
315
+ configg: 'config',
316
+ confg: 'config',
317
+ consdier: 'consider',
318
+ cosnole: 'console',
319
+ consoel: 'console',
320
+ contorl: 'control',
321
+ cotnrol: 'control',
322
+ contro: 'control',
323
+ coords: 'coords',
324
+ covearge: 'coverage',
325
+ cuase: 'cause',
326
+ cuases: 'causes',
327
+ curent: 'current',
328
+ cuurrent: 'current',
329
+ curren: 'current',
330
+ curretn: 'current',
331
+ daat: 'data',
332
+ datsa: 'data',
333
+ datat: 'data',
334
+ deatil: 'detail',
335
+ datail: 'detail',
336
+ detials: 'details',
337
+ dfeault: 'default',
338
+ diffrent: 'different',
339
+ differnt: 'different',
340
+ diffrently: 'differently',
341
+ dircetory: 'directory',
342
+ direcotry: 'directory',
343
+ direcory: 'directory',
344
+ documnet: 'document',
345
+ documet: 'document',
346
+ docuent: 'document',
347
+ doesnot: 'does not',
348
+ doesnt: "doesn't",
349
+ dont: "don't",
350
+ didnt: "didn't",
351
+ cant: "can't",
352
+ wont: "won't",
353
+ isnt: "isn't",
354
+ arent: "aren't",
355
+ wasnt: "wasn't",
356
+ werent: "weren't",
357
+ wouldnt: "wouldn't",
358
+ couldnt: "couldn't",
359
+ shouldnt: "shouldn't",
360
+ hasnt: "hasn't",
361
+ havent: "haven't",
362
+ im: "I'm",
363
+ ive: "I've",
364
+ thats: "that's",
365
+ ivee: "I've",
366
+ eeven: 'even',
367
+ enbale: 'enable',
368
+ enalbe: 'enable',
369
+ encodng: 'encoding',
370
+ entyr: 'entry',
371
+ enty: 'entry',
372
+ enviornment: 'environment',
373
+ enviroment: 'environment',
374
+ envirnoment: 'environment',
375
+ epxect: 'expect',
376
+ exect: 'expect',
377
+ exaple: 'example',
378
+ examle: 'example',
379
+ exmaple: 'example',
380
+ exsit: 'exist',
381
+ exsits: 'exists',
382
+ explict: 'explicit',
383
+ expresion: 'expression',
384
+ expresions: 'expressions',
385
+ extenison: 'extension',
386
+ extnesion: 'extension',
387
+ failre: 'failure',
388
+ falure: 'failure',
389
+ failuer: 'failure',
390
+ featre: 'feature',
391
+ feture: 'feature',
392
+ feautre: 'feature',
393
+ filel: 'file',
394
+ filse: 'files',
395
+ fiels: 'fields',
396
+ feilds: 'fields',
397
+ foucs: 'focus',
398
+ focsu: 'focus',
399
+ follw: 'follow',
400
+ folow: 'follow',
401
+ forgeting: 'forgetting',
402
+ forn: 'from',
403
+ frst: 'first',
404
+ frist: 'first',
405
+ fucntionality: 'functionality',
406
+ fucntion: 'function',
407
+ gaem: 'game',
408
+ genrate: 'generate',
409
+ genereate: 'generate',
410
+ genral: 'general',
411
+ generall: 'general',
412
+ givenn: 'given',
413
+ gloabl: 'global',
414
+ gorup: 'group',
415
+ gropu: 'group',
416
+ gruop: 'group',
417
+ haders: 'headers',
418
+ heades: 'headers',
419
+ heigth: 'height',
420
+ hiddne: 'hidden',
421
+ hidde: 'hidden',
422
+ hierachy: 'hierarchy',
423
+ hiearchy: 'hierarchy',
424
+ higer: 'higher',
425
+ higest: 'highest',
426
+ hwo: 'how',
427
+ hwoever: 'however',
428
+ howver: 'however',
429
+ hoever: 'however',
430
+ iamge: 'image',
431
+ imag: 'image',
432
+ impelment: 'implement',
433
+ implment: 'implement',
434
+ implemenation: 'implementation',
435
+ implementaiton: 'implementation',
436
+ implemention: 'implementation',
437
+ inlcude: 'include',
438
+ incldue: 'include',
439
+ inclued: 'include',
440
+ indedx: 'index',
441
+ inde: 'index',
442
+ inflateed: 'inflated',
443
+ informaiton: 'information',
444
+ infomation: 'information',
445
+ inforamtion: 'information',
446
+ inheritence: 'inheritance',
447
+ inital: 'initial',
448
+ intial: 'initial',
449
+ initail: 'initial',
450
+ initialise: 'initialize',
451
+ initilize: 'initialize',
452
+ initialzied: 'initialized',
453
+ inptu: 'input',
454
+ inptu: 'input',
455
+ inpout: 'input',
456
+ instaed: 'instead',
457
+ insted: 'instead',
458
+ instrcution: 'instruction',
459
+ instructon: 'instruction',
460
+ intead: 'instead',
461
+ interace: 'interface',
462
+ interfaec: 'interface',
463
+ intput: 'input',
464
+ inupt: 'input',
465
+ inver: 'invert',
466
+ isnpect: 'inspect',
467
+ isseu: 'issue',
468
+ issus: 'issues',
469
+ itesm: 'items',
470
+ itmes: 'items',
471
+ jsut: 'just',
472
+ juyst: 'just',
473
+ knwo: 'know',
474
+ kown: 'known',
475
+ lanugage: 'language',
476
+ langauge: 'language',
477
+ languge: 'language',
478
+ lauch: 'launch',
479
+ lciense: 'license',
480
+ licnce: 'license',
481
+ liek: 'like',
482
+ lke: 'like',
483
+ lnik: 'link',
484
+ lniked: 'linked',
485
+ lisence: 'license',
486
+ lst: 'list',
487
+ liist: 'list',
488
+ liset: 'list',
489
+ loadng: 'loading',
490
+ lamnguage: 'language',
491
+ loggin: 'logging',
492
+ lookng: 'looking',
493
+ maina: 'main',
494
+ mainain: 'maintain',
495
+ manully: 'manually',
496
+ maunal: 'manual',
497
+ maunally: 'manually',
498
+ mehtod: 'method',
499
+ methdo: 'method',
500
+ metohd: 'method',
501
+ mehtods: 'methods',
502
+ methdos: 'methods',
503
+ midle: 'middle',
504
+ moel: 'model',
505
+ moudle: 'module',
506
+ moudles: 'modules',
507
+ msut: 'must',
508
+ mutliple: 'multiple',
509
+ multipe: 'multiple',
510
+ mulitple: 'multiple',
511
+ mroe: 'more',
512
+ mpore: 'more',
513
+ nmae: 'name',
514
+ nmaes: 'names',
515
+ namse: 'names',
516
+ naem: 'name',
517
+ neeed: 'need',
518
+ ned: 'need',
519
+ nescessary: 'necessary',
520
+ newever: 'newer',
521
+ nex: 'next',
522
+ nto: 'not',
523
+ nubmer: 'number',
524
+ numebr: 'number',
525
+ numbr: 'number',
526
+ numer: 'number',
527
+ ofset: 'offset',
528
+ offest: 'offset',
529
+ olny: 'only',
530
+ onyl: 'only',
531
+ ony: 'only',
532
+ opne: 'open',
533
+ oepn: 'open',
534
+ opiton: 'option',
535
+ optioanl: 'optional',
536
+ oprtion: 'option',
537
+ optios: 'options',
538
+ optons: 'options',
539
+ ordr: 'order',
540
+ orignal: 'original',
541
+ orginal: 'original',
542
+ orignal: 'original',
543
+ outptu: 'output',
544
+ ouput: 'output',
545
+ ovew: 'overview',
546
+ overide: 'override',
547
+ overide: 'override',
548
+ pakcage: 'package',
549
+ paragrpah: 'paragraph',
550
+ parrameter: 'parameter',
551
+ patth: 'path',
552
+ pah: 'path',
553
+ phsical: 'physical',
554
+ peice: 'piece',
555
+ pices: 'pieces',
556
+ platfrom: 'platform',
557
+ platfom: 'platform',
558
+ plese: 'please',
559
+ pleae: 'please',
560
+ pleas: 'please',
561
+ plugn: 'plugin',
562
+ portt: 'port',
563
+ posible: 'possible',
564
+ possibel: 'possible',
565
+ prit: 'print',
566
+ pritn: 'print',
567
+ privte: 'private',
568
+ priavte: 'private',
569
+ procecss: 'process',
570
+ proejct: 'project',
571
+ progect: 'project',
572
+ porject: 'project',
573
+ propblem: 'problem',
574
+ problme: 'problem',
575
+ problem: 'problem',
576
+ provde: 'provide',
577
+ provied: 'provided',
578
+ provder: 'provider',
579
+ puplic: 'public',
580
+ qeueu: 'queue',
581
+ querey: 'query',
582
+ queery: 'query',
583
+ queryy: 'query',
584
+ raelly: 'really',
585
+ realy: 'really',
586
+ reead: 'read',
587
+ recrod: 'record',
588
+ referece: 'reference',
589
+ refrence: 'reference',
590
+ refrences: 'references',
591
+ regsiter: 'register',
592
+ registr: 'register',
593
+ registred: 'registered',
594
+ relaod: 'reload',
595
+ realod: 'reload',
596
+ relase: 'release',
597
+ relaese: 'release',
598
+ remaing: 'remaining',
599
+ remvoed: 'removed',
600
+ remvoe: 'remove',
601
+ repetion: 'repetition',
602
+ repalce: 'replace',
603
+ replce: 'replace',
604
+ replcaed: 'replaced',
605
+ requried: 'required',
606
+ requred: 'required',
607
+ reqired: 'required',
608
+ requirment: 'requirement',
609
+ requriement: 'requirement',
610
+ resouce: 'resource',
611
+ reosurce: 'resource',
612
+ resrouce: 'resource',
613
+ reuslt: 'result',
614
+ resul: 'result',
615
+ reslut: 'result',
616
+ resulst: 'results',
617
+ reuslts: 'results',
618
+ retrived: 'retrieved',
619
+ reveiw: 'review',
620
+ reviw: 'review',
621
+ rewritting: 'rewriting',
622
+ rigth: 'right',
623
+ rigt: 'right',
624
+ rnu: 'run',
625
+ runnign: 'running',
626
+ runing: 'running',
627
+ safly: 'safely',
628
+ samll: 'small',
629
+ smal: 'small',
630
+ scehduler: 'scheduler',
631
+ scheduelr: 'scheduler',
632
+ sceen: 'screen',
633
+ scrren: 'screen',
634
+ seale: 'scale',
635
+ seatle: 'settle',
636
+ secion: 'section',
637
+ seciton: 'section',
638
+ secton: 'section',
639
+ seelct: 'select',
640
+ selct: 'select',
641
+ selecet: 'select',
642
+ selecft: 'select',
643
+ sems: 'seems',
644
+ sentance: 'sentence',
645
+ sepcific: 'specific',
646
+ specifc: 'specific',
647
+ specfic: 'specific',
648
+ sepcify: 'specify',
649
+ serivce: 'service',
650
+ servce: 'service',
651
+ serivces: 'services',
652
+ shoud: 'should',
653
+ shuold: 'should',
654
+ shwo: 'show',
655
+ showd: 'showed',
656
+ shwon: 'shown',
657
+ sice: 'since',
658
+ sigin: 'signin',
659
+ signle: 'single',
660
+ sngle: 'single',
661
+ simplifed: 'simplified',
662
+ sitll: 'still',
663
+ slaot: 'slot',
664
+ slto: 'slot',
665
+ soem: 'some',
666
+ soemthing: 'something',
667
+ somthing: 'something',
668
+ soruce: 'source',
669
+ srouce: 'source',
670
+ souce: 'source',
671
+ specfic: 'specific',
672
+ spped: 'speed',
673
+ spce: 'space',
674
+ spcae: 'space',
675
+ spliting: 'splitting',
676
+ srping: 'spring',
677
+ stadard: 'standard',
678
+ standad: 'standard',
679
+ strcutre: 'structure',
680
+ strucutre: 'structure',
681
+ structre: 'structure',
682
+ stauts: 'status',
683
+ stataus: 'status',
684
+ stlye: 'style',
685
+ syte: 'style',
686
+ sucess: 'success',
687
+ succese: 'success',
688
+ suport: 'support',
689
+ supprot: 'support',
690
+ suppord: 'support',
691
+ suprt: 'support',
692
+ symobl: 'symbol',
693
+ symol: 'symbol',
694
+ syantx: 'syntax',
695
+ syste: 'system',
696
+ sytem: 'system',
697
+ systme: 'system',
698
+ tabel: 'table',
699
+ tabe: 'table',
700
+ tagerts: 'targets',
701
+ tahn: 'than',
702
+ thna: 'than',
703
+ taht: 'that',
704
+ theat: 'that',
705
+ therfore: 'therefore',
706
+ theree: 'there',
707
+ thigns: 'things',
708
+ thigs: 'things',
709
+ thnik: 'think',
710
+ thikn: 'think',
711
+ thniking: 'thinking',
712
+ though: 'though',
713
+ tihng: 'thing',
714
+ timne: 'time',
715
+ tmie: 'time',
716
+ tpoic: 'topic',
717
+ topci: 'topic',
718
+ trz: 'try',
719
+ trry: 'try',
720
+ tuen: 'tune',
721
+ turnng: 'turning',
722
+ twise: 'twice',
723
+ typcial: 'typical',
724
+ typcail: 'typical',
725
+ udner: 'under',
726
+ uner: 'under',
727
+ understnad: 'understand',
728
+ unfortunatley: 'unfortunately',
729
+ unqiue: 'unique',
730
+ unqie: 'unique',
731
+ unti: 'until',
732
+ upate: 'update',
733
+ upadte: 'update',
734
+ updte: 'update',
735
+ uesd: 'used',
736
+ usd: 'used',
737
+ useing: 'using',
738
+ usign: 'using',
739
+ usin: 'using',
740
+ usally: 'usually',
741
+ usuall: 'usually',
742
+ usualy: 'usually',
743
+ valdiate: 'validate',
744
+ valiate: 'validate',
745
+ vaule: 'value',
746
+ vaue: 'value',
747
+ vedio: 'video',
748
+ viev: 'view',
749
+ veiw: 'view',
750
+ vido: 'video',
751
+ wnat: 'want',
752
+ warining: 'warning',
753
+ warnig: 'warning',
754
+ warnign: 'warning',
755
+ watn: 'want',
756
+ wehn: 'when',
757
+ whne: 'when',
758
+ whne: 'when',
759
+ wehre: 'where',
760
+ whre: 'where',
761
+ wher: 'where',
762
+ whle: 'while',
763
+ whil: 'while',
764
+ wihtout: 'without',
765
+ wihtout: 'without',
766
+ witout: 'without',
767
+ wkith: 'with',
768
+ wokr: 'work',
769
+ wroking: 'working',
770
+ wrok: 'work',
771
+ wroks: 'works',
772
+ wrold: 'world',
773
+ wordl: 'world',
774
+ woud: 'would',
775
+ wuold: 'would',
776
+ woudl: 'would',
777
+ writting: 'writing',
778
+ wrapepr: 'wrapper',
779
+ wraper: 'wrapper',
780
+ wrriten: 'written',
781
+ yoru: 'your',
782
+ yuo: 'you',
783
+ yuor: 'your',
784
+ zeor: 'zero',
785
+ zreo: 'zero',
786
+ }
787
+
788
+ /** The largest edit distance worth showing. Beyond two, suggestions are noise. */
789
+ export const MAX_DISTANCE = 2
790
+
791
+ /** Below this length a "correction" is a different word, not a typo. */
792
+ export const MIN_LENGTH = 3
793
+
794
+ /** Learned words rank after the whole shipped list, never above it. */
795
+ const LEARNED_RANK_BASE = 1_000_000
796
+
797
+ /**
798
+ * Optimal-string-alignment Damerau-Levenshtein, with an early exit.
799
+ *
800
+ * Straight Levenshtein would not explain the most common fast-typing slip of
801
+ * all — two adjacent letters swapped (`atuo`, `teh`, `recieve`) — which costs it
802
+ * two edits and would fall outside a distance-2 budget on longer words.
803
+ *
804
+ * Returns `limit + 1` as soon as a row's best score exceeds the budget, so a
805
+ * hopeless candidate is abandoned without finishing the matrix.
806
+ */
807
+ export function distance(a, b, limit = MAX_DISTANCE) {
808
+ const al = a.length
809
+ const bl = b.length
810
+ const ceiling = limit + 1
811
+ if (Math.abs(al - bl) > limit) return ceiling
812
+ if (a === b) return 0
813
+
814
+ // Three rows, rotated: `prev` is row i-1, `prev2` is row i-2 (transpositions
815
+ // need the row before that one), `curr` is scratch for row i.
816
+ let prev2 = new Array(bl + 1)
817
+ let prev = new Array(bl + 1)
818
+ let curr = new Array(bl + 1)
819
+ for (let j = 0; j <= bl; j += 1) {
820
+ prev[j] = j
821
+ prev2[j] = j
822
+ }
823
+
824
+ for (let i = 1; i <= al; i += 1) {
825
+ curr[0] = i
826
+ let rowBest = i
827
+ const ca = a.charCodeAt(i - 1)
828
+ for (let j = 1; j <= bl; j += 1) {
829
+ const cost = ca === b.charCodeAt(j - 1) ? 0 : 1
830
+ let v = prev[j] + 1
831
+ const insertion = curr[j - 1] + 1
832
+ if (insertion < v) v = insertion
833
+ const substitution = prev[j - 1] + cost
834
+ if (substitution < v) v = substitution
835
+ if (
836
+ i > 1 &&
837
+ j > 1 &&
838
+ ca === b.charCodeAt(j - 2) &&
839
+ a.charCodeAt(i - 2) === b.charCodeAt(j - 1)
840
+ ) {
841
+ const transposition = prev2[j - 2] + 1
842
+ if (transposition < v) v = transposition
843
+ }
844
+ curr[j] = v
845
+ if (v < rowBest) rowBest = v
846
+ }
847
+ // No cell on this row can be within budget any more: abandon the candidate.
848
+ if (rowBest > limit) return ceiling
849
+ const recycled = prev2
850
+ prev2 = prev
851
+ prev = curr
852
+ curr = recycled
853
+ }
854
+ return prev[bl]
855
+ }
856
+
857
+ /** Title-case the first letter only, so `Teh` corrects to `The`. */
858
+ export function matchCase(original, replacement) {
859
+ if (original.length === 0) return replacement
860
+ const first = original[0]
861
+ if (first !== first.toUpperCase() || first === first.toLowerCase()) return replacement
862
+ const rest = original.slice(1)
863
+ // An all-caps token is an acronym, not a typo — leave it alone.
864
+ if (rest === rest.toUpperCase() && rest !== rest.toLowerCase()) return replacement
865
+ return replacement[0].toUpperCase() + replacement.slice(1)
866
+ }
867
+
868
+ /**
869
+ * Build the suggestion index over a frequency-ranked word list.
870
+ *
871
+ * @param words - Most common first. Index in this array IS the frequency rank.
872
+ * @param typoMap - Exact misspelling → correction pairs, answered instantly.
873
+ */
874
+ export function createEngine(words, typoMap = TYPO_MAP) {
875
+ const rank = new Map()
876
+ /** Bucket key `first letter + length` → candidate words, for a bounded scan. */
877
+ const buckets = new Map()
878
+
879
+ const list = Array.isArray(words) ? words : []
880
+ for (let i = 0; i < list.length; i += 1) {
881
+ const w = list[i]
882
+ if (typeof w !== 'string' || w.length === 0) continue
883
+ if (rank.has(w)) continue
884
+ rank.set(w, i)
885
+ for (let len = Math.max(MIN_LENGTH, w.length - MAX_DISTANCE); len <= w.length + MAX_DISTANCE; len += 1) {
886
+ const key = w[0] + ':' + len
887
+ const bucket = buckets.get(key)
888
+ if (bucket === undefined) buckets.set(key, [w])
889
+ else bucket.push(w)
890
+ }
891
+ }
892
+
893
+ /** Correct spellings the user has taught us; always treated as valid. */
894
+ const learned = new Set()
895
+
896
+ function isWord(word) {
897
+ return rank.has(word) || learned.has(word)
898
+ }
899
+
900
+ function addWord(word) {
901
+ const w = String(word ?? '').trim().toLowerCase()
902
+ if (!/^[a-z][a-z'-]*$/.test(w)) return false
903
+ if (rank.has(w)) return true
904
+ learned.add(w)
905
+ // Learned words are indexed too, at the very bottom of the ranking: a word
906
+ // the user taught us must still be able to WIN a correction (`courtkeyne`
907
+ // → `courtkeynet`), it just should not outrank everyday vocabulary.
908
+ rank.set(w, rank.size + LEARNED_RANK_BASE)
909
+ for (let len = Math.max(MIN_LENGTH, w.length - MAX_DISTANCE); len <= w.length + MAX_DISTANCE; len += 1) {
910
+ const key = w[0] + ':' + len
911
+ const bucket = buckets.get(key)
912
+ if (bucket === undefined) buckets.set(key, [w])
913
+ else bucket.push(w)
914
+ }
915
+ return true
916
+ }
917
+
918
+ /**
919
+ * Ranked corrections for one typed token, best first.
920
+ *
921
+ * Answers `[]` for anything already spelled correctly — correcting a real
922
+ * word is Chrome's most annoying behaviour (`hoe` → `how`), and the ranked
923
+ * list is what makes that check meaningful.
924
+ */
925
+ function suggest(word, options = {}) {
926
+ const raw = String(word ?? '')
927
+ if (raw.length < MIN_LENGTH) return []
928
+ if (!/^[A-Za-z][A-Za-z'’-]*$/.test(raw)) return []
929
+ // A fully upper-case token is an acronym (API, DSH, PDF), never a typo.
930
+ if (raw.length > 1 && raw === raw.toUpperCase()) return []
931
+
932
+ const lower = raw.toLowerCase()
933
+ const limit = Number.isInteger(options.limit) ? options.limit : 3
934
+ const cap = Number.isInteger(options.maxDistance) ? options.maxDistance : MAX_DISTANCE
935
+
936
+ const out = []
937
+ const seen = new Set()
938
+
939
+ const direct = typoMap?.[lower]
940
+ if (typeof direct === 'string' && direct !== lower) {
941
+ out.push({ word: matchCase(raw, direct), distance: 0, source: 'typo-map' })
942
+ seen.add(direct)
943
+ }
944
+
945
+ if (isWord(lower)) return out.slice(0, limit)
946
+
947
+ const firstBuckets = []
948
+ for (let len = Math.max(MIN_LENGTH, lower.length - cap); len <= lower.length + cap; len += 1) {
949
+ const bucket = buckets.get(lower[0] + ':' + len)
950
+ if (bucket !== undefined) firstBuckets.push(bucket)
951
+ }
952
+
953
+ const hits = []
954
+ /** A word is filed in several length buckets, so it can be met more than once. */
955
+ const counted = new Set()
956
+ for (const bucket of firstBuckets) {
957
+ for (const candidate of bucket) {
958
+ if (seen.has(candidate) || counted.has(candidate)) continue
959
+ const d = distance(lower, candidate, cap)
960
+ if (d > cap) continue
961
+ counted.add(candidate)
962
+ hits.push({ word: candidate, distance: d, rank: rank.get(candidate) ?? Infinity })
963
+ }
964
+ }
965
+
966
+ // Distance first: one edit away always beats two, however rare. Among
967
+ // equally distant candidates the commoner word wins, which is what puts
968
+ // `the` above `eth` for `theh`.
969
+ hits.sort((a, b) => a.distance - b.distance || a.rank - b.rank)
970
+
971
+ for (const hit of hits) {
972
+ if (out.length >= limit) break
973
+ out.push({ word: matchCase(raw, hit.word), distance: hit.distance, source: 'distance' })
974
+ }
975
+ return out
976
+ }
977
+
978
+ return { suggest, isWord, addWord, learned: () => [...learned], size: rank.size }
979
+ }
980
+
981
+ export default { TYPO_MAP, MAX_DISTANCE, MIN_LENGTH, distance, matchCase, createEngine }