2016年9月1日木曜日

開発環境

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

Exercises(Mother-Child Age Difference)

コード(Emacs)

'use strict';
var ancestry = JSON.parse(require('./ancestry')),
    by_name = {},
    children = [],
    diffs = [],
    average;

ancestry.forEach(function (person) {
    by_name[person.name] = person;
});

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

ancestry.forEach(function (person) {
    var mother = by_name[person.mother];
    
    if (mother !== undefined) {
        diffs.push(person.born - mother.born);
    }
});

console.log(average(diffs));

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

$ node sample2.js
31.22222222222222
$

0 コメント:

コメントを投稿