この解答例はChatGPTによって生成されています,正しいかは自己判断で。
BFE.devでのAI解答例 - JavaScript コーディング問題
11. Compositionとは?pipe()を実装する
Compositionとは、小さな関数を組み合わせて大きな関数を作るプログラミングテクニックです。これにより、コードの再利用性と可読性が向上します。
以下はpipe()
関数の実装例です。
const pipe = (funcs) => {
return funcs.reduce((fn1, fn2) => {
return (...args) => {
return fn2(fn1(...args))
}
})
}
この関数では、与えられた関数の配列をreduce()
メソッドで反復処理し、関数を連鎖的に呼び出します。各関数は前の関数の出力を受け取り、その出力を入力として次の関数を呼び出します。
たとえば、以下のように使用できます。
const times = (y) => (x) => x * y
const plus = (y) => (x) => x + y
const subtract = (y) => (x) => x - y
const divide = (y) => (x) => x / y
const func1 = pipe([times(2), times(3)])
const func2 = pipe([times(2), plus(3), times(4)])
const func3 = pipe([times(2), subtract(3), divide(4)])
console.log(func1(5)) // 30
console.log(func2(5)) // 38
console.log(func3(5)) // 0.25
それぞれのpipe()
関数により新しい関数が生成され、それぞれの結果が出力されます。pipe()
関数により、簡潔で再利用可能な関数を作成できるようになります。