2016年9月3日土曜日

開発環境

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

Exercises(Every and Then some)

コード(Emacs)

'use strict';
var a = [],
    b = [1],
    c = [2],
    d = [1 ,2, 3, 4, 5],
    e = [1, 3, 5, 7, 9],
    f = [2, 4, 6, 8, 10],
    arys = [a, b, c, d, e, f],
    every,
    some,
    even,
    odd;

every = function (ary, func) {
    var i,
        max;

    for (i = 0, max = ary.length; i < max; i += 1) {
        if (!func(ary[i])) {
            return false;
        }
    }
    return true;
};
some = function (ary, func) {
    var i,
        max;

    for (i = 0, max = ary.length; i < max; i += 1) {
        if (func(ary[i])) {
            return true;
        }
    }
    return false;
};
even = function (x) {
    return x % 2 === 0;
};
odd = function (x) {
    return x % 2 === 1;
};
arys.forEach(function (ary) {
    console.log(ary);
    [every, some].forEach(function (f) {
        [even, odd].forEach(function (g) {
            console.log(f(ary, g));
        });
    });
});

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

$ node sample4.js
[]
true
true
false
false
[ 1 ]
false
true
false
true
[ 2 ]
true
false
true
false
[ 1, 2, 3, 4, 5 ]
false
false
true
true
[ 1, 3, 5, 7, 9 ]
false
true
false
true
[ 2, 4, 6, 8, 10 ]
true
false
true
false
$

0 コメント:

コメントを投稿

Comments on Google+: