2017年4月3日月曜日

開発環境

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 5(Fruitful subroutines)の Boolean functions の Exercise 5-3.を JavaScript で取り組んでみる。

Exercise 5-3.

コード(Emacs)

let input = document.querySelector('#input0'),
    div = document.querySelector('#output0'),
    run = document.querySelector('#run0'),

    first_l = (word) => {
        return word[0];
    },
    last_l = (word) => {
        return word[word.length - 1];
    },
    middle_l = (word) => {        
        if (word.length <= 1) {
            return false;
        }
        return word.substr(1, word.length - 2);
    };

run.onclick = () => {
    div.innerHTML =
        `1.<br>` +
        `${middle_l('ab')}<br>` +
        `${middle_l('')}<br>` +
        `${middle_l('"')}<br>`;

    div.innerHTML += '2.<br>';

    let isPalindrome = (word) => {
        return word.length <= 1 ? true:
            (first_l(word) === last_l(word)) && isPalindrome(middle_l(word));
    };

    [
        ['', true],
        ['a', true],
        ['aa', true],
        ['ab', false],
        ['abc', false],
        ['aba', true],
        ['abcdedcba', true],
        ['abcdeedcba', true]
    ].forEach((x) => {
         div.innerHTML += `${x[0]} ${isPalindrome(x[0])} ${x[1]}<br>`;
    });
    let word = input.value;
    div.innerHTML += `${word} ${isPalindrome(word)}<br>`;
};

0 コメント:

コメントを投稿