aboutsummaryrefslogtreecommitdiff
path: root/ext/js/language/translator.js
blob: c885cd4d1c054fe4634b234d50c290d7b9742d62 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
/*
 * Copyright (C) 2016-2021  Yomichan Authors
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

/* global
 * Deinflector
 * RegexUtil
 * TextSourceMap
 */

/**
 * Class which finds term and kanji definitions for text.
 */
class Translator {
    /**
     * Creates a new Translator instance.
     * @param database An instance of DictionaryDatabase.
     */
    constructor({japaneseUtil, database}) {
        this._japaneseUtil = japaneseUtil;
        this._database = database;
        this._deinflector = null;
        this._tagCache = new Map();
        this._stringComparer = new Intl.Collator('en-US'); // Invariant locale
    }

    /**
     * Initializes the instance for use. The public API should not be used until
     * this function has been called.
     * @param deinflectionReasons The raw deinflections reasons data that the Deinflector uses.
     */
    prepare(deinflectionReasons) {
        this._deinflector = new Deinflector(deinflectionReasons);
    }

    /**
     * Clears the database tag cache. This should be executed if the database is changed.
     */
    clearDatabaseCaches() {
        this._tagCache.clear();
    }

    /**
     * Finds term definitions for the given text.
     * @param mode The mode to use for finding terms, which determines the format of the resulting array.
     *   One of: 'group', 'merge', 'split', 'simple'
     * @param text The text to find terms for.
     * @param options An object using the following structure:
     *   {
     *     wildcard: (enum: null, 'prefix', 'suffix'),
     *     mainDictionary: (string),
     *     alphanumeric: (boolean),
     *     convertHalfWidthCharacters: (enum: 'false', 'true', 'variant'),
     *     convertNumericCharacters: (enum: 'false', 'true', 'variant'),
     *     convertAlphabeticCharacters: (enum: 'false', 'true', 'variant'),
     *     convertHiraganaToKatakana: (enum: 'false', 'true', 'variant'),
     *     convertKatakanaToHiragana: (enum: 'false', 'true', 'variant'),
     *     collapseEmphaticSequences: (enum: 'false', 'true', 'full'),
     *     textReplacements: [
     *       (null or [
     *         {pattern: (RegExp), replacement: (string)}
     *         ...
     *       ])
     *       ...
     *     ],
     *     enabledDictionaryMap: (Map of [
     *       (string),
     *       {
     *         index: (number),
     *         priority: (number),
     *         allowSecondarySearches: (boolean)
     *       }
     *     ])
     *   }
     * @returns An array of [definitions, textLength]. The structure of each definition depends on the
     *   mode parameter, see the _create?TermDefinition?() functions for structure details.
     */
    async findTerms(mode, text, options) {
        switch (mode) {
            case 'group':
                return await this._findTermsGrouped(text, options);
            case 'merge':
                return await this._findTermsMerged(text, options);
            case 'split':
                return await this._findTermsSplit(text, options);
            case 'simple':
                return await this._findTermsSimple(text, options);
            default:
                return [[], 0];
        }
    }

    /**
     * Finds kanji definitions for the given text.
     * @param text The text to find kanji definitions for. This string can be of any length,
     *   but is typically just one character, which is a single kanji. If the string is multiple
     *   characters long, each character will be searched in the database.
     * @param options An object using the following structure:
     *   {
     *     enabledDictionaryMap: (Map of [
     *       (string),
     *       {
     *         index: (number),
     *         priority: (number)
     *       }
     *     ])
     *   }
     * @returns An array of definitions. See the _createKanjiDefinition() function for structure details.
     */
    async findKanji(text, options) {
        const {enabledDictionaryMap} = options;
        const kanjiUnique = new Set();
        for (const c of text) {
            kanjiUnique.add(c);
        }

        const databaseDefinitions = await this._database.findKanjiBulk([...kanjiUnique], enabledDictionaryMap);
        if (databaseDefinitions.length === 0) { return []; }

        this._sortDatabaseDefinitionsByIndex(databaseDefinitions);

        const definitions = [];
        for (const {character, onyomi, kunyomi, tags, glossary, stats, dictionary} of databaseDefinitions) {
            const expandedStats = await this._expandStats(stats, dictionary);
            const expandedTags = await this._expandTags(tags, dictionary);
            this._sortTags(expandedTags);

            const definition = this._createKanjiDefinition(character, dictionary, onyomi, kunyomi, glossary, expandedTags, expandedStats);
            definitions.push(definition);
        }

        await this._buildKanjiMeta(definitions, enabledDictionaryMap);

        return definitions;
    }

    // Find terms core functions

    async _findTermsSimple(text, options) {
        const {enabledDictionaryMap} = options;
        const [definitions, length] = await this._findTermsInternal(text, enabledDictionaryMap, options);
        this._sortDefinitions(definitions);
        return [definitions, length];
    }

    async _findTermsSplit(text, options) {
        const {enabledDictionaryMap} = options;
        const [definitions, length] = await this._findTermsInternal(text, enabledDictionaryMap, options);
        await this._buildTermMeta(definitions, enabledDictionaryMap);
        this._sortDefinitions(definitions);
        return [definitions, length];
    }

    async _findTermsGrouped(text, options) {
        const {enabledDictionaryMap} = options;
        const [definitions, length] = await this._findTermsInternal(text, enabledDictionaryMap, options);

        const groupedDefinitions = this._groupTerms(definitions, enabledDictionaryMap);
        await this._buildTermMeta(groupedDefinitions, enabledDictionaryMap);
        this._sortDefinitions(groupedDefinitions);

        for (const definition of groupedDefinitions) {
            this._flagRedundantDefinitionTags(definition.definitions);
        }

        return [groupedDefinitions, length];
    }

    async _findTermsMerged(text, options) {
        const {mainDictionary, enabledDictionaryMap} = options;
        const [definitions, length] = await this._findTermsInternal(text, enabledDictionaryMap, options);
        const {sequencedDefinitions, unsequencedDefinitions} = await this._getSequencedDefinitions(definitions, mainDictionary, enabledDictionaryMap);
        const definitionsMerged = [];

        for (const {relatedDefinitions, secondaryDefinitions} of sequencedDefinitions) {
            const mergedDefinition = this._getMergedDefinition(relatedDefinitions, secondaryDefinitions);
            definitionsMerged.push(mergedDefinition);
        }

        for (const groupedDefinition of this._groupTerms(unsequencedDefinitions, enabledDictionaryMap)) {
            const {reasons, score, expression, reading, source, rawSource, definitions: definitions2} = groupedDefinition;
            const termDetailsList = this._createTermDetailsList(definitions2);
            const compatibilityDefinition = this._createMergedTermDefinition(
                source,
                rawSource,
                this._convertTermDefinitionsToMergedGlossaryTermDefinitions(definitions2),
                [expression],
                [reading],
                termDetailsList,
                reasons,
                score
            );
            definitionsMerged.push(compatibilityDefinition);
        }

        await this._buildTermMeta(definitionsMerged, enabledDictionaryMap);
        this._sortDefinitions(definitionsMerged);

        for (const definition of definitionsMerged) {
            this._flagRedundantDefinitionTags(definition.definitions);
        }

        return [definitionsMerged, length];
    }

    // Find terms internal implementation

    async _findTermsInternal(text, enabledDictionaryMap, options) {
        const {alphanumeric, wildcard} = options;
        text = this._getSearchableText(text, alphanumeric);
        if (text.length === 0) {
            return [[], 0];
        }

        const deinflections = (
            wildcard ?
            await this._findTermWildcard(text, enabledDictionaryMap, wildcard) :
            await this._findTermDeinflections(text, enabledDictionaryMap, options)
        );

        let maxLength = 0;
        const definitions = [];
        const definitionIds = new Set();
        for (const {databaseDefinitions, source, rawSource, term, reasons} of deinflections) {
            if (databaseDefinitions.length === 0) { continue; }
            maxLength = Math.max(maxLength, rawSource.length);
            for (const databaseDefinition of databaseDefinitions) {
                const {id} = databaseDefinition;
                if (definitionIds.has(id)) { continue; }
                const definition = await this._createTermDefinitionFromDatabaseDefinition(databaseDefinition, source, rawSource, term, reasons, true, enabledDictionaryMap);
                definitions.push(definition);
                definitionIds.add(id);
            }
        }

        return [definitions, maxLength];
    }

    async _findTermWildcard(text, enabledDictionaryMap, wildcard) {
        const databaseDefinitions = await this._database.findTermsBulk([text], enabledDictionaryMap, wildcard);
        return databaseDefinitions.length > 0 ? [this._createDeinflection(text, text, text, 0, [], databaseDefinitions)] : [];
    }

    async _findTermDeinflections(text, enabledDictionaryMap, options) {
        const deinflections = this._getAllDeinflections(text, options);

        if (deinflections.length === 0) {
            return [];
        }

        const uniqueDeinflectionTerms = [];
        const uniqueDeinflectionArrays = [];
        const uniqueDeinflectionsMap = new Map();
        for (const deinflection of deinflections) {
            const term = deinflection.term;
            let deinflectionArray = uniqueDeinflectionsMap.get(term);
            if (typeof deinflectionArray === 'undefined') {
                deinflectionArray = [];
                uniqueDeinflectionTerms.push(term);
                uniqueDeinflectionArrays.push(deinflectionArray);
                uniqueDeinflectionsMap.set(term, deinflectionArray);
            }
            deinflectionArray.push(deinflection);
        }

        const databaseDefinitions = await this._database.findTermsBulk(uniqueDeinflectionTerms, enabledDictionaryMap, null);

        for (const databaseDefinition of databaseDefinitions) {
            const definitionRules = Deinflector.rulesToRuleFlags(databaseDefinition.rules);
            for (const deinflection of uniqueDeinflectionArrays[databaseDefinition.index]) {
                const deinflectionRules = deinflection.rules;
                if (deinflectionRules === 0 || (definitionRules & deinflectionRules) !== 0) {
                    deinflection.databaseDefinitions.push(databaseDefinition);
                }
            }
        }

        return deinflections;
    }

    _getAllDeinflections(text, options) {
        const textOptionVariantArray = [
            this._getTextReplacementsVariants(options),
            this._getTextOptionEntryVariants(options.convertHalfWidthCharacters),
            this._getTextOptionEntryVariants(options.convertNumericCharacters),
            this._getTextOptionEntryVariants(options.convertAlphabeticCharacters),
            this._getTextOptionEntryVariants(options.convertHiraganaToKatakana),
            this._getTextOptionEntryVariants(options.convertKatakanaToHiragana),
            this._getCollapseEmphaticOptions(options)
        ];

        const jp = this._japaneseUtil;
        const deinflections = [];
        const used = new Set();
        for (const [textReplacements, halfWidth, numeric, alphabetic, katakana, hiragana, [collapseEmphatic, collapseEmphaticFull]] of this._getArrayVariants(textOptionVariantArray)) {
            let text2 = text;
            const sourceMap = new TextSourceMap(text2);
            if (textReplacements !== null) {
                text2 = this._applyTextReplacements(text2, sourceMap, textReplacements);
            }
            if (halfWidth) {
                text2 = jp.convertHalfWidthKanaToFullWidth(text2, sourceMap);
            }
            if (numeric) {
                text2 = jp.convertNumericToFullWidth(text2);
            }
            if (alphabetic) {
                text2 = jp.convertAlphabeticToKana(text2, sourceMap);
            }
            if (katakana) {
                text2 = jp.convertHiraganaToKatakana(text2);
            }
            if (hiragana) {
                text2 = jp.convertKatakanaToHiragana(text2);
            }
            if (collapseEmphatic) {
                text2 = jp.collapseEmphaticSequences(text2, collapseEmphaticFull, sourceMap);
            }

            for (let i = text2.length; i > 0; --i) {
                const source = text2.substring(0, i);
                if (used.has(source)) { break; }
                used.add(source);
                const rawSource = sourceMap.source.substring(0, sourceMap.getSourceLength(i));
                for (const {term, rules, reasons} of this._deinflector.deinflect(source)) {
                    deinflections.push(this._createDeinflection(source, rawSource, term, rules, reasons, []));
                }
            }
        }
        return deinflections;
    }

    _createDeinflection(source, rawSource, term, rules, reasons, databaseDefinitions) {
        return {source, rawSource, term, rules, reasons, databaseDefinitions};
    }

    /**
     * @param definitions An array of 'term' definitions.
     * @param mainDictionary The name of the main dictionary.
     * @param enabledDictionaryMap The map of enabled dictionaries and their settings.
     */
    async _getSequencedDefinitions(definitions, mainDictionary, enabledDictionaryMap) {
        const secondarySearchDictionaryMap = this._getSecondarySearchDictionaryMap(enabledDictionaryMap);
        const sequenceList = [];
        const sequencedDefinitionMap = new Map();
        const sequencedDefinitions = [];
        const unsequencedDefinitions = new Map();
        for (const definition of definitions) {
            const {sequence, dictionary, id} = definition;
            if (mainDictionary === dictionary && sequence >= 0) {
                let sequencedDefinition = sequencedDefinitionMap.get(sequence);
                if (typeof sequencedDefinition === 'undefined') {
                    sequencedDefinition = {
                        relatedDefinitions: [],
                        definitionIds: new Set(),
                        secondaryDefinitions: []
                    };
                    sequencedDefinitionMap.set(sequence, sequencedDefinition);
                    sequencedDefinitions.push(sequencedDefinition);
                    sequenceList.push(sequence);
                }
                sequencedDefinition.relatedDefinitions.push(definition);
                sequencedDefinition.definitionIds.add(id);
            } else {
                unsequencedDefinitions.set(id, definition);
            }
        }

        if (sequenceList.length > 0) {
            await this._addRelatedDefinitions(sequencedDefinitions, unsequencedDefinitions, sequenceList, mainDictionary, enabledDictionaryMap);
            await this._addSecondaryDefinitions(sequencedDefinitions, unsequencedDefinitions, enabledDictionaryMap, secondarySearchDictionaryMap);
        }

        for (const {relatedDefinitions} of sequencedDefinitions) {
            this._sortDefinitionsById(relatedDefinitions);
        }

        return {sequencedDefinitions, unsequencedDefinitions: [...unsequencedDefinitions.values()]};
    }

    async _addRelatedDefinitions(sequencedDefinitions, unsequencedDefinitions, sequenceList, mainDictionary, enabledDictionaryMap) {
        const databaseDefinitions = await this._database.findTermsBySequenceBulk(sequenceList, mainDictionary);
        for (const databaseDefinition of databaseDefinitions) {
            const {relatedDefinitions, definitionIds} = sequencedDefinitions[databaseDefinition.index];
            const {id} = databaseDefinition;
            if (definitionIds.has(id)) { continue; }

            const {source, rawSource, sourceTerm} = relatedDefinitions[0];
            const definition = await this._createTermDefinitionFromDatabaseDefinition(databaseDefinition, source, rawSource, sourceTerm, [], false, enabledDictionaryMap);
            relatedDefinitions.push(definition);
            definitionIds.add(id);
            unsequencedDefinitions.delete(id);
        }
    }

    async _addSecondaryDefinitions(sequencedDefinitions, unsequencedDefinitions, enabledDictionaryMap, secondarySearchDictionaryMap) {
        if (unsequencedDefinitions.length === 0 && secondarySearchDictionaryMap.size === 0) { return; }

        // Prepare grouping info
        const expressionList = [];
        const readingList = [];
        const targetList = [];
        const targetMap = new Map();

        for (const sequencedDefinition of sequencedDefinitions) {
            const {relatedDefinitions} = sequencedDefinition;
            for (const definition of relatedDefinitions) {
                const {expressions: [{expression, reading}]} = definition;
                const key = this._createMapKey([expression, reading]);
                let target = targetMap.get(key);
                if (typeof target === 'undefined') {
                    target = {
                        sequencedDefinitions: [],
                        searchSecondary: false
                    };
                    targetMap.set(key, target);
                }
                target.sequencedDefinitions.push(sequencedDefinition);
                if (!definition.isPrimary && !target.searchSecondary) {
                    target.searchSecondary = true;
                    expressionList.push(expression);
                    readingList.push(reading);
                    targetList.push(target);
                }
            }
        }

        // Group unsequenced definitions with sequenced definitions that have a matching [expression, reading].
        for (const [id, definition] of unsequencedDefinitions.entries()) {
            const {expressions: [{expression, reading}]} = definition;
            const key = this._createMapKey([expression, reading]);
            const target = targetMap.get(key);
            if (typeof target === 'undefined') { continue; }

            for (const {definitionIds, secondaryDefinitions} of target.sequencedDefinitions) {
                if (definitionIds.has(id)) { continue; }

                secondaryDefinitions.push(definition);
                definitionIds.add(id);
                unsequencedDefinitions.delete(id);
                break;
            }
        }

        // Search database for additional secondary terms
        if (expressionList.length === 0 || secondarySearchDictionaryMap.size === 0) { return; }

        const databaseDefinitions = await this._database.findTermsExactBulk(expressionList, readingList, secondarySearchDictionaryMap);
        this._sortDatabaseDefinitionsByIndex(databaseDefinitions);

        for (const databaseDefinition of databaseDefinitions) {
            const {index, id} = databaseDefinition;
            const source = expressionList[index];
            const target = targetList[index];
            for (const {definitionIds, secondaryDefinitions} of target.sequencedDefinitions) {
                if (definitionIds.has(id)) { continue; }

                const definition = await this._createTermDefinitionFromDatabaseDefinition(databaseDefinition, source, source, source, [], false, enabledDictionaryMap);
                secondaryDefinitions.push(definition);
                definitionIds.add(id);
                unsequencedDefinitions.delete(id);
            }
        }
    }

    _getMergedDefinition(relatedDefinitions, secondaryDefinitions) {
        const {reasons, source, rawSource} = relatedDefinitions[0];
        const allDefinitions = secondaryDefinitions.length > 0 ? [...relatedDefinitions, ...secondaryDefinitions] : relatedDefinitions;
        const score = this._getMaxPrimaryDefinitionScore(allDefinitions);

        // Merge by glossary
        const allExpressions = new Set();
        const allReadings = new Set();
        const glossaryDefinitionGroupMap = new Map();
        for (const definition of allDefinitions) {
            const {dictionary, glossary, expressions: [{expression, reading}]} = definition;

            const key = this._createMapKey([dictionary, ...glossary]);
            let group = glossaryDefinitionGroupMap.get(key);
            if (typeof group === 'undefined') {
                group = {
                    expressions: new Set(),
                    readings: new Set(),
                    definitions: []
                };
                glossaryDefinitionGroupMap.set(key, group);
            }

            allExpressions.add(expression);
            allReadings.add(reading);
            group.expressions.add(expression);
            group.readings.add(reading);
            group.definitions.push(definition);
        }

        const glossaryDefinitions = [];
        for (const {expressions, readings, definitions} of glossaryDefinitionGroupMap.values()) {
            const glossaryDefinition = this._createMergedGlossaryTermDefinition(
                source,
                rawSource,
                definitions,
                expressions,
                readings,
                allExpressions,
                allReadings
            );
            glossaryDefinitions.push(glossaryDefinition);
        }
        this._sortDefinitions(glossaryDefinitions);

        const termDetailsList = this._createTermDetailsList(allDefinitions);

        return this._createMergedTermDefinition(
            source,
            rawSource,
            glossaryDefinitions,
            [...allExpressions],
            [...allReadings],
            termDetailsList,
            reasons,
            score
        );
    }

    _getUniqueDefinitionTags(definitions) {
        const definitionTagsMap = new Map();
        for (const {definitionTags} of definitions) {
            for (const tag of definitionTags) {
                const {name} = tag;
                if (definitionTagsMap.has(name)) { continue; }
                definitionTagsMap.set(name, this._cloneTag(tag));
            }
        }
        return [...definitionTagsMap.values()];
    }

    _flagRedundantDefinitionTags(definitions) {
        let lastDictionary = null;
        let lastPartOfSpeech = '';
        const removeCategoriesSet = new Set();

        for (const {dictionary, definitionTags} of definitions) {
            const partOfSpeech = this._createMapKey(this._getTagNamesWithCategory(definitionTags, 'partOfSpeech'));

            if (lastDictionary !== dictionary) {
                lastDictionary = dictionary;
                lastPartOfSpeech = '';
            }

            if (lastPartOfSpeech === partOfSpeech) {
                removeCategoriesSet.add('partOfSpeech');
            } else {
                lastPartOfSpeech = partOfSpeech;
            }

            if (removeCategoriesSet.size > 0) {
                this._flagTagsWithCategoryAsRedundant(definitionTags, removeCategoriesSet);
                removeCategoriesSet.clear();
            }
        }
    }

    /**
     * Groups definitions with the same [source, expression, reading, reasons].
     * @param definitions An array of 'term' definitions.
     * @returns An array of 'termGrouped' definitions.
     */
    _groupTerms(definitions) {
        const groups = new Map();
        for (const definition of definitions) {
            const {source, reasons, expressions: [{expression, reading}]} = definition;
            const key = this._createMapKey([source, expression, reading, ...reasons]);
            let groupDefinitions = groups.get(key);
            if (typeof groupDefinitions === 'undefined') {
                groupDefinitions = [];
                groups.set(key, groupDefinitions);
            }

            groupDefinitions.push(definition);
        }

        const results = [];
        for (const groupDefinitions of groups.values()) {
            this._sortDefinitions(groupDefinitions);
            const definition = this._createGroupedTermDefinition(groupDefinitions);
            results.push(definition);
        }

        return results;
    }

    _convertTermDefinitionsToMergedGlossaryTermDefinitions(definitions) {
        const convertedDefinitions = [];
        for (const definition of definitions) {
            const {source, rawSource, expression, reading} = definition;
            const expressions = new Set([expression]);
            const readings = new Set([reading]);
            const convertedDefinition = this._createMergedGlossaryTermDefinition(source, rawSource, [definition], expressions, readings, expressions, readings);
            convertedDefinitions.push(convertedDefinition);
        }
        return convertedDefinitions;
    }

    // Metadata building

    async _buildTermMeta(definitions, enabledDictionaryMap) {
        const allDefinitions = this._getAllDefinitions(definitions);
        const expressionMap = new Map();
        const expressionValues = [];
        const expressionKeys = [];

        for (const {expressions, frequencies: frequencies1, pitches: pitches1} of allDefinitions) {
            for (let i = 0, ii = expressions.length; i < ii; ++i) {
                const {expression, reading, frequencies: frequencies2, pitches: pitches2} = expressions[i];
                let readingMap = expressionMap.get(expression);
                if (typeof readingMap === 'undefined') {
                    readingMap = new Map();
                    expressionMap.set(expression, readingMap);
                    expressionValues.push(readingMap);
                    expressionKeys.push(expression);
                }
                let targets = readingMap.get(reading);
                if (typeof targets === 'undefined') {
                    targets = [];
                    readingMap.set(reading, targets);
                }
                targets.push(
                    {frequencies: frequencies1, pitches: pitches1, index: i},
                    {frequencies: frequencies2, pitches: pitches2, index: i}
                );
            }
        }

        const metas = await this._database.findTermMetaBulk(expressionKeys, enabledDictionaryMap);
        for (const {expression, mode, data, dictionary, index} of metas) {
            const dictionaryOrder = this._getDictionaryOrder(dictionary, enabledDictionaryMap);
            const map2 = expressionValues[index];
            for (const [reading, targets] of map2.entries()) {
                switch (mode) {
                    case 'freq':
                        {
                            let frequency = data;
                            const hasReading = (data !== null && typeof data === 'object');
                            if (hasReading) {
                                if (data.reading !== reading) { continue; }
                                frequency = data.frequency;
                            }
                            for (const {frequencies, index: expressionIndex} of targets) {
                                frequencies.push({index: frequencies.length, expressionIndex, dictionary, dictionaryOrder, expression, reading, hasReading, frequency});
                            }
                        }
                        break;
                    case 'pitch':
                        {
                            if (data.reading !== reading) { continue; }
                            const pitches2 = [];
                            for (let {position, tags} of data.pitches) {
                                tags = Array.isArray(tags) ? await this._expandTags(tags, dictionary) : [];
                                pitches2.push({position, tags});
                            }
                            for (const {pitches, index: expressionIndex} of targets) {
                                pitches.push({index: pitches.length, expressionIndex, dictionary, dictionaryOrder, expression, reading, pitches: pitches2});
                            }
                        }
                        break;
                }
            }
        }

        for (const definition of allDefinitions) {
            this._sortTermDefinitionMeta(definition);
        }
    }

    async _buildKanjiMeta(definitions, enabledDictionaryMap) {
        const kanjiList = [];
        for (const {character} of definitions) {
            kanjiList.push(character);
        }

        const metas = await this._database.findKanjiMetaBulk(kanjiList, enabledDictionaryMap);
        for (const {character, mode, data, dictionary, index} of metas) {
            const dictionaryOrder = this._getDictionaryOrder(dictionary, enabledDictionaryMap);
            switch (mode) {
                case 'freq':
                    {
                        const {frequencies} = definitions[index];
                        frequencies.push({index: frequencies.length, dictionary, dictionaryOrder, character, frequency: data});
                    }
                    break;
            }
        }

        for (const definition of definitions) {
            this._sortKanjiDefinitionMeta(definition);
        }
    }

    async _expandTags(names, dictionary) {
        const tagMetaList = await this._getTagMetaList(names, dictionary);
        const results = [];
        for (let i = 0, ii = tagMetaList.length; i < ii; ++i) {
            const meta = tagMetaList[i];
            const name = names[i];
            const {category, notes, order, score} = (meta !== null ? meta : {});
            const tag = this._createTag(name, category, notes, order, score, dictionary, false);
            results.push(tag);
        }
        return results;
    }

    async _expandStats(items, dictionary) {
        const names = Object.keys(items);
        const tagMetaList = await this._getTagMetaList(names, dictionary);

        const statsGroups = new Map();
        for (let i = 0; i < names.length; ++i) {
            const name = names[i];
            const meta = tagMetaList[i];
            if (meta === null) { continue; }

            const {category, notes, order, score} = meta;
            let group = statsGroups.get(category);
            if (typeof group === 'undefined') {
                group = [];
                statsGroups.set(category, group);
            }

            const value = items[name];
            const stat = this._createKanjiStat(name, category, notes, order, score, dictionary, value);
            group.push(stat);
        }

        const stats = {};
        for (const [category, group] of statsGroups.entries()) {
            this._sortKanjiStats(group);
            stats[category] = group;
        }
        return stats;
    }

    async _getTagMetaList(names, dictionary) {
        const tagMetaList = [];
        let cache = this._tagCache.get(dictionary);
        if (typeof cache === 'undefined') {
            cache = new Map();
            this._tagCache.set(dictionary, cache);
        }

        for (const name of names) {
            const base = this._getNameBase(name);

            let tagMeta = cache.get(base);
            if (typeof tagMeta === 'undefined') {
                tagMeta = await this._database.findTagForTitle(base, dictionary);
                cache.set(base, tagMeta);
            }

            tagMetaList.push(tagMeta);
        }

        return tagMetaList;
    }

    // Simple helpers

    _getNameBase(name) {
        const pos = name.indexOf(':');
        return (pos >= 0 ? name.substring(0, pos) : name);
    }

    _getSearchableText(text, allowAlphanumericCharacters) {
        if (allowAlphanumericCharacters) {
            return text;
        }

        const jp = this._japaneseUtil;
        let newText = '';
        for (const c of text) {
            if (!jp.isCodePointJapanese(c.codePointAt(0))) {
                break;
            }
            newText += c;
        }
        return newText;
    }

    _getTextOptionEntryVariants(value) {
        switch (value) {
            case 'true': return [true];
            case 'variant': return [false, true];
            default: return [false];
        }
    }

    _getCollapseEmphaticOptions(options) {
        const collapseEmphaticOptions = [[false, false]];
        switch (options.collapseEmphaticSequences) {
            case 'true':
                collapseEmphaticOptions.push([true, false]);
                break;
            case 'full':
                collapseEmphaticOptions.push([true, false], [true, true]);
                break;
        }
        return collapseEmphaticOptions;
    }

    _getTextReplacementsVariants(options) {
        return options.textReplacements;
    }

    _getSecondarySearchDictionaryMap(enabledDictionaryMap) {
        const secondarySearchDictionaryMap = new Map();
        for (const [dictionary, details] of enabledDictionaryMap.entries()) {
            if (!details.allowSecondarySearches) { continue; }
            secondarySearchDictionaryMap.set(dictionary, details);
        }
        return secondarySearchDictionaryMap;
    }

    _getDictionaryOrder(dictionary, enabledDictionaryMap) {
        const info = enabledDictionaryMap.get(dictionary);
        const {index, priority} = typeof info !== 'undefined' ? info : {index: enabledDictionaryMap.size, priority: 0};
        return {index, priority};
    }

    _getTagNamesWithCategory(tags, category) {
        const results = [];
        for (const tag of tags) {
            if (tag.category !== category) { continue; }
            results.push(tag.name);
        }
        results.sort();
        return results;
    }

    _flagTagsWithCategoryAsRedundant(tags, removeCategoriesSet) {
        for (const tag of tags) {
            if (removeCategoriesSet.has(tag.category)) {
                tag.redundant = true;
            }
        }
    }

    _getUniqueDictionaryNames(definitions) {
        const uniqueDictionaryNames = new Set();
        for (const {dictionaryNames} of definitions) {
            for (const dictionaryName of dictionaryNames) {
                uniqueDictionaryNames.add(dictionaryName);
            }
        }
        return [...uniqueDictionaryNames];
    }

    _getUniqueTermTags(definitions) {
        const newTermTags = [];
        if (definitions.length <= 1) {
            for (const {termTags} of definitions) {
                for (const tag of termTags) {
                    newTermTags.push(this._cloneTag(tag));
                }
            }
        } else {
            const tagsSet = new Set();
            let checkTagsMap = false;
            for (const {termTags} of definitions) {
                for (const tag of termTags) {
                    const key = this._getTagMapKey(tag);
                    if (checkTagsMap && tagsSet.has(key)) { continue; }
                    tagsSet.add(key);
                    newTermTags.push(this._cloneTag(tag));
                }
                checkTagsMap = true;
            }
        }
        return newTermTags;
    }

    *_getArrayVariants(arrayVariants) {
        const ii = arrayVariants.length;

        let total = 1;
        for (let i = 0; i < ii; ++i) {
            total *= arrayVariants[i].length;
        }

        for (let a = 0; a < total; ++a) {
            const variant = [];
            let index = a;
            for (let i = 0; i < ii; ++i) {
                const entryVariants = arrayVariants[i];
                variant.push(entryVariants[index % entryVariants.length]);
                index = Math.floor(index / entryVariants.length);
            }
            yield variant;
        }
    }

    _areSetsEqual(set1, set2) {
        if (set1.size !== set2.size) {
            return false;
        }

        for (const value of set1) {
            if (!set2.has(value)) {
                return false;
            }
        }

        return true;
    }

    _getSetIntersection(set1, set2) {
        const result = [];
        for (const value of set1) {
            if (set2.has(value)) {
                result.push(value);
            }
        }
        return result;
    }

    _getAllDefinitions(definitions) {
        definitions = [...definitions];
        for (let i = 0; i < definitions.length; ++i) {
            const childDefinitions = definitions[i].definitions;
            if (Array.isArray(childDefinitions)) {
                definitions.push(...childDefinitions);
            }
        }
        return definitions;
    }

    // Reduction functions

    _getSourceTermMatchCountSum(definitions) {
        let result = 0;
        for (const {sourceTermExactMatchCount} of definitions) {
            result += sourceTermExactMatchCount;
        }
        return result;
    }

    _getMaxDefinitionScore(definitions) {
        let result = Number.MIN_SAFE_INTEGER;
        for (const {score} of definitions) {
            if (score > result) { result = score; }
        }
        return result;
    }

    _getMaxPrimaryDefinitionScore(definitions) {
        let result = Number.MIN_SAFE_INTEGER;
        for (const {isPrimary, score} of definitions) {
            if (isPrimary && score > result) { result = score; }
        }
        return result;
    }

    _getBestDictionaryOrder(definitions) {
        let index = Number.MAX_SAFE_INTEGER;
        let priority = Number.MIN_SAFE_INTEGER;
        for (const {dictionaryOrder: {index: index2, priority: priority2}} of definitions) {
            if (index2 < index) { index = index2; }
            if (priority2 > priority) { priority = priority2; }
        }
        return {index, priority};
    }

    // Common data creation and cloning functions

    _cloneTag(tag) {
        const {name, category, notes, order, score, dictionary, redundant} = tag;
        return this._createTag(name, category, notes, order, score, dictionary, redundant);
    }

    _getTagMapKey(tag) {
        const {name, category, notes} = tag;
        return this._createMapKey([name, category, notes]);
    }

    _createMapKey(array) {
        return JSON.stringify(array);
    }

    _createTag(name, category, notes, order, score, dictionary, redundant) {
        return {
            name,
            category: (typeof category === 'string' && category.length > 0 ? category : 'default'),
            notes: (typeof notes === 'string' ? notes : ''),
            order: (typeof order === 'number' ? order : 0),
            score: (typeof score === 'number' ? score : 0),
            dictionary: (typeof dictionary === 'string' ? dictionary : null),
            redundant
        };
    }

    _createKanjiStat(name, category, notes, order, score, dictionary, value) {
        return {
            name,
            category: (typeof category === 'string' && category.length > 0 ? category : 'default'),
            notes: (typeof notes === 'string' ? notes : ''),
            order: (typeof order === 'number' ? order : 0),
            score: (typeof score === 'number' ? score : 0),
            dictionary: (typeof dictionary === 'string' ? dictionary : null),
            value
        };
    }

    _createKanjiDefinition(character, dictionary, onyomi, kunyomi, glossary, tags, stats) {
        return {
            type: 'kanji',
            character,
            dictionary,
            onyomi,
            kunyomi,
            glossary,
            tags,
            stats,
            frequencies: []
        };
    }

    async _createTermDefinitionFromDatabaseDefinition(databaseDefinition, source, rawSource, sourceTerm, reasons, isPrimary, enabledDictionaryMap) {
        const {expression, reading: rawReading, definitionTags, termTags, glossary, score, dictionary, id, sequence} = databaseDefinition;
        const reading = (rawReading.length > 0 ? rawReading : expression);
        const dictionaryOrder = this._getDictionaryOrder(dictionary, enabledDictionaryMap);
        const termTagsExpanded = await this._expandTags(termTags, dictionary);
        const definitionTagsExpanded = await this._expandTags(definitionTags, dictionary);

        this._sortTags(definitionTagsExpanded);
        this._sortTags(termTagsExpanded);

        const termDetailsList = [this._createTermDetails(sourceTerm, expression, reading, termTagsExpanded)];
        const sourceTermExactMatchCount = (sourceTerm === expression ? 1 : 0);

        return {
            type: 'term',
            id,
            source,
            rawSource,
            sourceTerm,
            reasons,
            score,
            isPrimary,
            sequence,
            dictionary,
            dictionaryOrder,
            dictionaryNames: [dictionary],
            expression,
            reading,
            expressions: termDetailsList,
            glossary,
            definitionTags: definitionTagsExpanded,
            termTags: termTagsExpanded,
            // definitions
            frequencies: [],
            pitches: [],
            // only
            sourceTermExactMatchCount
        };
    }

    /**
     * Creates a grouped definition from an array of 'term' definitions.
     * @param definitions An array of 'term' definitions.
     * @returns A single 'termGrouped' definition.
     */
    _createGroupedTermDefinition(definitions) {
        const {reasons, source, rawSource, sourceTerm, expressions: [{expression, reading}]} = definitions[0];
        const score = this._getMaxDefinitionScore(definitions);
        const dictionaryOrder = this._getBestDictionaryOrder(definitions);
        const dictionaryNames = this._getUniqueDictionaryNames(definitions);
        const termTags = this._getUniqueTermTags(definitions);
        const termDetailsList = [this._createTermDetails(sourceTerm, expression, reading, termTags)];
        const sourceTermExactMatchCount = (sourceTerm === expression ? 1 : 0);
        return {
            type: 'termGrouped',
            // id
            source,
            rawSource,
            sourceTerm,
            reasons: [...reasons],
            score,
            // isPrimary
            // sequence
            dictionary: dictionaryNames[0],
            dictionaryOrder,
            dictionaryNames,
            expression,
            reading,
            expressions: termDetailsList,
            // glossary
            // definitionTags
            termTags,
            definitions, // type: 'term'
            frequencies: [],
            pitches: [],
            // only
            sourceTermExactMatchCount
        };
    }

    _createMergedTermDefinition(source, rawSource, definitions, expressions, readings, termDetailsList, reasons, score) {
        const dictionaryOrder = this._getBestDictionaryOrder(definitions);
        const sourceTermExactMatchCount = this._getSourceTermMatchCountSum(definitions);
        const dictionaryNames = this._getUniqueDictionaryNames(definitions);
        return {
            type: 'termMerged',
            // id
            source,
            rawSource,
            // sourceTerm
            reasons,
            score,
            // isPrimary
            // sequence
            dictionary: dictionaryNames[0],
            dictionaryOrder,
            dictionaryNames,
            expression: expressions,
            reading: readings,
            expressions: termDetailsList,
            // glossary
            // definitionTags
            // termTags
            definitions, // type: 'termMergedByGlossary'
            frequencies: [],
            pitches: [],
            // only
            sourceTermExactMatchCount
        };
    }

    _createMergedGlossaryTermDefinition(source, rawSource, definitions, expressions, readings, allExpressions, allReadings) {
        const only = [];
        if (!this._areSetsEqual(expressions, allExpressions)) {
            only.push(...this._getSetIntersection(expressions, allExpressions));
        }
        if (!this._areSetsEqual(readings, allReadings)) {
            only.push(...this._getSetIntersection(readings, allReadings));
        }

        const sourceTermExactMatchCount = this._getSourceTermMatchCountSum(definitions);
        const dictionaryNames = this._getUniqueDictionaryNames(definitions);

        const termDetailsList = this._createTermDetailsList(definitions);

        const definitionTags = this._getUniqueDefinitionTags(definitions);
        this._sortTags(definitionTags);

        const {glossary} = definitions[0];
        const score = this._getMaxDefinitionScore(definitions);
        const dictionaryOrder = this._getBestDictionaryOrder(definitions);
        return {
            type: 'termMergedByGlossary',
            // id
            source,
            rawSource,
            // sourceTerm
            reasons: [],
            score,
            // isPrimary
            // sequence
            dictionary: dictionaryNames[0],
            dictionaryOrder,
            dictionaryNames,
            expression: [...expressions],
            reading: [...readings],
            expressions: termDetailsList,
            glossary: [...glossary],
            definitionTags,
            // termTags
            definitions, // type: 'term'; contains duplicate data
            frequencies: [],
            pitches: [],
            only,
            sourceTermExactMatchCount
        };
    }

    /**
     * Creates a list of term details from an array of 'term' definitions.
     * @param definitions An array of 'term' definitions.
     * @returns An array of term details.
     */
    _createTermDetailsList(definitions) {
        const termInfoMap = new Map();
        for (const {expression, reading, sourceTerm, termTags} of definitions) {
            let readingMap = termInfoMap.get(expression);
            if (typeof readingMap === 'undefined') {
                readingMap = new Map();
                termInfoMap.set(expression, readingMap);
            }

            let termInfo = readingMap.get(reading);
            if (typeof termInfo === 'undefined') {
                termInfo = {
                    sourceTerm,
                    termTagsMap: new Map()
                };
                readingMap.set(reading, termInfo);
            }

            const {termTagsMap} = termInfo;
            for (const tag of termTags) {
                const {name} = tag;
                if (termTagsMap.has(name)) { continue; }
                termTagsMap.set(name, this._cloneTag(tag));
            }
        }

        const termDetailsList = [];
        for (const [expression, readingMap] of termInfoMap.entries()) {
            for (const [reading, {termTagsMap, sourceTerm}] of readingMap.entries()) {
                const termTags = [...termTagsMap.values()];
                this._sortTags(termTags);
                termDetailsList.push(this._createTermDetails(sourceTerm, expression, reading, termTags));
            }
        }
        return termDetailsList;
    }

    _createTermDetails(sourceTerm, expression, reading, termTags) {
        return {
            sourceTerm,
            expression,
            reading,
            termTags,
            frequencies: [],
            pitches: []
        };
    }

    // Sorting functions

    _sortTags(tags) {
        if (tags.length <= 1) { return; }
        const stringComparer = this._stringComparer;
        tags.sort((v1, v2) => {
            const i = v1.order - v2.order;
            if (i !== 0) { return i; }

            return stringComparer.compare(v1.name, v2.name);
        });
    }

    _sortDefinitions(definitions) {
        if (definitions.length <= 1) { return; }
        const stringComparer = this._stringComparer;
        const compareFunction = (v1, v2) => {
            // Sort by length of source term
            let i = v2.source.length - v1.source.length;
            if (i !== 0) { return i; }

            // Sort by the number of inflection reasons
            i = v1.reasons.length - v2.reasons.length;
            if (i !== 0) { return i; }

            // Sort by how many terms exactly match the source (e.g. for exact kana prioritization)
            i = v2.sourceTermExactMatchCount - v1.sourceTermExactMatchCount;
            if (i !== 0) { return i; }

            // Sort by dictionary priority
            i = v2.dictionaryOrder.priority - v1.dictionaryOrder.priority;
            if (i !== 0) { return i; }

            // Sort by term score
            i = v2.score - v1.score;
            if (i !== 0) { return i; }

            // Sort by expression string comparison (skip if either expression is not a string, e.g. array)
            const expression1 = v1.expression;
            const expression2 = v2.expression;
            if (typeof expression1 === 'string' && typeof expression2 === 'string') {
                i = expression2.length - expression1.length;
                if (i !== 0) { return i; }

                i = stringComparer.compare(expression1, expression2);
                if (i !== 0) { return i; }
            }

            // Sort by dictionary order
            i = v1.dictionaryOrder.index - v2.dictionaryOrder.index;
            return i;
        };
        definitions.sort(compareFunction);
    }

    _sortDatabaseDefinitionsByIndex(definitions) {
        if (definitions.length <= 1) { return; }
        definitions.sort((a, b) => a.index - b.index);
    }

    _sortDefinitionsById(definitions) {
        if (definitions.length <= 1) { return; }
        definitions.sort((a, b) => a.id - b.id);
    }

    _sortKanjiStats(stats) {
        if (stats.length <= 1) { return; }
        const stringComparer = this._stringComparer;
        stats.sort((v1, v2) => {
            const i = v1.order - v2.order;
            if (i !== 0) { return i; }

            return stringComparer.compare(v1.notes, v2.notes);
        });
    }

    _sortTermDefinitionMeta(definition) {
        const compareFunction = (v1, v2) => {
            // Sort by dictionary priority
            let i = v2.dictionaryOrder.priority - v1.dictionaryOrder.priority;
            if (i !== 0) { return i; }

            // Sory by expression order
            i = v1.expressionIndex - v2.expressionIndex;
            if (i !== 0) { return i; }

            // Sort by dictionary order
            i = v1.dictionaryOrder.index - v2.dictionaryOrder.index;
            if (i !== 0) { return i; }

            // Default order
            i = v1.index - v2.index;
            return i;
        };

        const {expressions, frequencies: frequencies1, pitches: pitches1} = definition;
        frequencies1.sort(compareFunction);
        pitches1.sort(compareFunction);
        for (const {frequencies: frequencies2, pitches: pitches2} of expressions) {
            frequencies2.sort(compareFunction);
            pitches2.sort(compareFunction);
        }
    }

    _sortKanjiDefinitionMeta(definition) {
        const compareFunction = (v1, v2) => {
            // Sort by dictionary priority
            let i = v2.dictionaryOrder.priority - v1.dictionaryOrder.priority;
            if (i !== 0) { return i; }

            // Sort by dictionary order
            i = v1.dictionaryOrder.index - v2.dictionaryOrder.index;
            if (i !== 0) { return i; }

            // Default order
            i = v1.index - v2.index;
            return i;
        };

        const {frequencies} = definition;
        frequencies.sort(compareFunction);
    }

    // Regex functions

    _applyTextReplacements(text, sourceMap, replacements) {
        for (const {pattern, replacement} of replacements) {
            text = RegexUtil.applyTextReplacement(text, sourceMap, pattern, replacement);
        }
        return text;
    }
}