I wrote this to be able to compare two different arrays to figure out how many words were in common as a percentage value.
The use case is that I have array a which is a list of the most commonly known and used words in a language (normally something like 2000 different words). In array b I have the text.
The end result is the percentage usage of commonly used words as a means to figure out total readability of the text.
Note: The intersect_array function is used elsewhere in the full fledged application.
The full functioning CodePen can be viewed here: http://codepen.io/MarkBuskbjerg/pen/rWWRbX?editors=0010
The JS goes like this:
tinymce.init({
selector: '#myTextArea',
height: 300,
setup: function(ed) {
ed.on('keyup', run);
},
init_instance_callback: "run"
});
// helper function that matches two arrays with each other
function intersect_arrays(a, b) {
var sorted_a = a.concat().sort();
var sorted_b = b.concat().sort();
var common = [];
var a_i = 0;
var b_i = 0;
while (a_i < a.length && b_i < b.length) {
if (sorted_a[a_i] === sorted_b[b_i]) {
common.push(sorted_a[a_i]);
a_i++;
b_i++;
} else if (sorted_a[a_i] < sorted_b[b_i]) {
a_i++;
} else {
b_i++;
}
}
return common;
}
// simple addition function
function add(a, b) {
return a + b;
}
function run(inst) {
var sum;
var percentageUsage;
var words = ["store", "javascript", "hammertime"];
var result = {};
var text = tinyMCE.get('myTextArea').getContent({
format: 'text'
})
.replace(/<([^>]+)>|[\.\+\?,\(\)"'\-\!\;\:]/ig, "")
.toLowerCase()
.split(/[\s]/)
.filter(Boolean);
var textLength = text.length;
var match = intersect_arrays(text, words);
for (var y = 0; y < match.length; y++) {
for (var i = 0; i < text.length; ++i) {
if(text[i] === match[y]) {
if (!result[text[i]])
result[text[i]] = 0;
++result[text[i]];
}
}
}
sum = Object
.values(result)
.reduce(add, 0);
percentageUsage = textLength / sum;
document.getElementById('totalWords').innerHTML = textLength;
document.getElementById('totalPercentage').innerHTML = percentageUsage;
}
Any ideas as to how I can handle the code more effective, easier or just in a more beautiful way is more than welcome. I'm quite new at JS so still wanna learn a lot about best practice and stuff.