2016年8月31日水曜日

開発環境

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

Exercises(Flattening)

コード(Emacs)

'use strict';
var a1 = [],
    a2 = [1],
    a3 = [1,2],
    a4 = [1,[2, 3]],
    a5 = [[1,2],3],
    a6 = [[1,2], [3,4]],
    a7 = [1, [2, [3, 4]], [5, 6]],
    flatten;

flatten = function (ary) {
    return ary.reduce(function (x, y) {
        if (y instanceof Array) {
            return x.concat(flatten(y));
        }
        return x.concat([y]);
    }, [])
};

[a1, a2, a3, a4, a5, a6, a7].forEach(function (a) {
    console.log(flatten(a));
});

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

$ node sample1.js
[]
[ 1 ]
[ 1, 2 ]
[ 1, 2, 3 ]
[ 1, 2, 3 ]
[ 1, 2, 3, 4 ]
[ 1, 2, 3, 4, 5, 6 ]
$

0 コメント:

コメントを投稿

Comments on Google+: