0

I wrote the function that tokenizes arithmetic string expression into an array of tokens, such as numbers and operators. Everything's fine but I get a weird results when dealing with strings containing "10". Here's the code:

function tokenizeString(expressionString) {
    const tokenArray = [];

    let token = "";
    for (let i = 0; i < expressionString.length; i++) {
        if (parseInt(expressionString[i])) {
            token += expressionString[i];
        } else {
            tokenArray.push(parseInt(token));
            token = "";
            tokenArray.push(expressionString[i]);
        }
    }

    if (token !== "") {
        tokenArray.push(parseInt(token));
    }

    return tokenArray;
}

console.log(tokenizeString("14+2/8")); // [14, "+", 2, "/", 8]
console.log(tokenizeString("10+1")); // [1, '0', NaN, '-', 3] ??

For now I can't come up with an idea, why this happens.

Steve
  • 11,596
  • 7
  • 39
  • 53
tnsaturday
  • 527
  • 2
  • 10
  • 31

1 Answers1

1

Instead of parseInt in the if(parseInt(expressionString[i])){} you could use isNaN() to check if the string is number or not isNaN() returns true if not a number so your if would be if (!isNaN(expressionString[i])){}

function tokenizeString(expressionString) {
    const tokenArray = [];

    let token = "";
    for (let i = 0; i < expressionString.length; i++) {
        if (!isNaN(expressionString[i])) {
            token += expressionString[i];
        } else {
            tokenArray.push(parseInt(token));
            token = "";
            tokenArray.push(expressionString[i]);
        }
    }

    if (token !== "") {
        tokenArray.push(parseInt(token));
    }

    return tokenArray;
}

console.log(tokenizeString("14+2/8")); // [14, "+", 2, "/", 8]
console.log(tokenizeString("10+1")); // [10, '+', 1] ??
Haque
  • 175
  • 2
  • 12