2017年4月14日金曜日

開発環境

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)の Boolean functions の Exercises 7-1.を JavaScript で取り組んでみる。

Exercises 7-1.

コード(Emacs)

HTML5

<input id="word0" type="text" value="banana">
<input id="letter0" type="text" value="a">
<br>
<button id="run0">run</button>
<button id="clear0">clear</button>
<pre id="output0"></pre>

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

JavaScript

let input0 = document.querySelector('#word0'),
    input1 = document.querySelector('#letter0'),
    btn0 = document.querySelector('#run0'),
    btn1 = document.querySelector('#clear0'),
    pre0 = document.querySelector('#output0'),
    p = (x) => pre0.textContent += x + '\n';

let counter1 = (word, letter) => {
    let count = 0;
    let start = 0;
    for (;;) {
        let i = word.indexOf(letter, start);
        if (i !== -1) {
            count += 1;
            start = i + 1;
        } else {
            break;
        }
    }
    return count;
};

let counter2 = (word, letter) => {
    let count = 0;
    for (let i = 0; i < word.length; i += 1) {
        if (word.substring(i, i + 1) === letter) {
            count += 1;
        }
    }
    return count;
};

let output = () => {
    let word = input0.value,
        letter = input1.value;

    p(counter1(word, letter));
    p(counter2(word, letter));
};
    

btn0.onclick = output;
btn1.onclick = () => {
    pre0.textContent = '';
};

output();














						

0 コメント:

コメントを投稿