Advertisement
karlakmkj

Higher-order function

Dec 10th, 2020 (edited)
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //Not fully understood yet
  2. const checkThatTwoPlusTwoEqualsFourAMillionTimes = () => {
  3.   for(let i = 1; i <= 1000000; i++) {
  4.     if ( (2 + 2) != 4) {
  5.       console.log('Something has gone very wrong :( ');
  6.     }
  7.   }
  8. };
  9.  
  10. const addTwo = num => num + 2;
  11.  
  12. const timeFuncRuntime = funcParameter => {
  13.   let t1 = Date.now();
  14.   funcParameter();
  15.   let t2 = Date.now();
  16.   return t2 - t1;
  17. };
  18.  
  19.  
  20. let time2p2 = timeFuncRuntime(checkThatTwoPlusTwoEqualsFourAMillionTimes);
  21.  
  22. //Higher-order function that has two parameters: a function and a value.
  23. const checkConsistentOutput = (func,val) => {
  24.     let firstTry = func(val);
  25.     let secondTry = func(val);
  26.     if (firstTry === secondTry) {
  27.         return firstTry;
  28.     } else {
  29.         return 'This function returned inconsistent results';
  30.     }
  31. }
  32.  
  33. console.log(checkConsistentOutput(addTwo, 3));  //pass the function of addTwo but not invoke it
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement