๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“’ JavaScript

[JavaScript] Closure ๊ณผ Currying

by Tamii 2021. 4. 9.
๋ฐ˜์‘ํ˜•

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 

๋Œ“๊ธ€