함수를 부분 실행하는 currying 개념

사용 예시 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 해설

함수 handleChangefieldName를 받아 새로운 함수를 반환한다. 반환한 함수에 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,
); // toNumber -> double -> toBoolean 순으로 실행된다.
// 매개변수는 composedFunction에 전달된 것부터
// 각 함수의 반환값이 다음 함수의 매개변수가 된다.

composedFunction('0'); // false
composedFunction(''); // false
composedFunction(); // false
composedFunction('hello'); // false
composedFunction('2'); // true

함수 본문 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 함수

함수형 프로그래밍과의 연관성

  1. currying함수를 인자로 받게 만들 수도 있고, 함수가 아닌 값을 받게 만들 수도 있다. 두 방법 모두 유용하다.
  2. currying은 마지막으로 반환되는 경우를 제외하면 대부분 계속해서 함수를 반환한다. 이는 함수간의 조합이 쉽다.

참고

  1. JavaScript ES6 curry functions with practical examples (EN)

  2. Learning Javascript Courses: ES6 Curry (EN)

  3. What is the advantage of currying? (EN)

함수를 부분 실행하는 currying 개념

https://jsqna.com/fjs-2-currying/

Author

Seongbin Kim

Posted on

19-09-03

Updated on

21-01-19

Licensed under

댓글