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
'๐ JavaScript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JS Tam9์ํ] #2 FE ์ํ๊ด๋ฆฌ (0) | 2021.07.16 |
---|---|
[JS Tam9์ํ] #1 DOM (0) | 2021.07.16 |
javascript ๊ณผ Promise ์ async await (0) | 2021.03.15 |
[Javascript] Prototype ์ ํตํ ์์ ๊ณผ __proto__ +(MDN ์์ ๋ก ๋ณด๋ Prototype ์์) (0) | 2021.03.12 |
[JavaScript ] prototype vs __proto__ + ๊ฐ์ฒด ์งํฅ ํ๋ก๊ทธ๋๋ฐ (0) | 2021.03.11 |
๋๊ธ