Home > Back-end >  Complete logger function that takes in a function and a string and returns the result of calling the
Complete logger function that takes in a function and a string and returns the result of calling the

Time:10-07

function logger(func, str) {
 let newStr = ''
  for (i = 0; i < str.length; i  ){
      newStr.push(func)
      return newStr
  }
}

Need help making the logger function that takes in a function and a string and returns the result of calling the function on each letter in the string

CodePudding user response:

You can try [...str].map(func).join('')

function logger(func, str) {
  return [...str].map(func).join('');
}

Explanation

if str is abc then [...str] is [ "a", "b", "c" ].

Then if you .map to something like c => c.toUpperCase() you get [ "A", "B", "C" ].

Then .join('') produces ABC.

CodePudding user response:

Right now, you are pushing the function itself into the newStr, which will return... interesting results. Try something like this? Also, push won't work on strings. You should also move return newStr outside of the loop.

function logger(func, str) {
    let newStr = ''
       for (i = 0; i < str.length; i  ){
           newStr  = (func(str[i])
       }
    return newStr
}
  • Related