jyoon006
jyoon006

Reputation: 809

higher order function javascripts

I'm trying to understand better and start coding JS with higher order functions. Below is just a practice I'm doing, and I want to output an array of numbers * 2.

function each(collection, callback) {
  for(var i = 0; i < collection.length; i++) {
    callback(collection[i]);
    }
}

function isNumber(item) {

  var arr = [];
    if(typeof item === "number") {
      arr.push(item * 2);
    }

  return arr;
}

each([1, 2, 3, 4, "String"], isNumber);

from my understanding, when each() function is invoked with array and isNumber argument, it runs through function each. When each function is invoked, it calls back isNumber function with array[i], then isNumber function with that array[i] is invoked and if the type of the array[i] is a number, it pushes that number * 2 to an array. The output I'm expecting is

[2, 4, 6, 8] since "String" is not a number it never got pushed into the array.

Am I not understanding this correctly? When I try to log this code, no output shows.

Upvotes: 0

Views: 89

Answers (2)

Kevin Boucher
Kevin Boucher

Reputation: 16675

I think this will work for you:

// Let's call this what it is
function getNumbersFromArray(collection, callback) {
    var arr = [],
        i = 0;

    for (; i < collection.length; i++) {
        // Check if isNumber and do mutliplication here
        if (callback(collection[i])) {
            arr.push(item * 2);
        }
    }

    return arr;
}

// Make isNumber actually return a boolean
function isNumber(item) {
    return typeof item === "number";
}

// call console.log()
console.log(getNumbersFromArray([1, 2, 3, 4, "String"], isNumber)); 

Upvotes: 2

PhilVarg
PhilVarg

Reputation: 4820

no output is showing because neither of your functions return anything.

here, i'd have your callback just apply the multiplication and return that value, then push to an array in your each function

function each(collection, callback) {
  var arr = [];
  for(var i = 0; i < collection.length; i++) {
      var result = callback(collection[i])
      if (typeof result !== 'undefined') {
        arr.push(callback(collection[i]));
      }
    }
  return arr
}

function isNumber(item) {
    if (typeof item === "number") {
      return item * 2;
    }
}

Upvotes: 2

Related Questions