2015年7月8日水曜日

開発環境

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

Exercises 2.(No. 3595)

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  : false
*/

/*global print */
var Queue = function () {
        this.data_store = [];
    },
    Deque = function () {
        this.data_store = [];
    },
    isPalindrom = function (word) {
        var deque = new Deque(),
            i,
            max;

        for (i = 0, max = word.length; i < max; i += 1) {
            deque.addLast(word[i]);
        }
        i = 0;
        while (!deque.isEmpty()) {
            if (deque.removeLast() !== word[i]) {
                return false;
            }
            i += 1;
        }
        return true;
    },
    words = ['hello', 'racecar'],
    i,
    max;

Queue.prototype.enqueue = function (element) {
    this.data_store.push(element);
};
Queue.prototype.dequeue = function () {
    return this.data_store.shift();
};
Queue.prototype.front = function () {
    return this.data_store[0];
};
Queue.prototype.back = function () {
    return this.data_store[this.data_store.length - 1];
};
Queue.prototype.toString = function () {
    var result = '',
        i,
        max;
    for (i = 0, max = this.data_store.length; i < max - 1; i += 1) {
        result += this.data_store[i] + ',';
    }
    result += this.data_store[i];
    return result;
};
Queue.prototype.isEmpty = function () {
    return this.data_store.length === 0 ? true : false;
};
Queue.prototype.count = function () {
    return this.data_store.length;
};

Deque.prototype = new Queue();
Deque.constructor = Deque;
Deque.prototype.addFirst = function (element) {
    this.data_store.unshift(element);
};
Deque.prototype.addLast = function (element) {
    this.enqueue(element);
};
Deque.prototype.removeFirst = function () {
    return this.dequeue();
};
Deque.prototype.removeLast = function () {
    return this.data_store.pop();
};
Deque.prototype.getFirst = function () {
    return this.front();
};
Deque.prototype.getLast = function () {
    return this.back();
};

for (i = 0, max = words.length; i < max; i += 1) {
    if (isPalindrom(words[i])) {
        print(words[i] + ' is a palindrome.');
    } else {
        print(words[i] + ' is not a palindrome.');
    }
}

出力結果(Terminal, shell, SpiderMonkey)

$ jslint sample2.js

sample2.js is OK.
$ js sample2.js
hello is not a palindrome.
racecar is a palindrome.
$ 

0 コメント:

コメントを投稿

Comments on Google+: