상세 컨텐츠

본문 제목

코드카데미 Javascript - 고차함수와 콜백함수

IT/Javascript

by J KIMS 2020. 9. 24. 16:07

본문

반응형

Functions as Data

- 자바스크립트에서는 함수를 다른 변수에 저장하는 것이 가능하다

- 자바스크립트에서 함수는 first class object이다

💡 first class object의 개념

: 다른 객체들 처럼 함수도 속성(properties)메서드를 가짐

e.g. arguments, length, name

 

const checkThatTwoPlusTwoEqualsFourAMillionTimes = () => {
  for(let i = 1; i <= 1000000; i++) {
    if ( (2 + 2) != 4) {
      console.log('Something has gone very wrong :( ');
    }
  }
}

// Write your code below
const is2p2 = checkThatTwoPlusTwoEqualsFourAMillionTimes;
is2p2();
console.log(is2p2.name);

 

checkThatTwoPlusTwoEqualsFourAMillionTimes라는 아주 긴 이름의 함수가 있다.

이럴 때는 이름이 간단한 변수에 저장해서 쓰면 편리하다.

만약 원래 함수의 이름을 확인해보고 싶다면 name 프로퍼티를 출력해보면 된다.

 

 


Functions as Parameters

 

- higher-order function(고차함수)는 다른 함수를 파라미터로 받거나 리턴할 수 있는 함수이다

- 파라미터로 전달되거나 호출되는 함수를 콜백 함수(callback function)이라고 부른다. 왜냐하면 고차 함수가 실행되는 동안 called 되기 때문이다.

- 다른 함수에 함수를 전달할 때는 괄호 없이 이름만 적음

 

When we pass a function in as an argument to another function, we don’t invoke it. Invoking the function would evaluate to the return value of that function call. With callbacks, we pass in the function itself by typing the function name without the parentheses (that would evaluate to the result of calling the function):

 

이 부분 무슨 말인지 잘 모르겠네..

 

- 또 다음과 같이 익명 함수(anonymous function)을 다른 함수에 전달하는 것도 가능

 

const timeFuncRuntime = funcParameter => {
   let t1 = Date.now();
   funcParameter();
   let t2 = Date.now();
   return t2 - t1;
}

timeFuncRuntime(() => {
  for (let i = 10; i>0; i--){
    console.log(i);
  }
});

 

아래는 고차함수와 콜백함수를 이용한 코드

 

const checkThatTwoPlusTwoEqualsFourAMillionTimes = () => {
  for(let i = 1; i <= 1000000; i++) {
    if ( (2 + 2) != 4) {
      console.log('Something has gone very wrong :( ');
    }
  }
};

const addTwo = num => num + 2;

const timeFuncRuntime = funcParameter => {
  let t1 = Date.now();
  funcParameter();
  let t2 = Date.now();
  return t2 - t1;
};

// Write your code below

const time2p2 = timeFuncRuntime(checkThatTwoPlusTwoEqualsFourAMillionTimes);

const checkConsistentOutput = (func, val) => {
  let firstTry = func(val);
  let secondTry = func(val);
  if (firstTry === secondTry){
    return firstTry;
  } else {
    return 'This function returned inconsistent results';
  }

} 

checkConsistentOutput(addTwo, 2);




 

1. check어쩌구로 시작되는 긴 함수를 timeFuncRuntime이라는 함수에 인수로 전달하고 그걸 또 time2p2라는 변수에 저장함. 인수로 전달된 함수가 바로 콜백함수인데 이런 방식은 실행되는 시간을 줄여줌. 

 

2. checkConsistentOutput은 함수와 값 하나를 파라미터로 가짐. 함수가 제대로 같은 결과를 리턴하는지 테스트하는 함수를 만든 것.

 

반응형

관련글 더보기

댓글 영역