To implement the tables view, you need a database of words. Listing 29.20 provides a basic Node.js application that implements the words database used in this chapter. You need to run this before you can test the tables view defined in the previous sections. You need to modify the words
variable on line 3 to include the words you want in the database. The example on the book’s website includes about 5,000 words.
01 var vowelArr = "aeiou";
02 var consenantArr = "bcdfghjklmnpqrstvwxyz";
03 var words = "the,be,and,of,a,in ... ,middle-class,apology,till";
04 var wordArr = words.split(",");
05 var wordObjArr = new Array();
06 for (var i=0; i<wordArr.length; i++){
07 try{
08 var word = wordArr[i].toLowerCase();
09 var vowelCnt = ("|"+word+"|").split(/[aeiou]/i).length-1;
10 var consonantCnt =
11 ("|"+word+"|").split(/[bcdfghjklmnpqrstvwxyz]/i).length-1;
12 var letters = [];
13 var vowels = [];
14 var consonants = [];
15 var other = [];
16 for (var j=0; j<word.length; j++){
17 var ch = word[j];
18 if (letters.indexOf(ch) === -1){
19 letters.push(ch);
20 }
21 if (vowelArr.indexOf(ch) !== -1){
22 if(vowels.indexOf(ch) === -1){
23 vowels.push(ch);
24 }
25 }else if (consenantArr.indexOf(ch) !== -1){
26 if(consonants.indexOf(ch) === -1){
27 consonants.push(ch);
28 }
29 }else{
30 if(other.indexOf(ch) === -1){
31 other.push(ch);
32 }
33 }
34 }
35 var charsets = [];
36 if(consonants.length){
37 charsets.push({type:"consonants", chars:consonants});
38 }
39 if(vowels.length){
40 charsets.push({type:"vowels", chars:vowels});
41 }
42 if(other.length){
43 charsets.push({type:"other", chars:other});
44 }
45 var wordObj = {
46 word: word,
47 first: word[0],
48 last: word[word.length-1],
49 size: word.length,
50 letters: letters,
51 stats: { vowels: vowelCnt, consonants: consonantCnt },
52 charsets: charsets
53 };
54 if(other.length){
55 wordObj.otherChars = other;
56 }
57 wordObjArr.push(wordObj);
58 } catch (e){
59 console.log(e);
60 console.log(word);
61 }
62 }
63 var MongoClient = require('mongodb').MongoClient;
64 MongoClient.connect("mongodb://localhost/", function(err, db) {
65 var myDB = db.db("words");
66 myDB.dropCollection("words");
67 myDB.createCollection("words", function(err, wordCollection){
68 wordCollection.insert(wordObjArr, function(err, result){
69 console.log(result);
70 db.close();
71 });
72 });
73 });