2016年8月28日日曜日

開発環境

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

19(BMI Calculator)

コード(Emacs)

<label for="height0">
  Height(cm): 
</label>
<input id="height0" type="number" min="0" step="0.01" value="170">
<br>
<label for="weight0">
  Weight(kg): 
</label>
<input id="weight0" type="number" min="0" step="0.01" value="60">
<br>
<br>
<div id="output0"></div>

<script src="sample19.js"></script>
(function () {
    'use strict';
    var input_weight = document.querySelector('#weight0'),
        input_height = document.querySelector('#height0'),
        div_output = document.querySelector('#output0'),
        inputs = [input_weight, input_height],

        calcBmi,
        display;

    calcBmi = function (weight, height) {
        var h = height / 100;
        
        return (weight / (h * h)).toFixed(2);
    };

    display = function () {
        var weight = parseFloat(input_weight.value),
            height = parseFloat(input_height.value),
            bmi = calcBmi(weight, height),
            output = '';

        output += 'Your BMI is ' + bmi + '.<br>';
        if (bmi < 18.5) {
            output += 'You are underweight. You should see your doctor.<br>';
        } else if (bmi > 25) {
            output += 'You are overweight. You should see your doctor.<br>';
        } else {
            output += 'You are within the ideal weight range.<br>';
        }
        div_output.innerHTML = output;
    };

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



0 コメント:

コメントを投稿