2016年9月8日木曜日

開発環境

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

28(Adding Numbers)

コード(Emacs)

<label for="numbers0">
  How many numbers to add?:
</label>
<input id="numbers0" type="number" min="0" step="1" value="5">
<br>
<div id="inputs0"></div>
<div id="output0"></div>

<script src="array.js"></script>
<script src="sample28.js"></script>
(function () {
    'use strict';
    var input_numbers = document.querySelector('#numbers0'),
        div_output = document.querySelector('#output0'),
        div_inputs = document.querySelector('#inputs0'),

        createInputs,
        calc,
        output;

    createInputs = function () {
        var nums = parseInt(input_numbers.value, 10),
            inputs;

        inputs = range(nums).map(function (i) {
            var id = 'number' + i;
            
            return '<label for="' + id +'">' +
                'Enter a number: ' +
                '</label>' +
                '<input id="' + id + '" class="numbers0"' +
                'type="number" value="0">';
        }).join('<br>');

        div_inputs.innerHTML = inputs;
    };

    calc = function () {
        var class_numbers = document.querySelectorAll('.numbers0'),
            i,
            max,
            num,
            total = 0;

        for (i = 0, max = class_numbers.length; i < max; i += 1) {
            num = parseFloat(class_numbers[i].value);
            if (!isNaN(num)) {
                total += num;
            }
        }
        div_output.innerText = 'The total is ' + total + '.';
    };

    output = function () {
        var class_numbers,
            i,
            max;

        createInputs();
        calc();
        class_numbers = document.querySelectorAll('.numbers0');
        for (i = 0, max = class_numbers.length; i < max; i += 1) {
            class_numbers[i].onchange = calc;
        }    
    };

    input_numbers.onchange = output;

    output();
}());

0 コメント:

コメントを投稿

Comments on Google+: