2017年5月22日月曜日

開発環境

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 11(Case Study: Data Structure Selection)の Exercise: The given … when switch statement.を JavaScript で取り組んでみる。

Exercise: The given … when switch statement.

コード(Emacs)

HTML5

<pre id="output0"></pre>
<label for="value0">value = </label>
<input id="value0" type="number" min="0" step="1" value="10">

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

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

JavaScript

let btn0 = document.querySelector('#run0'),
    btn1 = document.querySelector('#clear0'),
    pre0 = document.querySelector('#output0'),
    input_value = document.querySelector('#value0'),
    inputs = [input_value],
    p = (x) => pre0.textContent += x + '\n',
    range = (start, end, step=1) => {
        let result = [];

        for (let i = start; i < end; i += 1) {
            result.push(i);
        }
        return result;
    };


let output = () => {
    let nums = [7, 42, 43, 100],
        value = parseInt(input_value.value, 10);

    nums.push(value);
    
    nums.forEach((value) => {
        p(value);
        if (range(0, 10).indexOf(value) !== -1) {
            p('One digit');
        } else {
            if (range(10, 100).indexOf(value) !== -1) {
                p('Two digits');
            }
            if (42 === value) {
                p('Thre response to the ultimate question');
            } else if(/^\d{3}$/.test(value)) {
                p('Three digits');
            } else {
                p('More than three digits');
            }
        }
    });
    p('ANSWER');
    nums.forEach((value) => {
        p(value);
        if (range(0, 10).indexOf(value) !== -1) {
            p('One digit');
        } else if (range(10, 100).indexOf(value) !== -1) {
            p('Two digits');
            if (42 === value) {
                p('Thre response to the ultimate question');
            }
        } else if(/^\d{3}$/.test(value)) {
            p('Three digits');
        } else {
            p('More than three digits');
        }
    });
};

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

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

output();
















						

0 コメント:

コメントを投稿