The implementation of the dictionary
// 字典类function Dictionary () { this.add = add; this.dataStore = new Array(); this.find = find; this.remove = remove; this.showAll = showAll; this.count = count; this.clear = clear;}function add (key, value) { this.dataStore[key] = value;}function find (key) { return this.dataStore[key];}function remove (key) { delete this.dataStore[key];}function showAll () { let datakeys = Array.prototype.slice.call(Object.keys(this.dataStore)); for (let key in datakeys.sort()) { console.log(`${datakeys[key]} -> ${this.dataStore[datakeys[key]]}`); }}// 计数function count () { let n = 0; for (let key in Object.keys(this.dataStore)) { ++n; } return n;}// 清空function clear () { Object.keys(this.dataStore).forEach((key) => { delete this.dataStore[key]; }, this);}
Practice using the Dictionary class to write a program that stores the number of occurrences of each word in a piece of text. The program displays the number of occurrences of each word, but each word is displayed only once. For example, in the following paragraph, "The Brown Fox jumped over the blue Fox", the output of the program should be:
- The:2
- Brown:1
- Fox:2
- Jumped:1
- Over:1
- Blue:1
function showWordCount (word) { let d = new Dictionary(); let words = word.split(' '); for (let i = 0, max = words.length; i < max; ++i) { // 首次出现 if (typeof d.find(words[i]) === 'undefined') { d.add(words[i], 1); } else { ++d.dataStore[words[i]]; } } Object.keys(d.dataStore).forEach((key) => { console.log(`${key}: ${d.find(key)}`); }, this);}// 示例showWordCount('the brown fox jumped over the blue fox');
JavaScript data structures and algorithms-dictionary exercises