0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptで任意の数の関数を合成

Posted at

概要

任意の数の関数を合成した、新しい関数を返す関数を定義する方法を紹介します。
名前は、compose_all_funcsと仮に決めます。
このcompose_all_funcsは、任意の数の関数を引数に取ります。
compose_all_funcsの戻り値も関数です。
戻り値の関数では、引数valueが与えられたときに、
このvalueに、compose_all_funcsの引数の複数個の関数を、
最初(左側)から適用していった、最終結果を返します。

定義

// 引数は任意の数の関数
function compose_all_funcs(...fs){
    // 戻り値の関数
    return function(value){
        // 返す値の初期値は引数の値そのもの
        let result = value;
        for(let idx = 0; idx < fs.length; idx++){
            // 関数を左側から順番に適用
            result = fs[idx](result);
        }
        // 最終結果を返す
        return result;
    }
}

実行例

// 数値を2倍にして、数値に3を足して、最後に文字列結合として!を末尾に付加する関数を作成
const composed_function = compose_all_funcs(v => v * 2, v => v + 3, v => v + "!");
console.log(composed_function(100));

結果

203!
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?