Working outside function -alg challenges

Working outside function -alg challenges
0

#1

I just completed the intermediate front-end challenges. Steamroller was my last one, and i used recursion in my solution. Unfortunately, i had to nest a function within the steamroller function. If i tried to put the new array variable within the steamroller function, it got reset every recursive call–an anticipated problem. However, if i placed it outside the prefabricated steamroller function, there was some sort of testing error. I would get all the right answers, but my new array accumulated all of the test answers, not just the one that the steamroller function was called on, thus not allowing me to pass the challenge.

Like i said, i just nested a function inside the steamroller function so the new array variable could be outside of the recursion but inside the steamroller function. Maybe i did the problem in an unsatisfactory way, but it felt like the testing mechanism should’ve cooperated with my initial attempt to have the new empty array declared outside of the function.

If this is common in testing, can you explain why?

(If need be, i’ll supply code. Always try to be careful with that on the forums.)


#2

The testing mechanism was fine. Your code contained global variables that are changed each time the function is run. This means that after each test completes, subsequent tests start with the new value. To fix this, make sure your function doesn’t change any global variables, and declare/assign variables within the function if they need to be changed.

Example:

var myGlobal = [1];
function returnGlobal(arg) {
  myGlobal.push(arg);
  return myGlobal;
} // unreliable - array gets longer each time the function is run

function returnLocal(arg) {
  var myLocal = [1];
  myLocal.push(arg);
  return myLocal;
} // reliable - always returns an array of length 2

It’s hard to tell you how to remove the nested function without seeing your code. There are many ways to skin this cat. Probably what you need to be doing is to be modifying the array with the recursive call.