Codesmith CSX Challenge: Censor - Stuck right at the end!
Man, I am super stuck on this problem.
The problem comes from Codesmith here: csx.codesmith.io/units/closures/challenge-c..
This is the error message I get from Codesmith's environment:
And this is the console output of my code.
Here's a repl.it so you can run it and maybe point me to where I'm blind: repl.it/@miguelmanalo/WelloffReadyEngineers..
// Create a function censor that accepts no arguments. censor will return a function that will accept either two strings, or one string. When two strings are given, the returned function will hold onto the two strings as a pair, for future use. When one string is given, the returned function will return the same string, except all instances of a first string (of a saved pair) will be replaced with the second string (of a saved pair).
const censor = () =>
{
let counter = 0;
const saved = [];
const innerFunction = (str1, str2) => {
if (str2 === undefined) {
counter++;
let regex1 = new RegExp(saved[counter - 3][0], "gi");
let regex2 = new RegExp(saved[counter - 2][0], "gi");
let answer1;
answer1 = str1.replace(regex1, (saved[counter - 3][1]));
return answer1.replace(regex2, (saved[counter - 2][1]));
}
else if (str2 !== undefined) {
for (let i = 0; i <= counter; i++) {
if (saved[i] === undefined) {
saved[i] = [];
saved[i][0] = str1;
saved[i][1] = str2;
}
}
counter++;
}
}
return innerFunction;
}
// Uncomment these to check your work!
const changeScene = censor();
changeScene('dogs', 'cats');
changeScene('quick', 'slow');
console.log(changeScene('The quick, brown fox jumps over the lazy dogs.')); // should log: 'The slow, brown fox jumps over the lazy cats.'
//Notes
// const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
// const regex = /dog/gi;
// console.log(p.replace(regex, 'ferret'));
// // expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"
// console.log(p.replace('dog', 'monkey'));
// // expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"
Edit 1: found the error. The test passes in another call to the function with just one argument which... breaks everything. So back to zero I guess!
Edit 2: solved it
github.com/miguelmanalo/codesmith-csx-censo..
I needed to pair up the word to be censored and the new word which I did with an initial replace on the passed in argument. Then I did a while loop to keep updating answer1 with the newly replaced words in the sentence.
What went wrong before is that I wasn't writing for the possibility that someone sends in a single argument multiple times in a row. I was also too tied to the counter incrementing variable to use that as my anchor on where my data was stored.
Using the while loop was a big, big revelation.