사용 예시 1
1 2 3 4 5 6 7 8
| <Field name="username" onChange={handleChange('username')} /> <Field name="password" onChange={handleChange('password')} />
|
함수 본문 1
1 2 3
| const handleChange = (fieldName) => (value) => { fields[fieldName].value = value; };
|
함수 본문 1 해설
함수 handleChange
는 fieldName
를 받아 새로운 함수를 반환한다. 반환한 함수에 value
를 전달하는 경우, fields
객체에서 fieldName
에 해당하는 프로퍼티에 value
를 전달받은 value
로 갱신한다.
사용 예시 2
1 2 3 4 5 6
| const createForm = createElHtml('form'); const createInput = createElHtml('input');
const form = createForm(); const idInput = createInput('name="username"'); form.innerHTML = idInput;
|
함수 본문 2
1 2 3 4
| const createElHtml = (tag) => ( arrtibutes = '', children = '', ) => `<${tag} ${arrtibutes}>${children}</${tag}>`;
|
사용 예시 3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| const toBoolean = (x) => !!x; const double = (n) => n * 2; const toNumber = (str) => Number.parseInt(str, 10); const composedFunction = compose( toBoolean, double, toNumber, );
composedFunction('0'); composedFunction(''); composedFunction(); composedFunction('hello'); composedFunction('2');
|
함수 본문 3
1 2 3 4
| const compose = (...functions) => [...functions].reduce((f, g) => (...args) => f(g(...args)), );
|
함수 본문 3 해설
compose(f,g,h)(1)
=> f(g(h(1)))
의 형태로 실행한다.
- compose 내부에선
functions
를 배열에 넣어 reduce
를 호출한다. Array.reduce
는 (result, currentvalue) => result;
이다. reduce에게 (f, g) => (...args) => f(g(...args))
를 인자로 넘겨준다.
- 단계별 흐름도
(f, g) => (...args) => f(g(...args)) // f, g
((...args) => f(g(...args)), h) => ((...args) => f(g(h(...args)))) // f,g 합성함수, h 함수
함수형 프로그래밍과의 연관성
currying
은 함수
를 인자로 받게 만들 수도 있고, 함수가 아닌 값
을 받게 만들 수도 있다. 두 방법 모두 유용하다.
- currying은 마지막으로 반환되는 경우를 제외하면 대부분 계속해서 함수를 반환한다. 이는 함수간의 조합이 쉽다.
참고
JavaScript ES6 curry functions with practical examples (EN)
Learning Javascript Courses: ES6 Curry (EN)
What is the advantage of currying? (EN)