[JS] Currying

Suyeon·2021년 2월 19일
0

Javascript

목록 보기
30/31
post-thumbnail

What is currying?

Currying is a technique of evaluating function with multiple arguments , into sequence of function with single argument. Currying helps you to avoid passing the same variable again and again. It helps to create a higher order function. It extremely helpful in event handling.

Currying은 여러개의 arguments를 가지는 함수를, 하나의 argument를 가진 여러개의 함수를 return함으로써 함수를 연쇄시키는 기법이다.

예제 1

(1) Function declaration

const add = function(a) {
  return function(b) {
    return a + b;
  }
};

const addOne = add(1);
addOne(2); // 3

아래와 같이 호출할 수도 있다.

add(1)(2) // 3

(2) Arrow Function

const add = a => b => a + b;
add(1)(2);

예제 2

아래와 같이 currying을 사용하면, argument의 중복 사용을 줄일 수 있다.

const greeting = a => b => a + ' ' + b;
const hello = greeting('Hello');
const morning = greeting('Good morning');

hello('Suyeon'); // Hello Suyeon
hello('Hanna'); // Hello Hanna
morning('Suyeon'); // Good morning Suyeon
morning('Hanna'); // Good morning Hanna

greeting('Hello')('Suyeon') 
greeting('Good morning')('Hanna') 

예제 3

아래의 예시는 함수형 프로그래밍으로, first class function과 함께 currying을 사용해서 중복을 제거한다.

// List
let NBAPlayers = [
  { 
    team: 'Golden State Warriors',
    name: 'Seth Curry',
    status: 'active',
    jersey: 30
  },
  { 
    team: 'Golden State Warriors',
    name: 'Kevin Durant',
    status: 'active',
    jersey: 35
  }
]

let MLBPlayers = [
  { 
    team: 'Chicago Cubs',
    name: 'Anthony Rizzo',
    status: 'active',
    jersey: 44
  },
  { 
    team: 'Chicago Cubs',
    name: 'Kris Bryant',
    status: 'active',
    jersey: 17
  }
];

// currying을 사용하지 않은 경우
const basketballPlayers = NBAPlayers.map(player => player.name);
const baseballPlayers = MLBPlayers.map(player => player.name);

// currying을 사용한 경우
const get = property => object => object[property];
const getPlayers = get('name');
const basketballPlayers = NBAPlayers.map(getPlayers);
const baseballPlayers = MLBPlayers.map(getPlayers);

const getActivePlayers = player => player.status === 'active';
const activeBasketballPlayers = NBAPlayers.filter(getActivePlayers);
const activeBaseballPlayers = MLBPlayers.filter(getActivePlayers);

// 위의 함수들을 함께 사용
const activeNBAplayers = NBAPlayers.filter(getActivePlayers).map(getPlayers);
const activeMLBplayers = MLBPlayers.filter(getActivePlayers).map(getPlayers);
profile
Hello World.

0개의 댓글