Here is the prompt for what I need to do. I still haven't figured out the full solution yet, and I know this is not optimal at all (I'm a complete beginner and just trying to get something working for now), but that's not what my question is.
/* There are two types of potions:
Growing potion: "A"
Shrinking potion: "B"
If "A" immediately follows a digit, add 1 to the digit using your "addOne" function
If "B" immediately follows a digit, subtract 1 from the digit using your subtractOne function
Create a function "usePotions" that returns a string according to these rules, removing the potions once they've been consumed.
Example:
usePotions("3A7851") ➞ "47851"
usePotions("9999B") ➞ "9998"
usePotions("9A123") ➞ "10123"
usePotions("567") ➞ "567"
*/
I am using the string.replace() method in order to both increment or decrement the digit before A or B, and remove the A or B. For the strings with "A" in them, the code is working perfectly fine. For the one with B, even though the correct index is being passed into the replace method (which is 3), it's replacing the digit at index 0. I can't for the life of me figure out why the same exact code is behaving differently. I tried manually passing different indexes and it keeps replacing the character at index 0.
const addOne = (num) => num + 1;
const subtractOne = (num) => num - 1;
const usePotions = (str) => {
let newStrA;
let finalStrA;
let newStrB;
let finalStrB;
if (!str.includes("A") && !str.includes("B")) return str;
if (str.includes("A")){
newStrA = str.replace(str[str.indexOf("A")-1], addOne(Number(str[str.indexOf("A")-1])))
finalStrA = newStrA.replace("A", "");
return finalStrA;
}
if (str.includes("B")){
console.log(str.indexOf("B")-1);
newStrB = str.replace(str[str.indexOf("B")-1], subtractOne(Number(str[str.indexOf("B")-1])))
finalStrB = newStrB.replace("B", "");
return finalStrB;
}
}
console.log(usePotions("3A7851"));
console.log(usePotions("9999B"));
console.log(usePotions("9A123"));
console.log(usePotions("567"));