Home > Software engineering >  Passing Arguments into array of inline functions
Passing Arguments into array of inline functions

Time:08-27

Challenge Instructions: Construct a function multiMap that will accept two arrays: an array of values and an array of callbacks. multiMap will return an object whose keys match the elements in the array of values. The corresponding values that are assigned to the keys will be arrays consisting of outputs from the array of callbacks, where the input to each callback is the key.

My Solution:

    let obj = {};
  for(let i = 0; i < arrVals.length; i  ) {
    obj[arrVals[i]] = [arrCallbacks.apply(null, arrVals[i])]
  }
  return obj;
}

console.log(multiMap(['catfood', 'glue', 'beer'], [function(str) { return str.toUpperCase(); }, function(str) { return str[0].toUpperCase()   str.slice(1).toLowerCase(); }, function(str) { return str   str; }]));
// should log: { catfood: ['CATFOOD', 'Catfood', 'catfoodcatfood'], glue: ['GLUE', 'Glue', 'glueglue'], beer: ['BEER', 'Beer', 'beerbeer'] }

Thoughts: Obviously my object keys are correct but I can't seem to pass in the values from the arrVals parameter into my anonymous function call list from the arrCallbacks parameter. I tried setting my key value to [arrCallbacks[i](arrVals[i])] but that only populates the first element in the array but I need all three values from the functions to be passed into the value of each key. Hmmmmmm...

CodePudding user response:

As far as I can see in your code, you're using the apply method on the callbacks array, not on each callback. This is probably why it isn't working.

Here is my guess:

function multiMap(values, callbacks) {
  let result = {}
  // Iterate over the values
  for (const value of values) {
    // get an array of the result of the callbacks
    result[value] = callbacks.map((callback) => callback(value));
    // version using apply
    // result[value] = callbacks.map((callback) => callback.apply(null, value));
  }
  return result
}

console.log(multiMap(['catfood', 'glue', 'beer'], [function(str) { return str.toUpperCase(); }, function(str) { return str[0].toUpperCase()   str.slice(1).toLowerCase(); }, function(str) { return str   str; }]));

  • Related