[JS] 함수형 기본

최정환·2021년 9월 13일
0

평가

  • 코드가 계산(Evaluation) 되어 값을 만드는 것
1	// 1
1 + 2	// 3 
[1, 2]	// [1, 2]
[1, 2+3]	// [1, 5]
[1,2, ...[3,4]]	// [1,2,3,4]

일급 함수

  • 값으로 다룰 수 있다.
  • 변수에 담을 수 있다.
  • 함수의 인자로 사용될 수 있다.
  • 함수의 결과로 사용될 수 있다.
  • 조합성과 추상화의 도구
const a = 10;
const add10 = a => a+10
const r = add10(a)
console.log(r)	// 20


const f1 => () = () => 1;
console.log((f1());	// () => 1
const f2 = f1();
console.log(f2);	// () => 1
console.log(f2());	// 1

고차 함수

  • 함수를 값으로 다루는 함수

함수를 인자로 받아 실행하는 함수

  • apply1, times
const apply1 = f => f(1);	// f라는 함수를 인자로 받아 사용함
const add2 = a => a+2;
console.log(apply1(add2));	// 3

const times = (f,n) => {
	let i = -1;
  	while(++i <n) f(i);
}

times(console.log, 3);	// 0 1 2
times(a=>console.log(a+10),3)	// 10 11 12

함수를 만들어 리턴하는 함수 (클로저를 만들어 리턴하는 함수)

  • addMaker
const addMaker = a => b => a+b;	// a를 기억하는 클로저이자 함수
const add10 = addMaker(10);	// a = 10
console.log(add10)	// b => a+b
console.log(add10(5));	// 15
console.log(add10(10));	// 20

0개의 댓글