DEV Community

loading...
Cover image for DAY 3 of building the Higher Order Functions in Javascript. the find Higher Order Function.

DAY 3 of building the Higher Order Functions in Javascript. the find Higher Order Function.

Emmanuel Onah
Frontend Architect
Updated on ・2 min read

Hello community,

today we will be implementing the find Higher Order Function.

//find function
/********************
 *@_find prototype is a javascript higher order function   that returns the first value that mets the condition i.e it takes it out of the prepended array because tnen its no more a  collection but rather just a singular value
 *@_find takes in a callback function
 *@callback: the callback takes in the finded value,index     of the finded value,the array
 *@author: Emmanuel Onah
 ********************/

Array.prototype._find = function(callback){
  for(let i = 0; i < this.length;i++){
     const expectedValue = callback(this[i],i,this);

     /*if the index is found i.e expected value exist in   the array, then return it and break        out.Note: i did not  use the break keyword because it will then be redundant in the   scope of return keyword but outside the scope of return  keyword you can use the break keyword.
      */
       if(expectedValue){
          const indexOfExpectedValue =     this.indexOf(this[i]);
   return this[indexOfExpectedValue];
   }
 }
 //if user computation is invalid, then lets just return   the function operation.
 return;
}

const names =  ["Jerry","Jude","Joe","CreativeDams","SashaBlanca"];
//test
const newValue = names._find((name,index,names)=>name.length > 3);
console.log(newValue);
Enter fullscreen mode Exit fullscreen mode

Alt Text

Day 1: the map array prototype
Day 2: the filter array prototype
Day 4: The reduce prototype

Discussion (0)