計算機科学のブログ

Building Abstractions with Functions - The Elements of Programming - Conditional Expressions and Predicates - conditional expressions

Structure and Interpretation of Computer Programs: JavaScript Edition(Harold Abelson(著)、Gerald Jay Sussman(著)、Julie Sussman(著)、The MIT Press)のChapter 1(Building Abstractions with Functions)、1.1(The Elements of Programming)、1.1.6(Conditional Expressions and Predicates)、Exercise 1.3の解答を求めてみる。

コード

function sum_of_squares_of_larger_numbers(x, y, z) {
    return x > z && y > z ?
        x ** 2 + y ** 2 :
        x > y ?
            x ** 2 + z ** 2 :
            y ** 2 + z ** 2;
}

const nums_array = [
    [2, 3, 4],
    [2, 4, 3],
    [3, 2, 4],
    [3, 4, 2],
    [4, 2, 3],
    [4, 3, 2]
];

for (const nums of nums_array) {
    console.log(sum_of_squares_of_larger_numbers(...nums));
}

入出力結果(Terminal, Zsh)

% node answer1.3.js
25
25
25
25
25
25
%