0

Okay, the problem asks me to update a string. When the char is followed by an A, I callback my addOne function and delete the A. When my char is followed by a B, I callback my subtractOne function and delete the B. Here is what I have, and my test variable - 123A456B should return 124455. Instead it returns 1231455. Can someone help me figure out why? I feel like I am missing something obvious. Thank you!

const test = '123A456B'

function addOne(num) {
  return num + 1
}

function subtractOne(num) {
  return num - 1
}

function updateString(string) {
  let result = ''
  for (let i = 0; i < string.length; i++) {
    if (string[i] === 'A' || string[i] === 'B') {
    } else if (string[i + 1] === 'A') {
      result += addOne(string[i])
    } else if (string[i + 1] === 'B') {
      result += subtractOne(string[i])
    } else result += string[i]
  }
  return result
}
console.log(updateString(test))
Barmar
  • 741,623
  • 53
  • 500
  • 612
mimi
  • 1
  • 1
    `num` is a string, not a number. So `num + 1` performs string concatenation, not numeric addition. – Barmar Sep 14 '22 at 21:39

1 Answers1

0

You need to convert those strings intro numbers when you do your addition. You can use the shorthand + prefix, parseInt(n) or Number(n)

function addOne (num){
  return +num + 1
}

function subtractOne (num){
  return +num - 1
}

const test = '123A456B'

function addOne (num){
  return +num + 1
}

function subtractOne (num){
  return +num - 1
}

function updateString(string){
  let result = ''
    for(let i = 0; i < string.length; i++){ 
    if(string[i] === 'A' || string[i] === 'B'){ 
    }else if(string[i + 1] === 'A'){
        result += addOne(string[i])
    }else if(string[i + 1] === 'B'){
      result += subtractOne(string[i])
    }else result += string[i]
  }
  return result
}
console.log(updateString(test))
Kinglish
  • 23,358
  • 3
  • 22
  • 43