[JavaScript] Closure κ³Ό Currying
Closure
closure μ μ₯μ νμ©
κ°μ κ°μ§ ν¨μλ₯Ό λ§λ€ μ μμ
function sum(a,b) {
return a+b;
}
function calculate(fn, prev) {
return (v) =>{
return fn(prev,v);
}
const sum100 = calculate(sum, 100)
sum100(20); //120
β sum100
sum100 = (v) => {
return sum(100,v)
}
sum100μ΄λΌλ ν¨μλ μ΄λ»κ² 보면 100μ΄λΌλ κ°μ κ°μ§ ν¨μκ° λλ κ²μ΄λ€.
ν¬λ‘¬ λλ²κ±°μμ Scope(μ ν¨λ²μ) λ₯Ό νμΈν΄λ³΄λ©΄
Closure : { prev :100, fn: f }
Currying
κ°μ κ°μ§ ν¨μλ₯Ό λ§λ€ μ μλ ν¨μ ex) calculate ν¨μ
ν¨μν νλ‘κ·Έλλ°μ pipe λΌμΈμ λ§λ€μ΄ ν©μ±(composition)μ΄ κ°λ₯ν¨
λνμ μΈ ν¨μ : bind
React
λ©μλκ° ν¬ν¨λ κ°μ²΄λ₯Ό λ°ν
value= ν΄λ‘μ
useState λ λ³νλ₯Ό κ°μ§νλ ν¨μ
< Curry ν¨μ μμ >
볡μ‘ν Curry ν¨μ μμμΈλ° μ΄μ§μΈ λλ νλ²μ μ΄ν΄κ° μλμ λλ²κΉ νλ©° μκ² μͺΌκ°λ³΄μλ€.
let curry = (fn) => {
return function curryFn(...args1) {
if (args1.length >= fn.length) {
return fn(...args1);
} else {
return (...args2) => curryFn(...args1, ...args2);
}
}
}
function multiply(a, b, c){
return a * b * c;
}
let curriedMultiply = curry(multiply);
let result = curriedMultiply(2,3)(4);
1οΈβ£ μ²μ μ€ν
let curriedMultiply = curry(multiply);
curriedMiultiply(...args1) {
if (args1.length >= fn.length) {
return fn(...args1);
} else {
return (...args2) => curryFn(...args1, ...args2);
}
}
fn : multiply
args1: [2,3]
args1.length (2) < fn.length (3)
2οΈβ£ return μΌλ‘ curry μ€ν
return (...args2) => curryFn(...args1, ...args2);
curriedMultiply(2,3) = (...args2) => curryFn(...args1, ...args2);
fn : multiply
args1: [2,3]
args2: 4
3οΈβ£ μ λ΅
return fn(...args1);
multiply(2, 3, 4)
λ΅μ 24