Search code examples
google-apps-scriptgoogle-sheetsreturnreturn-valuespreadsheet

Why my return array function won't using or combinning with "Math" methode after it has returnig to the array's values?


Guess ... I'm trying to write a function that returns an Array that I can pass into a String format. Like I will mention to here: I have the randomColor(customColorsArrays, takenColorsArray) the function is depend to class has filled which if the both of them are empty return the value of color has calculated by Math methode, if the class of customColorsArrays has filled by user to put their own Array themeselves, if the both of class has writed by user means return the array's var has seted at an earlier inside that function. To make this clearly see at the down below these of the codes :


function randomColor(customColorsArray, takenColorsArray) {
 var text = "",
     colors = ["orange", "yellow", "red", "maroon"];

   if (customColorsArray && takenColorsArray) {
      var text = "["+colors+"]";
   }
     else if (!customColorsArray && !takenColorsArray) {
      text += colors[Math.floor(Math.random() * colors.length)];
   }
     else {
      text += customColorsArray[Math.floor(Math.random() * customColorsArray.length)];
  };

   return text;
}

function personalRandomColor(e) {
 var text = "";

   if (e == "orange") {text += "almond";}
    else if (e == "yellow") {text += "melrose";}
    else if (e == "red") {text += "danube";}
    else if (e == "maroon") {text += "magenta";};

  return text;
}


And this is the HTML code to implemented the function an above.

bla... bla... bla...
  var customColorsArrays = randomColor('passingClass', 'takenColor'),
      randomFirstColor = randomColor(),
      skipFirstColors = customColorsArrays.replace('\[', '\[\"').replace('\]', '\"\]').replace(/[\,]/g, '\"\, \"').replace('\"'+randomColor()+'\"\,', ''),
      randomSecondColor = personalRandomColor(randomColor(toString(skipFirstColors))),
bla... bla... bla...

Solution

  • An easy and straight forward way to fix your code is to replace the line

    randomSecondColor = personalRandomColor(randomColor(toString(skipFirstColors)))
    

    for

    randomSecondColor = personalRandomColor(randomColor(JSON.parse(skipFirstColors)))
    

    The reason for this is that randomColor takes arrays of elements, and you are passing a String to it. The argument, skipFirstColors, is a String which is in fact a JSON representation of a list of Strings. You want it to be an actual list, not a String representing a list.

    The JSON.parse function will evaluate the String returned by skipFirstColors and return the list it represents.

    Furthermore, I would suggest you revisit and potentially refactor your code. You should try to use the built-in types such as lists as function returns instead of working with JSON representations of your objects (serialized as Strings) as that will avoid this sort of errors, and will make for cleaner code.