-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
48 lines (42 loc) · 1.35 KB
/
app.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
function getAverageWordLength(tokens){
var totalLength = tokens.join("").length;
return (totalLength / tokens.length).toFixed(2);
}
function countDistinctWords(tokens) {
var distinctWords = [];
for (var i=0; i<tokens.length; i++) {
if(distinctWords.indexOf(tokens[i]) === -1) {
distinctWords.push(tokens[i]);
}
}
return distinctWords.length;
}
function tokenizeText(text) {
return text.toLowerCase().match(/\b[^\s]+\b/g).sort();
}
function removeReturns(text) {
return text.replace(/\r?n|\r/g, "");
}
function reportOnText(text) {
var tokens = tokenizeText(text);
var numDistinctWords = countDistinctWords(tokens);
var numTotalWords = tokens.length;
var averageWordLength = getAverageWordLength(tokens);
var textReport = $('.js-text-report');
textReport.find('.js-word-count').text(numTotalWords);
textReport.find('.js-unique-word-count').text(numDistinctWords);
textReport.find('.js-average-word-length').text(averageWordLength + " characters");
textReport.removeClass('hidden');
}
function watchFormSubmission() {
$('.js-text-form').submit(function(event) {
event.preventDefault();
// get the text the user submitted
var userText = $(this).find('#user-text').val();
reportOnText(removeReturns(userText));
});
}
// equivalent to `$(document).ready(function() {...})`
$(function() {
watchFormSubmission();
});