2016年9月2日金曜日

開発環境

Eloquent JavaScript(Marijn Haverbeke 著、No Starch Press)のPart 1(Language)、Chapter 5(Higher-Order Functions)、Exercises(Historical Life Expectancy)を取り組んでみる。

Exercises(Historical Life Expectancy)

コード(Emacs)

'use strict';
var ancestry = JSON.parse(require('./ancestry')),
    by_century = {},
    centuries,
    average;

ancestry.forEach(function (person) {
    var century = Math.ceil(person.died / 100),
        age = person.died - person.born;

    if (by_century[century] === undefined) {
        by_century[century] = [age];
    } else {
        by_century[century].push(age);
    }
});

average = function (ary) {
    return ary.reduce(function (x, y) {
        return x + y;
    }, 0) / ary.length;
};

centuries = Object.keys(by_century);
centuries.sort(function (x, y) {
    return x- y;
});
centuries.forEach(function (century) {
    console.log('century: ' + century +
                ', average: ' + average(by_century[century]));
});

入出力結果(Terminal, Node.js)

$ node sample3.js 
century: 16, average: 43.5
century: 17, average: 51.2
century: 18, average: 52.78947368421053
century: 19, average: 54.833333333333336
century: 20, average: 84.66666666666667
century: 21, average: 94
$

0 コメント:

コメントを投稿

Comments on Google+: