statsguyz
statsguyz

Reputation: 469

Creating a function using callback

I'm trying to understand how callback functions work properly by solving this problem:

Complete the following merge function such that is behaves as described in the example below. Merge should take two arrays of numbers of identical length and a callback function.

var merge = function(array1, array2, callback){  
  //your code here.
}

var x = merge([1, 2, 3, 4], [5, 6, 7, 8], function(a, b){  
  return a + b;
});

//x should now equal [6, 8, 10, 12].

Now, use your merge function to complete the euclid function defined below. Euclid should take two arrays, each of which has an equal number of numerical elements, and return the euclidean distance between them. For a quick refresher on what Euclidean distance is, check here

var euclid = function(coords1, coords2){  
  //Your code here.
  //You should not use any loops and should
  //instead use your original merge function.
}

var x = euclid([1.2, 3.67], [2.0, 4.4]);

//x should now equal approximately 1.08.

I'm able to do this without callbacks, but ultimately I want to know how to complete a function like this using callback as a parameter.

Upvotes: 0

Views: 150

Answers (1)

venkat7668
venkat7668

Reputation: 2777

Here you go..

var merge = function(array1, array2, callback) {
  var result = [];
  if (array1.length === array2.length) {
    while (array1.length > 0) {
      result.push(callback.call(null, array1.shift(), array2.shift()));
    }
  }
  return result;
}

var euclid = function(coords1, coords2) {
  var x = merge(coords1, coords2, function(a, b) {
    return a - b;
  })
  return Math.sqrt(Math.pow(x[0], 2) + Math.pow(x[1], 2));
}

console.log(euclid([1.2, 3.67], [2.0, 4.4]));

Upvotes: 1

Related Questions