同僚からのコードレビューで学んだ。
カリー化
TODO
カリー化 + map関数
まずはwarming up。
const arr = [1,2,3]
const increment = (x:number) => x + 1
arr.map((e) => increment(e))
// [ 2, 3, 4 ]
arr.map(increment)
// [ 2, 3, 4 ]
本番。
const arr = [1,2,3]
const increment = (x:number, gap: number) => x + gap
arr.map((e) => increment(e, 10))
// [ 11, 12, 13 ]
これをカリー化すると、
const arr = [1,2,3]
const incrementCurry = (gap: number) => (x: number) => x + gap
arr.map(increment_curry(10))
// [ 11, 12, 13 ]
明示的に型を別定義してみると、
const arr = [1,2,3]
type IncrementCurryType = (gap: number) => (x: number) => number
const incrementCurry: IncrementCurryType
= (gap: number) => (x: number) => x + gap
arr.map(increment_curry(10))
// [ 11, 12, 13 ]
要は、arr.map((e) => increment(e, 10))
が、arr.map(increment_curry(10))
に書き換えられた。
まとめ
カリー化とは、f(g(x))
(関数の二重呼び出し) を F(x)(y) // Fは関数を返す関数
(関数の2回呼び出し)に書き換えることだという認識。(3回以上の場合もある。)
今回は、これをmap関数と組み合わせた。