Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing Arguments into array of inline functions

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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; }]));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading