2017年5月5日金曜日

開発環境

Think Perl 6: How to Think Like a Computer Scientist (Laurent Rosenfeld(著)、Allen B. Downey(著)、Oreilly & Associates Inc)の Part 1(Starting with the basics)、Chapter 7(Strings)、Debugging の Exercise: is-reverse Subroutine.を JavaScript で取り組んでみる。

Exercise: is-reverse Subroutine.

コード(Emacs)

HTML5

<pre id="output0"></pre>
<label for="word1">word1: </label>
<input id="word1" type="text">
<label for="word2">word2: </label>
<input id="word2" type="text">

<button id="run0">run</button>
<button id="clear0">clear</button>

<script src="sample_rev.js"></script>

JavaScript

let btn0 = document.querySelector('#run0'),
    btn1 = document.querySelector('#clear0'),
    pre0 = document.querySelector('#output0'),
    input_word1 = document.querySelector('#word1'),
    input_word2 = document.querySelector('#word2'),
    inputs = [input_word1, input_word2],
    p = (x) => pre0.textContent += x + '\n';

let isReverse = (word1, word2) => {
    if (word1.length !== word2.length) {
        return false;
    }
    let i = 0,
        j = word2.length - 1;

    for (; j >= 0;) {
        p(`i = ${i}, j = ${j}`);
        if (word1.substring(i, i + 1) === word2.substring(j, j + 1)) {
            i += 1;
            j -= 1;
        } else {
            return false;
        }
    }
    return true;
};

let output = () => {
    let word1 = input_word1.value,
        word2 = input_word2.value;

    p(isReverse('', ''));
    p(!isReverse('', 'a'));
    p(!isReverse('a', ''));
    p(isReverse('a', 'a'));
    p(!isReverse('ab', 'a'));
    p(isReverse('ab', 'ba'));
    p(isReverse('abcde', 'edcba'));

    p(!isReverse('日本語', 'abc'));
    p(isReverse('日本語', '語本日'));
    p(isReverse(word1, word2));
};

inputs.forEach((input) => input.onchange = output);
btn0.onclick = output;
btn1.onclick = () => pre0.textContent = '';

output();


















						

0 コメント:

コメントを投稿

Comments on Google+: