robertoandres24
4/26/2020 - 8:39 PM

own higher order function

const strArray = ['JavaScript', 'Python', 'PHP', 'Java', 'C'];
function mapForEach(arr, fn) {
  const newArray = [];
  for(let i = 0; i < arr.length; i++) {
    newArray.push(
      fn(arr[i])
    );
  }
  return newArray;
}
const lenArray = mapForEach(strArray, function(item) {
  return item.length;
});
// prints [ 10, 6, 3, 4, 1 ]
console.log(lenArray);
let animals = [
  { name: 'alf', type: 'dog' },
  { name: 'beto', type: 'cat' },
  { name: 'carl', type: 'dog' },
  { name: 'dan', type: 'fish' }
]
let isDog = a => a.type === 'dog'

const myFilter = function (cb) {
  const newArr = []
  for (let i = 0; i < this.length; i++) {
    let truthy = cb(this[i])
    truthy && newArr.push(this[i])
  }
  return newArr
}

Array.prototype.myFilter = myFilter

console.log(animals.myFilter(isDog))