hi i'm a junior web developer sorry for my dummy question, i give a text to spinWords function, if the text includes forbidden words , it should return the "ifWordExistsInList()" function and if it doesn't return the "ifWordNotExistInList()" function, but spinwords function only return one of them and can not decide which one is better , can you fix it ? (other functions work fine , just spinWords is the problem) .
const _SRC_ = {
//list of sentences that includes forbidden words ( just for test )
listOfTries: [
"Welcome",
"Hey fellow warriors",
"This is a test",
"This is another test",
"You are almost to the last test",
"Just kidding there is still one more",
"Seriously this is the last one",
],
//list of forbidden words
forbiddenWords: [
"Welcome",
"fellow",
"warriors",
"another",
"almost",
"kidding",
"there",
"still",
"Seriously",
"sentence",
"rrxqsqpw",
],
};
//this function reverses the forbidden words only ex: hey fellow warriors => hey wollef sroirraw
function ifWordExistsInList(value) {
const reverse = (item) => {
return [...item].reverse().join("");
};
let collection = value;
_SRC_.forbiddenWords.forEach((word) => {
const reg = new RegExp(word, "gi");
collection = collection.replace(reg, reverse(word));
});
return collection;
}
//this function reveses all the words ex: hello world => olleh dlrow
function ifWordNotExistInList(string) {
const makeArray = string.split(" "); // [ hello , world ]
const reversed = [];
makeArray.forEach((item) => {
const each = [...item]; // [ h,e,l,l,o ]
const word = each.reverse().join("");
reversed.push(word);
});
return reversed.join(" ");
}
/* in this function we check text to decide which fucntion is proper
if text is nonsense then go with function 'ifWordNotExistInList()' and if text has
forbidden words go with 'ifWordExistsInList()' */
function spinWords(text) {
// this function is the problem , and doesn't work the way that it should
for (var item in _SRC_.forbiddenWords) {
if (text.includes(item)) {
return ifWordExistsInList(text);
} else {
return ifWordNotExistInList(text);
}
}
}
//Here i check different sentences
//nonsense text test
var test = "ksdf skdjfh";
//sentences that includes forbidden words - i loop through them
console.log(`${test} => `, spinWords(test), "\n---------------------------");
_SRC_.listOfTries.forEach((item) => {
console.log("-- ", spinWords(item));
});