2016年8月29日月曜日

開発環境

Exercises for Programmers: 57 Challenges to Develop Your Coding Skills (Brian P. Hogan 著、Pragmatic Bookshelf)のChapter 4(Making Decisions)、20(Multistate Sales Tax Calculator)を取り組んでみる。

20(Multistate Sales Tax Calculator)

コード(Emacs)

<label for="amount0">
  What is the order amount?
</label>
<input id="amount0" type="number" min="0" step="0.01" value="10">
<br>
<label for="state0">What state do you live in? </label>
<select id="state0">
  <option>Wisconsin</option>
  <option>Illinois</option>
  <option>Other</option>
</select>
<br>
<label for="country0" class="countries0">What country do you live in? </label>
<select id="country0" class="countries0">
  <option>Eau Claire</option>
  <option>Dunn</option>
  <option>Other</option>
</select>

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

<script src="sample20.js"></script>
(function () {
    'use strict';
    var price = 10,
        input_amount = document.querySelector('#amount0'),
        select_state = document.querySelector('#state0'),
        select_country = document.querySelector('#country0'),
        elems = [input_amount, select_state, select_state],
        countries_class = document.querySelectorAll('.countries0'),
        div_output = document.querySelector('#output0'),
        country_hidden,
        display;

    country_hidden = function (bln) {
        var i,
            len = countries_class.length;

        for (i = 0; i < len; i += 1) {
            countries_class[i].hidden = bln;
        }
    };
    display = function () {
        var amount = parseFloat(input_amount.value),
            state = select_state.value,
            country,
            tax = 0,
            pre_total = price * amount,
            total;

        if (state === 'Wisconsin') {
            country_hidden(false);
            country = select_country.value;
            if (country === 'Eau Claire') {
                tax = pre_total * 0.005;            
            } else if (country === 'Dunn') {
                tax = pre_total * 0.0004;
            }
        } else if (state === 'Illinois') {
            country_hidden(true);
            tax = pre_total * 0.08;
        }
        total = pre_total + tax.toFixed(2);
        div_output.innerHTML =
            'The tax is $' + tax + '.<br>' +
            'The total is $' + total + '.<br>';
    };

    elems.forEach(function (elem) {
        elem.onchange = display;
    });

    display();
}());


0 コメント:

コメントを投稿