2016年9月5日月曜日

開発環境

Exercises for Programmers: 57 Challenges to Develop Your Coding Skills (Brian P. Hogan 著、Pragmatic Bookshelf)のChapter 5(Functions)、26(Months to Pay Off a Credit Card)を取り組んでみる。

26(Months to Pay Off a Credit Card)

コード(Emacs)

<label for="balance0">
  What is your balance?
</label>
<input id="balance0" type="number" min="0" step="1" value="5000">
<br>
<label for="apr0">
  What is the APR on the card (as a percent)?
</label>
<input id="apr0" type="number" min="0" value="12">
<br>
<label for="payment0">
  What is the monthly payment you can make?
</label>
<input id="payment0" type="number" min="0" value="100">
<br>
<br>
<div id="output0"></div>

<script src="sample26.js"></script>
(function () {
    'use strict';
    var input_balance = document.querySelector('#balance0'),
        input_apr = document.querySelector('#apr0'),
        input_payment = document.querySelector('#payment0'),
        inputs = [input_balance, input_apr, input_payment],
        div_output = document.querySelector('#output0'),
        calculateMonthsUntilPaidOff,
        output;

    calculateMonthsUntilPaidOff = function (balance, apr, payment) {
        var i = apr / 365,
            n;

        n = (-1 / 30) *
            Math.log(1 + (balance / payment) * (1 - Math.pow(1 + i, 30))) /
            Math.log(1 + i);

        return Math.ceil(n);
    };
    output = function () {
        var balance = parseFloat(input_balance.value),
            apr = parseFloat(input_apr.value) / 100,
            payment = parseFloat(input_payment.value),
            n = calculateMonthsUntilPaidOff(balance, apr, payment);

        div_output.innerText =
            'It will take you ' + n + ' months to pay off this card.';
    };

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

    output();
}());




0 コメント:

コメントを投稿