JavaScript Higher-Order Functions

김서하·2021년 4월 7일
0

JavaScript

목록 보기
8/11
<데이터로서의 함수>
const announceThatIAmDoingImportantWork = () => {
    console.log("I’m doing very important 
    work!");
}; 함수 이름 바꾸려면
const busy = announceThatIAmDoingImportantWork;
 
busy(); // This function call barely takes any space!
다른 예
const checkThatTwoPlusTwoEqualsFourAMillionTimes = () => {
  for(let i = 1; i <= 1000000; i++) {
    if ( (2 + 2) != 4) {
      console.log('Something has gone very wrong :( ');
    }
  }
}

const is2p2 = checkThatTwoPlusTwoEqualsFourAMillionTimes;

is2p2();
console.log(is2p2.name); 
// Output:  
   checkThatTwoPlusTwoEqualsFourAMillionTimes
   
<매개변수로서의 함수>
const timeFuncRuntime = funcParameter => {
   let t1 = Date.now();
   funcParameter();
   let t2 = Date.now();
   return t2 - t1;
}
 
const addOneToOne = () => 1 + 1;
 
timeFuncRuntime(addOneToOne);
//
timeFuncRuntime(() => {
  for (let i = 10; i>0; i--){
    console.log(i);
  }
}); // 10부터 거꾸로 세는 함수 호출
 다른 예
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, 10);
profile
개발자 지망생 서하입니당

0개의 댓글