πŸ“’ JavaScript

[JavaScript] Closure κ³Ό Currying

Tamii 2021. 4. 9. 03:44
λ°˜μ‘ν˜•

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