2016年9月17日土曜日

開発環境

Exercises for Programmers: 57 Challenges to Develop Your Coding Skills (Brian P. Hogan 著、Pragmatic Bookshelf)のChapter 7(Data Structures)、36(Computing Statistics)を取り組んでみる。

36(Computing Statistics)

コード(Emacs)

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

<script src="sample36.js"></script>
(function () {
    'use strict';
    var nums = [],
        div_inputs = document.querySelector('#inputs0'),
        div_output = document.querySelector('#output0'),
        nl = '<br>',
        getInputs,
        output,
        average;

    average = function (array) {
        return array.sum() / array.length;
    };
    Object.defineProperties(Array.prototype, {
        min: { get: function () { return Math.min.apply(null, this); }},
        max: { get: function () { return Math.max.apply(null, this); }},
        sum: {
            value: function () {
                return this.reduce(function (x, y) {
                    return x + y;
                }, 0);
            },
        },
        average: {
            value: function () {
                return average(this);
            },
        },
        mean: {
            value: function () {
                return average(this);
            },
        },
        variance: {
            value: function () {
                var mean = this.mean();

                return this.map(function (x) {
                    return Math.pow(x - mean, 2);
                }).sum() / this.length;
            },
        },
        standardDeviation: {
            value: function () {
                return Math.sqrt(this.variance());
            },
        },
    });
    getInputs = function (i) {
        var id = 'num' + i,
            input;
        
        div_inputs.innerHTML +=
            '<label for="' + id + '">Enter a number: </label>' +
            '<input id="' + id + '" type="text"><br>';

        input = document.querySelector('#' + id);
        input.focus();
        input.onchange = function () {
            var num = input.value;
            
            input.setAttribute('value', num);
            input.setAttribute('readOnly', true);
            input.onchange = null;
            if (num === 'done') {
                output();
            } else {
                nums.push(parseInt(num, 10));
                getInputs(i + 1);
            }
        };
    };
    output = function () {
        div_output.innerHTML =
            'Numbers: ' + nums.join(', ') + nl +
            'The average is ' + nums.mean() + '. ' + nl +
            'The minimum is ' + nums.min + '. ' + nl +
            'The maximum is ' + nums.max + '. ' + nl +
            'The standard deviation is ' + nums.standardDeviation() + '. ' + nl;
    };
    getInputs(0);
}());

0 コメント:

コメントを投稿

Comments on Google+: