-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools.ts
More file actions
1033 lines (944 loc) · 32.8 KB
/
Copy pathtools.ts
File metadata and controls
1033 lines (944 loc) · 32.8 KB
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
import esrever from "esrever";
import "intl-segmenter-polyfill";
import {
type SentimentResult,
type ReadabilityResult,
type TextDiffResult,
type LanguageDetectionResult,
SentimentAnalyzer,
TextStatistics,
LanguageDetector,
TextDiff,
LexiconLoader,
KeywordExtractor,
} from "./extensions";
/**
* @description A TypeScript module providing text analysis functionalities through various operations like removing punctuations, numbers, alphabets, special characters, extracting URLs, and performing case transformations. It also includes functions for character and alphanumeric counting.
*/
/**
* @class ToolsConstant
* @summary A collection of regular expressions for different character patterns.
* @readonly
* @property {Object} regex - An object containing regex patterns.
* @property {RegExp} regex.alphabets - Matches all alphabetical characters (both uppercase and lowercase).
* @property {RegExp} regex.numbers - Matches all numeric digits (0-9).
* @property {RegExp} regex.punctuations - Matches common punctuation characters.
* @property {RegExp} regex.specialCharacters - Matches any special characters that are not alphanumeric or common punctuation.
* @property {RegExp} regex.urls - Matches URLs that start with "http" or "https".
* @property {RegExp} regex.newlines - Matches empty lines (newlines with only whitespace).
* @property {RegExp} regex.extraSpaces - Matches multiple consecutive spaces.
* @property {RegExp} regex.character - Matches whitespace characters.
*/
export class ToolsConstant {
static readonly regex = {
alphabets: /[a-zA-Z]/g,
numbers: /\d/g,
punctuations: /[!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~]/g, // Simplified syntax
specialCharacters: /[^a-zA-Z0-9\s!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~]/g,
urls: /https?:\/\/\S+/gi,
newlines: /^\s*$(?:\r\n?|\n)/gm,
extraSpaces: / +/g,
character: /[^\s\p{Cf}]/gu,
// Enhanced patterns
email: /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,
phoneNumber: /(?:\+\d{1,3}[-\s]?)?\(?\d{3}\)?[-\s]?\d{3}[-\s]?\d{4}/g,
hashtags: /#[a-zA-Z0-9_]+/g,
mentions: /(?<![a-zA-Z0-9.])@[a-zA-Z0-9_]+(?![a-zA-Z0-9_])/g,
};
}
/**
* @enum {string} Operations
* @description Enum representing various text analysis and manipulation operations. Each operation corresponds to a specific functionality within the `Analyser` class.
*/
export enum Operations {
RemovePunctuations = "removepunc",
RemoveNumbers = "removenum",
RemoveAlphabets = "removealpha",
RemoveSpecialChars = "removespecialchar",
RemoveNewlines = "newlineremover",
RemoveExtraSpaces = "extraspaceremover",
ExtractUrls = "extractUrls",
ExtractEmails = "extractEmails",
ExtractPhoneNumbers = "extractPhoneNumbers",
ExtractHashtags = "extractHashtags",
ExtractMentions = "extractMentions",
ConvertToUppercase = "fullcaps",
ConvertToLowercase = "lowercaps",
ConvertToTitleCase = "titlecase",
CountCharacters = "charcount",
CountAlphabets = "alphacount",
CountNumbers = "numcount",
CountAlphanumeric = "alphanumericcount",
CountWords = "wordcount",
CountSentences = "sentencecount",
ReverseText = "reversetext",
Truncate = "truncate",
ExtractKeywords = "extractKeywords",
AnalyzeSentiment = "analyzeSentiment",
CalculateReadability = "calculateReadability",
DetectLanguage = "detectLanguage",
CompareTexts = "compareTexts",
}
/** Types for Analyser options and built-in operations */
export type AnalyserBuiltInOptions = Partial<
Record<Operations | string, boolean | any>
>;
type BuiltInOptions = keyof typeof Operations;
/** Type for operation results */
export interface AnalyserResult {
purpose: string;
output: string;
metadata: {
counts: {
characterCount: number;
alphabetCount: number;
numericCount: number;
wordCount?: number;
sentenceCount?: number;
};
urls?: string[];
emails?: string[];
phoneNumbers?: string[];
hashtags?: string[];
mentions?: string[];
keywords?: string[];
readability?: ReadabilityResult;
sentiment?: SentimentResult;
languageDetection?: LanguageDetectionResult;
textComparison?: TextDiffResult;
custom?: {
[key: string]: any;
};
};
[key: string]: any;
operations: string[];
builtInOperations: string[];
customOperations: string[];
executionTime?: number;
}
/** Configuration type for Truncate operation */
export interface TruncateConfig {
maxLength: number;
suffix?: string;
}
/**
* @class Analyser
* @summary A class to analyze and manipulate strings based on user-provided options.
*/
export class Analyser {
public raw_text: string;
public output: string;
public count: number = 0;
public alphacount: number = 0;
public numericcount: number = 0;
public wordCount: number = 0;
public sentenceCount: number = 0;
// Enhanced extraction features
public urls: string[] = [];
public emails: string[] = [];
public phoneNumbers: string[] = [];
public hashtags: string[] = [];
public mentions: string[] = [];
public keywords: string[] = []; // Store TF-IDF keywords
private metadata: { [key: string]: { [key: string]: any } } = {};
private readability: ReadabilityResult | undefined;
private sentiment: SentimentResult | undefined;
private language: LanguageDetectionResult | undefined;
private langaugeOptions:
| {
whitelist?: string[] | undefined;
blacklist?: string[] | undefined;
minLength?: number | undefined;
}
| undefined;
private comparison: TextDiffResult | undefined;
public operations: string[] = [];
public customOperationsList: string[] = [];
public builtInOperationsList: string[] = [];
private executionStartTime: number = 0;
private executionEndTime: number = 0;
private customOperations: { [key: string]: () => Promise<void> } = {};
private builtInOptions: AnalyserBuiltInOptions = {};
// Extension instances
private sentimentAnalyzer: SentimentAnalyzer;
private keywordExtractor: KeywordExtractor;
private textStats: TextStatistics;
private languageDetector: LanguageDetector;
private textDiff: TextDiff;
/**
* @constructor
* @param {string} raw_text - The input text to process.
* @param {AnalyserBuiltInOptions} options - The options object defining operations to perform.
* @param {Object} languageOptions - Detection options
* @param {string[]} languageOptions.whitelist - Languages to consider (ISO 639-3 codes)
* @param {string[]} languageOptions.blacklist - Languages to ignore (ISO 639-3 codes)
* @param {number} languageOptions.minLength - Minimum text length for detection
* @throws {Error} If raw_text is not a string
*/
constructor(
raw_text: string,
options: AnalyserBuiltInOptions = {},
languageOptions?: {
whitelist?: string[];
blacklist?: string[];
minLength?: number;
},
) {
if (typeof raw_text !== "string") {
throw new Error("Input text must be a string");
}
this.raw_text = raw_text || ""; // Fallback to empty string if raw_text is empty
this.output = this.raw_text;
this.builtInOptions = options;
this.langaugeOptions = languageOptions;
// Initialize Extension Classes
this.sentimentAnalyzer = new SentimentAnalyzer();
this.keywordExtractor = new KeywordExtractor();
this.textStats = new TextStatistics();
this.languageDetector = new LanguageDetector();
this.textDiff = new TextDiff();
}
/**
* @static
* @async
* @function create
* @summary Static Factory Method to initialize the Analyser with dynamic resources.
* @description Ensures Lexicons and IDF maps are loaded before analysis begins[cite: 76, 79].
* @param {string} raw_text - The input text.
* @param {AnalyserBuiltInOptions} options - Configuration options.
* @param {Object} languageOptions - Detection options
* @param {string[]} languageOptions.whitelist - Languages to consider (ISO 639-3 codes)
* @param {string[]} languageOptions.blacklist - Languages to ignore (ISO 639-3 codes)
* @param {number} languageOptions.minLength - Minimum text length for detection
*
*/
public static async create(
raw_text: string,
options: AnalyserBuiltInOptions = {},
langaugeOptions?:
| {
whitelist?: string[] | undefined;
blacklist?: string[] | undefined;
minLength?: number | undefined;
}
| undefined,
): Promise<Analyser> {
// Parallel loading of dynamic resources (Stopwords, IDF maps) [cite: 88, 174]
await Promise.all([
LexiconLoader.loadStopWords(),
LexiconLoader.loadStandardIDF(),
]);
return new Analyser(raw_text, options, langaugeOptions);
}
/** @summary Get all available operations */
public get availableOperations(): Record<string, string> {
const customOps = Object.keys(this.customOperations).reduce(
(acc, key) => ({ ...acc, [key]: key }),
{},
);
return {
...Operations,
...customOps,
};
}
/** @summary Get current options */
public get options(): AnalyserBuiltInOptions {
return this.builtInOptions;
}
/** @summary Set new options */
public set options(newOptions: AnalyserBuiltInOptions) {
this.builtInOptions = { ...this.builtInOptions, ...newOptions };
}
/**
* @description Operation handlers mapping
* @private
*/
private get operationHandlers(): Record<string, () => Promise<void>> {
return {
[Operations.RemovePunctuations]: this.removePunctuations.bind(this),
[Operations.RemoveNumbers]: this.removeNumbers.bind(this),
[Operations.RemoveAlphabets]: this.removeAlphabets.bind(this),
[Operations.RemoveSpecialChars]: this.removeSpecialCharacters.bind(this),
[Operations.RemoveNewlines]: this.newLineRemover.bind(this),
[Operations.RemoveExtraSpaces]: this.extraSpaceRemover.bind(this),
[Operations.ExtractUrls]: this.extractURL.bind(this),
[Operations.ExtractEmails]: this.extractEmails.bind(this),
[Operations.ExtractPhoneNumbers]: this.extractPhoneNumbers.bind(this),
[Operations.ExtractHashtags]: this.extractHashtags.bind(this),
[Operations.ExtractMentions]: this.extractMentions.bind(this),
[Operations.ConvertToUppercase]: this.toFullUppercase.bind(this),
[Operations.ConvertToLowercase]: this.toFullLowercase.bind(this),
[Operations.ConvertToTitleCase]: this.toTitleCase.bind(this),
[Operations.CountCharacters]: this.countCharacters.bind(this),
[Operations.CountAlphabets]: this.countAlphas.bind(this),
[Operations.CountNumbers]: this.countNums.bind(this),
[Operations.CountAlphanumeric]: this.countAlphaNumeric.bind(this),
[Operations.CountWords]: this.countWords.bind(this),
[Operations.CountSentences]: this.countSentences.bind(this),
[Operations.ReverseText]: this.reverseText.bind(this),
[Operations.Truncate]: this.truncateText.bind(this),
[Operations.ExtractKeywords]: this.extractKeywords.bind(this),
[Operations.AnalyzeSentiment]: this.analyzeSentiment.bind(this),
[Operations.CalculateReadability]: this.calculateReadability.bind(this),
[Operations.DetectLanguage]: this.detectLanguage.bind(this),
[Operations.CompareTexts]: this.compareTexts.bind(this),
...this.customOperations,
};
}
/**
* @private
* @async
* @function removeAlphabets
* @summary Removes all alphabetic characters from the input text.
*/
private async removeAlphabets(): Promise<void> {
this.output = this.output.replace(ToolsConstant.regex.alphabets, "");
this.logOperation("Removed Alphabets");
}
/**
* @private
* @async
* @function removeNumbers
* @summary Removes all numeric characters from the input text.
*/
private async removeNumbers(): Promise<void> {
this.output = this.output.replace(ToolsConstant.regex.numbers, "");
this.logOperation("Removed Numbers");
}
/**
* @private
* @async
* @function removePunctuations
* @summary Removes all punctuation characters from the input text.
*/
private async removePunctuations(): Promise<void> {
this.output = this.output.replace(ToolsConstant.regex.punctuations, "");
this.logOperation("Removed Punctuations");
}
/**
* @private
* @async
* @function removeSpecialCharacters
* @summary Removes all special characters from the input text.
*/
private async removeSpecialCharacters(): Promise<void> {
this.output = this.output.replace(
ToolsConstant.regex.specialCharacters,
"",
);
this.logOperation("Removed Special Characters");
}
/**
* @private
* @async
* @function extraSpaceRemover
* @summary Removes extra spaces and trims the input text.
*/
private async extraSpaceRemover(): Promise<void> {
this.output = this.output
.replace(ToolsConstant.regex.extraSpaces, " ")
.trim();
this.logOperation("Removed Extra Spaces");
}
/**
* @private
* @async
* @function newLineRemover
* @summary Removes newline characters from the input text.
C * @description Collapses multiple consecutive blank lines into a single blank line, removes leading/trailing blank lines, while preserving single newlines for readability.
*/
private async newLineRemover(): Promise<void> {
this.output = this.output.replace(ToolsConstant.regex.newlines, "\n").trim();
// Clean up any double spaces created by replacing newlines
this.output = this.output.replace(/ +/g, " ");
this.logOperation("Removed New Line Characters");
}
/**
* @private
* @async
* @function extractURL
* @summary Extracts all URLs from the input text.
*/
private async extractURL(): Promise<void> {
this.urls = this.raw_text.match(ToolsConstant.regex.urls) || [];
this.logOperation("Extracted URLs");
}
/**
* @private
* @async
* @function extractEmails
* @summary Extracts all email addresses from the input text.
*/
private async extractEmails(): Promise<void> {
this.emails = this.raw_text.match(ToolsConstant.regex.email) || [];
this.logOperation("Extracted Emails");
}
/**
* @private
* @async
* @function extractPhoneNumbers
* @summary Extracts all phone numbers from the input text.
*/
private async extractPhoneNumbers(): Promise<void> {
this.phoneNumbers =
this.raw_text.match(ToolsConstant.regex.phoneNumber) || [];
this.logOperation("Extracted Phone Numbers");
}
/**
* @private
* @async
* @function extractHashtags
* @summary Extracts all hashtags from the input text.
*/
private async extractHashtags(): Promise<void> {
this.hashtags = this.raw_text.match(ToolsConstant.regex.hashtags) || [];
this.logOperation("Extracted Hashtags");
}
/**
* @private
* @async
* @function extractMentions
* @summary Extracts all mentions from the input text.
*/
private async extractMentions(): Promise<void> {
this.mentions = this.raw_text.match(ToolsConstant.regex.mentions) || [];
this.logOperation("Extracted Mentions");
}
/**
* @private
* @async
* @function toFullUppercase
* @summary Converts all characters in the input text to uppercase.
*/
private async toFullUppercase(): Promise<void> {
this.output = this.output.toUpperCase();
this.logOperation("Changed to Uppercase");
}
/**
* @private
* @async
* @function toFullLowercase
* @summary Converts all characters in the input text to lowercase.
*/
private async toFullLowercase(): Promise<void> {
this.output = this.output.toLowerCase();
this.logOperation("Changed to Lowercase");
}
/**
* @private
* @async
* @function toTitleCase
* @summary Converts the input text to title case (first letter of each word capitalized).
*/
private async toTitleCase(): Promise<void> {
this.output = this.output.replace(/\w\S*/g, (txt) => {
return txt.charAt(0).toUpperCase() + txt.substring(1).toLowerCase();
});
this.logOperation("Changed to Title Case");
}
/**
* @private
* @async
* @function countCharacters
* @summary Counts the number of non-whitespace characters in the input text.
*/
private async countCharacters(): Promise<void> {
this.count = (
this.raw_text.match(ToolsConstant.regex.character) ?? []
).length;
this.logOperation("Counted Characters");
}
/**
* @private
* @async
* @function countAlphas
* @summary Counts the number of alphabets in the input text.
*/
private async countAlphas(): Promise<void> {
this.alphacount = (
this.raw_text.match(ToolsConstant.regex.alphabets) || []
).length;
this.logOperation("Counted Alphabets");
}
/**
* @private
* @async
* @function countNums
* @summary Counts the number of numeric characters in the input text.
*/
private async countNums(): Promise<void> {
this.numericcount = (
this.raw_text.match(ToolsConstant.regex.numbers) || []
).length;
this.logOperation("Counted Numbers");
}
/**
* @private
* @async
* @function countAlphaNumeric
* @summary Counts the number of alphabetic and numeric characters in the input text.
*/
private async countAlphaNumeric(): Promise<void> {
this.alphacount = (
this.raw_text.match(ToolsConstant.regex.alphabets) || []
).length;
this.numericcount = (
this.raw_text.match(ToolsConstant.regex.numbers) || []
).length;
this.logOperation("Counted Alphabets and Numbers");
}
/**
* @private
* @async
* @function countWords
* @summary Counts the number of words in the input text.
*/
private async countWords(): Promise<void> {
// Count words by splitting on whitespace and filtering out empty strings
const words = this.raw_text
.trim()
.split(/\s+/)
.filter((word) => word.length > 0);
this.wordCount = words.length;
this.logOperation("Counted Words");
}
/**
* @private
* @async
* @function countSentences
* @summary Counts the number of sentences in the input text.
*/
private async countSentences(): Promise<void> {
const trimmed = this.raw_text.trim();
if (!trimmed) {
this.sentenceCount = 0;
this.logOperation("Counted Sentences");
return;
}
// Check for Intl.Segmenter support (Node 16+ / Modern Browsers)
if (typeof Intl !== "undefined" && Intl.Segmenter) {
const segmenter = new Intl.Segmenter("en", {
granularity: "sentence",
});
const segments = segmenter.segment(trimmed);
let count = 0;
for (const _ of segments) {
count++;
}
this.sentenceCount = count;
} else {
// robust fallback if Intl.Segmenter is not available
// Matches sentences ending in . ! ? but ignores common abbreviations (Mr. Dr. etc)
const output = trimmed.replace(/([.?!])\s*(?=[A-Z])/g, "$1|");
this.sentenceCount = output.split("|").length;
}
this.logOperation("Counted Sentences");
}
/**
* @private
* @async
* @function reverseText
* @summary Reverses the input text.
*/
private async reverseText(): Promise<void> {
this.output = esrever.reverse(this.output);
this.logOperation("Reversed Text");
}
/**
* @private
* @async
* @function truncateText
* @summary Truncates the input text to a specified length.
*/
private async truncateText(): Promise<void> {
const config = this.builtInOptions[Operations.Truncate] as TruncateConfig;
if (!config || typeof config !== "object" || !config.maxLength) {
throw new Error(
"Truncate operation requires a valid configuration with maxLength",
);
}
const { maxLength, suffix = "..." } = config;
if (this.output.length <= maxLength) {
return; // No truncation needed
}
this.output = this.output.substring(0, maxLength) + suffix;
this.logOperation(`Truncated Text to ${maxLength} characters`);
}
/**
* @private
* @async
* @function extractKeywords
* @summary Extracts keywords using TF-IDF logic.
* @description Moves beyond counting to semantic analysis[cite: 161].
*/
private async extractKeywords(): Promise<void> {
// Default to top 5 keywords, or use user config
const options = this.builtInOptions[Operations.ExtractKeywords];
const topN = typeof options === "object" && options.topN ? options.topN : 5;
this.keywords = this.keywordExtractor.extractKeywords(this.raw_text, topN);
this.logOperation(`Extracted Top ${topN} Keywords (TF-IDF)`);
}
/**
* @private
* @async
* @function analyzeSentiment
* @summary Analyzes the sentiment of the input text.
*/
private async analyzeSentiment(): Promise<void> {
const result = this.sentimentAnalyzer.analyze(this.raw_text);
this.sentiment = result;
this.logOperation("Analysed Sentiment");
}
/**
* @private
* @async
* @function calculateReadability
* @summary Calculates readability metrics including Flesch-Kincaid and SMOG.
* @description Implements advanced morphological metrics[cite: 139].
*/
private async calculateReadability(): Promise<void> {
const result = this.textStats.fleschKincaidReadability(this.raw_text);
this.readability = result;
this.logOperation("Calculated readability Metrics (Flesch-Kincaid & SMOG)");
}
/**
* @private
* @async
* @function detectLanguage
* @summary Detects language using n-gram profiles.
*/
private async detectLanguage(): Promise<void> {
const detectionResult = this.languageDetector.detect(
this.raw_text,
this.langaugeOptions,
);
this.language = detectionResult;
this.logOperation(`Detected Language: ${detectionResult.detectedLanguage}`);
}
/**
* @private
* @async
* @function compareTexts
* @summary Compares two texts using basic diff logic.
*/
private async compareTexts(): Promise<void> {
const compareOptions = this.builtInOptions[Operations.CompareTexts];
if (
!compareOptions ||
typeof compareOptions !== "object" ||
!("compareWith" in compareOptions)
) {
throw new Error("CompareTexts operation requires a 'compareWith' text");
}
const compareWith = compareOptions.compareWith as string;
const comparisonResult = this.textDiff.compare(this.raw_text, compareWith);
this.comparison = comparisonResult;
this.logOperation(
`Compared Texts (${comparisonResult.similarity.toFixed(2)}% similarity)`,
);
}
/**
* @function addCustomOperation
* @summary Adds a custom text operation to the analyser dynamically.
* @param {string} commandName - The name of the custom operation to be registered.
* @param {string} logName - The logging name of the custom operation to be registered.
* @param {Object} config - Configuration object for the custom operation.
* @param {(text: string) => string} config.operation - A function that performs the custom operation on the text.
* @param {boolean} [config.isEnabled=false] - Whether to enable the operation immediately.
* @param {Object} [config.metadata] - Optional metadata to be added to the result.
* @param {(text: string) => any} [config.metadataExtractor] - Optional function to extract additional metadata.
*
* @returns {Promise<void>} Resolves when the custom operation is successfully added.
* @throws {Error} If the commandName already exists or if parameters are invalid.
*/
public async addCustomOperation(
commandName: string,
logName: string,
config: {
operation: (text: string) => string;
isEnabled?: boolean;
metadata?: { [key: string]: any };
metadataExtractor?: (text: string) => any;
},
): Promise<void> {
if (!commandName || typeof commandName !== "string")
throw new Error("Command name must be a non-empty string");
if (!logName || typeof logName !== "string")
throw new Error("Log name must be a non-empty string");
if (typeof config.operation !== "function")
throw new Error("Operation must be a function");
if (
Operations[commandName as BuiltInOptions] ||
this.customOperations[commandName]
) {
throw new Error(`Operation "${commandName}" already exists`);
}
this.customOperations[commandName] = async () => {
try {
const originalText = this.raw_text;
this.output = config.operation(this.output);
this.logOperation(`${logName}`, true);
// Initialize custom metadata object if it doesn't exist
if (!this.metadata.custom) {
this.metadata.custom = {};
}
// Initialize this operation's metadata object if it doesn't exist
if (!this.metadata.custom[commandName]) {
this.metadata.custom[commandName] = {};
}
// Merge static metadata if provided
if (config.metadata) {
this.metadata.custom[commandName] = {
...this.metadata.custom[commandName],
...config.metadata,
};
}
// Extract and merge dynamic metadata if extractor provided
if (config.metadataExtractor) {
const extractedMetadata = config.metadataExtractor(originalText);
this.metadata.custom[commandName] = {
...this.metadata.custom[commandName],
...extractedMetadata,
};
}
} catch (error) {
this.logOperation(
`Error in Custom Operation: ${logName} - ${error}`,
true,
);
throw error;
}
};
this.builtInOptions[commandName] = config.isEnabled ?? false;
}
/**
* @function toggleOperation
* @summary Toggles an operation on or off.
* @param {string} commandName - The name of the operation to toggle.
* @param {boolean} isEnabled - Whether to enable the operation.
* @returns {Promise<void>} Resolves when the operation is successfully toggled.
* @throws {Error} If the operation does not exist or is already in the requested state.
*/
public async toggleOperation(
commandName: string,
isEnabled: boolean,
): Promise<void> {
if (
!(commandName in this.builtInOptions) &&
!(commandName in Operations) &&
!(commandName in this.customOperations)
) {
throw new Error(
`Operation "${commandName}" not found. Please add it first.`,
);
}
if (this.builtInOptions[commandName] === isEnabled) return;
this.builtInOptions[commandName] = isEnabled;
}
/**
* @function enableAllOperations
* @summary Enables all available operations.
* @returns {Promise<void>} Resolves when all operations are enabled.
*/
public async enableAllOperations(): Promise<void> {
// Enable all built-in operations
for (const operation in Operations) {
if (isNaN(Number(operation))) {
// Set both the enum name (key) and the enum value
this.builtInOptions[operation] = true;
this.builtInOptions[Operations[operation as BuiltInOptions]] = true;
}
}
// Enable all custom operations
for (const operation in this.customOperations) {
this.builtInOptions[operation] = true;
}
}
/**
* @function disableAllOperations
* @summary Disables all operations.
* @returns {Promise<void>} Resolves when all operations are disabled.
*/
public async disableAllOperations(): Promise<void> {
// Disable all built-in operations
for (const operation in Operations) {
if (isNaN(Number(operation))) {
// Set both the enum name (key) and the enum value
this.builtInOptions[operation] = false;
this.builtInOptions[Operations[operation as BuiltInOptions]] = false;
}
}
// Disable all custom operations
for (const operation in this.customOperations) {
this.builtInOptions[operation] = false;
}
}
/**
* @function resetText
* @summary Resets the text to the original value or a new value.
* @param {string} [newText] - Optional new text to set.
* @returns {Promise<void>} Resolves when the text is reset.
*/
public async resetText(newText?: string): Promise<void> {
if (newText !== undefined) {
if (typeof newText !== "string") {
throw new Error("New text must be a string");
}
this.output = newText;
}
// Reset all counters and extracted data
this.count = 0;
this.alphacount = 0;
this.numericcount = 0;
this.wordCount = 0;
this.sentenceCount = 0;
this.urls = [];
this.emails = [];
this.phoneNumbers = [];
this.hashtags = [];
this.keywords = [];
this.mentions = [];
// Reset operations log
this.operations = [];
this.logOperation("Text Reset");
}
/**
* @private
* @function logOperation
* @summary Logs the performed operation.
* @param {string} operation - The operation performed on the text.
* @param {string} isCustom - Whether the operation is a custom function.
*/
private logOperation(operation: string, isCustom: boolean = false): void {
this.operations.push(operation);
if (isCustom) {
this.customOperationsList.push(operation);
} else {
this.builtInOperationsList.push(operation);
}
}
/**
* @private
* @async
* @function getResults
* @summary Retrieves the results of the operations performed on the text.
* @returns {Promise<AnalyserResult>} An object containing the results of the analysis.
*/
private async getResults(): Promise<AnalyserResult> {
const executionTime = this.executionEndTime - this.executionStartTime;
const result: AnalyserResult = {
purpose: this.operations.join(","),
output: this.output,
operations: [...this.operations],
builtInOperations: [...this.builtInOperationsList],
customOperations: [...this.customOperationsList],
executionTime,
metadata: {
counts: {
characterCount: this.count,
alphabetCount: this.alphacount,
numericCount: this.numericcount,
wordCount: this.wordCount,
sentenceCount: this.sentenceCount,
},
urls: this.urls,
emails: this.emails,
phoneNumbers: this.phoneNumbers,
hashtags: this.hashtags,
mentions: this.mentions,
keywords: this.keywords,
readability: this.readability,
sentiment: this.sentiment,
languageDetection: this.language,
textComparison: this.comparison,
custom: { ...this.metadata.custom },
},
};
return result;
}
/**
* @async
* @function main
* @summary Executes the text analysis operations based on the provided options.
* @returns {Promise<AnalyserResult>} An object containing the analysis results.
* @throws {Error} If an operation fails.
*/
public async main(): Promise<AnalyserResult> {
this.executionStartTime = performance.now();
try {
for (const [operation, enabled] of Object.entries(this.builtInOptions)) {
if (enabled) {
// First check if it's a custom operation
const customHandler = this.customOperations[operation];
if (customHandler) {
await customHandler();
continue;
}
// Otherwise, check for built-in operation handler
const handler = this.operationHandlers[operation];
if (handler) {
await handler();
} else {
console.warn(`No handler found for operation: ${operation}`);
}
}
}
} catch (error) {
this.logOperation(
`Error: ${error instanceof Error ? error.message : String(error)}`,
);
throw error;
} finally {
this.executionEndTime = performance.now();
}
return this.getResults();
}
/**
* @static
* @function createWithEnabledOperations
* @summary Factory method to create an Analyser instance with specific operations enabled.
* @param {string} text - The text to analyze.
* @param {(keyof typeof Operations)[]} operations - The operations to enable.
* @returns {Analyser} A new Analyser instance with the specified operations enabled.
*/
public static createWithEnabledOperations(
text: string,
operations: (keyof typeof Operations)[],
): Analyser {
const options: AnalyserBuiltInOptions = {};
for (const operation of operations) {
if (Operations[operation]) {
options[Operations[operation]] = true;
}
}
return new Analyser(text, options);
}