2016年8月27日土曜日

開発環境

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

18(Temperature Converter)

コード(Emacs)

<input id="fahrenheit0" name="units0" type="radio" checked>
<label for="fahrenheit0">
  To convert from Fahrenheit to Celsius.
</label>
<br>
<input id="celsius0" name="units0" type="radio">
<label for="celsius0">
  To convert from Celsius to Fahrenheit.
</label>
<br>
<label for="temperature0">
  Please enter the temperature in <span id="unit0"></span>:
</label>
<input id="temperature0" type="number" value="32">
<br>

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

<script src="sample18.js"></script>
(function () {
    'use strict';
    var input_fahrenheit = document.querySelector('#fahrenheit0'),
        input_celsius = document.querySelector('#celsius0'),
        span_unit = document.querySelector('#unit0'),
        input_temperature = document.querySelector('#temperature0'),
        inputs = [input_fahrenheit, input_celsius, input_temperature],
        div_output = document.querySelector('#output0'),
        
        f2c,
        c2f,
        display;

    f2c = function (f) {
        return (f - 32) * 5 / 9;
    };
    c2f = function (c) {
        return c * 9 / 5 + 32;
    };
    display = function () {
        var temperature = parseFloat(input_temperature.value);

        if (input_fahrenheit.checked) {
            span_unit.innerText = 'Fahrenheit';
            div_output.innerText =
                'The temperature in Celius is ' + f2c(temperature) + '.';
        } else {
            span_unit.innerText = 'Celsius';
            div_output.innerText =
                'The temperature in Fahrenheit is ' + c2f(temperature) + '.';
        }    
    };

    inputs.forEach(function (input) {
        input.onkeyup = display;
        input.onchange = display;
    });
    display();
}());



0 コメント:

コメントを投稿