2015年8月1日土曜日

開発環境

  • OS X Yosemite - Apple (OS)
  • Emacs (Text Editor)
  • JavaScript (プログラミング言語)
  • SpiderMonkey, Node.js(V8) (JavaScript engine)

Data Structures and Algorithms With Javascript (Michael McMillan(著)、O'Reilly Media)のChapter 7(Dictionaries)、Exercises 2.(No. 4558)を解いてみる。

Exercises 2.(No. 4558)

JavaScript(Emacs)

/*jslint         browser : true, continue : true,
  devel  : true, indent  : 4,    maxerr   : 50,
  newcap : true, nomen   : true, plusplus : false,
  regexp : true, sloppy  : true, vars     : false,
  white  : true
*/

/*global */
var Dictionary = function () {
        this.datastore = {};
    },
    print = console.log,
    text = 'the brown fox jumped over the blue fox,',
    d,
    i,
    max,
    words,
    word,
    number;

Dictionary.prototype = {
    constructor: Dictionary,
    add: function (key, value) {
        this.datastore[key] = value;
    },
    find: function (key) {
        return this.datastore[key];
    },
    remove: function (key) {
        delete this.datastore[key];
    },
    showAll: function () {
        var keys = Object.keys(this.datastore),
            i,
            max,
            key;

        keys.sort();
        for (i = 0, max = keys.length; i < max; i += 1) {
            key = keys[i];
            console.log(key + ' -> ' + this.datastore[key]);
        }
    },
    count: function () {
        return Object.keys(this.datastore).length;
    },
    clear: function () {
        var keys = Object.keys(this.datastore),
            i,
            max,
            key;
        for (i = 0, max = keys.length; i < max ; i += 1) {
            key = keys[i];
            delete this.datastore[key];
        }
    },
};

d = new Dictionary();
words = text.split(/\b/);
for (i = 0, max = words.length; i < max; i += 1) {
    word = words[i];
    if (word.match(/[a-zA-Z]+/)) {
        number = d.find(word);
        if (number !== undefined) {
            d.add(word, number + 1);
        } else {
            d.add(word, 1);
        }
    }
}
d.showAll();

出力結果(Terminal, shell, SpiderMonkey)

$ jslint sample2.js

sample2.js is OK.
$ node sample2.js
blue -> 1
brown -> 1
fox -> 2
jumped -> 1
over -> 1
the -> 2
$ 

0 コメント:

コメントを投稿