2017年7月16日日曜日

開発環境

Head First Python (Paul Barry (著)、O'Reilly Media)のChapter 3.(Structured Data: Working with Structured Data)、Iterating Over a Dictionary with "items" の FREQUENCY COUNT MAGNETS(No. 2256) を JavaScript で取り組んでみる。

FREQUENCY COUNT MAGNETS(No. 2256)

コード(Emacs)

HTML5

<pre id="output0"></pre>
<label for="word0">word: </label>
<input id="word0" type="text" value="JavaScript">
<button id="run0">run</button>
<button id="clear0">clear</button>

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

JavaScript

let pre0 = document.querySelector('#output0'),
    btn0 = document.querySelector('#run0'),
    btn1 = document.querySelector('#clear0'),
    input0 = document.querySelector('#word0'),
    inputs = [input0],
    range = (start, end, step=1) => {
        let res = [];

        for (let i = start; i < end; i += step) {
            res.push(i);
        }
        return res;
    },
    p = (x) => pre0.textContent += x + '\n';

let vowels = ['a', 'e', 'i', 'o', 'u'];

let output = () => {
    let word = input0.value,
        found = {};

    vowels.forEach((letter) => found[letter] = 0);

    word.split('').forEach((letter) => {
        if (vowels.indexOf(letter) !== -1) {
            found[letter] += 1;
        }
    });
    p(word);
    Object.entries(found)
        .sort(([x, x0], [y, y0]) =>  x < y ? -1 : x === y ? 0 : 1)
        .forEach(([k, v]) => p(`${k} was found ${v} time(s).`));
};

let clear = () => pre0.textContent = '';

btn0.onclick = output;
btn1.onclick = clear;
inputs.forEach((input) => input.onchange = output);

output();
















						

0 コメント:

コメントを投稿