JavaScript data structures and algorithms-dictionary exercises

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.