2016年9月9日金曜日

開発環境

Exercises for Programmers: 57 Challenges to Develop Your Coding Skills (Brian P. Hogan 著、Pragmatic Bookshelf)のChapter 6(Repetition)、29(Handling Bad Input)を取り組んでみる。

29(Handling Bad Input)

コード(Emacs)

<div id="input0"></div>
<div id="output0"></div>

<button id="start0">start</button>
<script src="array.js"></script>
<script src="sample29.js"></script>
(function () {
    'use strict';
    var div_output = document.querySelector('#output0'),
        div_input = document.querySelector('#input0'),
        button_start = document.querySelector('#start0'),
        input,
        createInput,
        getInput,
        invalid = "Sorry. That's not a valid input.<br>",
        isValid,
        validate,
        calc;

    createInput = function (i) {
        return '<label for="rate"' + i + '">' +
            'What is the rate of return? ' +
            '</label>' +
            '<input id="rate' + i + '"><br>';
    };
    getInput = function (i) {
        var id = 'rate' + i,
            input_rate = document.querySelector('#' + id);

        return input_rate.value;
    };
    isValid = function (r) {
        return !isNaN(r) && typeof r === 'number' && r !== 0;
    };
    calc = function (r) {
        return 72 / r;
    };
    validate = function (i) {
        var num = getInput(i),
            r = parseFloat(num),
            years;

        if (isValid(r)) {
            years = calc(r);
            div_output.innerText = 'It will take ' + years +
                ' years to double your initial investment';
            button_start.focus();
        } else {
            input.setAttribute('value', num);
            input.readOnly = true;
            i += 1;
            div_input.innerHTML += invalid + createInput(i);
            input = document.querySelector('#rate' + i);
            input.focus();
            input.onchange = function () {
                validate(i);
            };
        }
    };
    div_input.innerHTML = createInput(0);
    input = document.querySelector('#rate0');
    input.focus();
    input.onchange = function () {
        validate(0);
    };
    button_start.onclick = function () {
        div_output.innerHTML = '';
        div_input.innerHTML = createInput(0);
        input = document.querySelector('#rate0');
        input.focus();
        input.onchange = function () {
            validate(0);
        };
    };
}());

0 コメント:

コメントを投稿

Comments on Google+: