repl.it
@ThomasS1/

Frequency Analysis

Nodejs

No description

fork
loading
Files
  • index.js
index.js
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
// Does the raw frequency analysis
function frequencyAnalysis(text, caseSensitive, alphabet, toAnalyse, n, ngramType) {

	result = {}

	// Makes all chars uppercase if not caseSensitive
	if (!caseSensitive) {
		text = text.toUpperCase()
		alphabet = alphabet.toUpperCase()
	}

	text = text.split('').filter(c => alphabet.indexOf(c) > -1).join("")

	if (toAnalyse == "chars") {

		for (i = 0; i < alphabet.length; i++) {
			char = alphabet[i]
			result[char] = [...text].filter(k => k === char).length;
		}

	} else {
		
		if (ngramType == "blocks") {
			increment = n;
		} else {
			increment = 1;
		}

		for (i = 0; i+n < text.length; i+=increment) {
			gram = text.slice(i, i+n);
			if (gram in result) {
				result[gram] += 1;
			} else {
				result[gram] = 1;
			}
		}

	}

	return result
}

//console.log(frequencyAnalysis("abcdabdaf", false, "ABCDEFGHIJKLMNOPQRSTUVWXYZ! ", "ngrams", 2, "sliding"))

console.log(frequencyAnalysis("heloawdasucjknlasdhaugyughbcabksjdugauwdyglwiufhoiwuegfdjamvcnspdfipqwdlhgjhaxvsxajkryguehrfpshjavxjnxkajgeydjhchgvwkjefgajsbhdjcsdjxhbjmnbxs", false, "abcdefgh", "ngrams", 2, "sliding"))

for (var key in result) {
	console.log(key + '  ' + result[key]); // Create a text node
}
?