2017年5月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 7(Strings)、Looping and Counting の Exercise: Counting the Letters of a String.を JavaScript で取り組んでみる。

Exercise: Counting the Letters of a String.

コード(Emacs)

HTML5

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

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

JavaScript

let btn0 = document.querySelector('#run0'),
    btn1 = document.querySelector('#clear0'),
    pre0 = document.querySelector('#output0'),
    input_word = document.querySelector('#word0'),
    input_letter = document.querySelector('#letter0'),
    inputs = [input_word, input_letter],
    p = (x) => pre0.textContent += x + '\n',
    range = (start, end, step=1) => {
        let result = [];
        for (let i = start; i < end; i += step) {
            result.push(i);
        }
        return result;
    };

let count = (word, letter) => word.split('').filter((l) => l === letter).length;
let output = () => {
    let word = input_word.value,
        letter = input_letter.value;    
    p(
        ['', 'a', 'A', 'banana', '日本語', '日本語a']
            .map((word) => `count('${word}', 'a') => ${count(word, 'a')}`)
            .join('\n')
    );
    p(`count('${word}', '${letter}') => ${count(word, letter)}`);
};

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

output();















						

0 コメント:

コメントを投稿