2017年8月23日水曜日

開発環境

Head First Python (Paul Barry (著)、O'Reilly Media)のChapter 13.(Advanced Iteration: Looping Like Crazy)の SHARPEN YOUR PENCIL(No. 9296) を JavaScript で取り組んでみる。

SHARPEN YOUR PENCIL(No. 9296)

コード(Emacs)

HTML5

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

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

JavaScript

let pre0 = document.querySelector('#output0'),
    btn0 = document.querySelector('#run0'),
    btn1 = document.querySelector('#clear0'),
    inputs = [],
    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 data1 = range(1, 10),
    data2 = [1, 'one', 2, 'two', 3, 'three', 4, 'four'],
    data3 = 'So long and thanks for all the fish'.split(/\s+/);

let output = () => {
    p('1.')
    let evens = data1.filter((num) => num % 2 === 0);
    
    p(evens);

    p('2.')
    let words = data2.filter((num) => typeof num === 'string');
    
    p(words);

    p('3.')
    let title = data3
        .map((word) => word[0].toUpperCase() + word.slice(1).toLowerCase());
    
    p(title);
};

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

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

output();














						

0 コメント:

コメントを投稿