2015年7月31日金曜日

開発環境

  • 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 1.(No. 4558)を解いてみる。

Exercises 1.(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,
    file_str = 'name1,12345\nname2,23456\nname3,34567\nname4,' +
    '45678\nname5,56789',
    names_and_phone_numbers,
    names,
    phone_numbers,
    i,
    max,
    d;

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];
        }
    },
};

names_and_phone_numbers = file_str.split('\n');
names = names_and_phone_numbers.map(function (name_and_phone_number) {
    return name_and_phone_number.split(',')[0];
});
phone_numbers = names_and_phone_numbers.map(function (name_and_phone_number) {
    return name_and_phone_number.split(',')[1];
});

d = new Dictionary();
for (i = 0, max = names.length; i < max; i += 1) {
    d.add(names[i], phone_numbers[i]);
}
d.showAll();
print(d.find('name2'));
d.remove('name2');
d.showAll();
d.add('name2', '00000');
d.showAll();
d.clear();
d.showAll();

出力結果(Terminal, shell, SpiderMonkey)

$ jslint sample1.js 

sample1.js is OK.
$ node sample1.js
name1 -> 12345
name2 -> 23456
name3 -> 34567
name4 -> 45678
name5 -> 56789
23456
name1 -> 12345
name3 -> 34567
name4 -> 45678
name5 -> 56789
name1 -> 12345
name2 -> 00000
name3 -> 34567
name4 -> 45678
name5 -> 56789
$

0 コメント:

コメントを投稿

Comments on Google+: