-2

I am trying to create a simple code which splits a string at ',' . The expected string is a list of numbers separated by commas. I have to print the sum of those numbers. My code is here:

function add(numbers) {
if (numbers === "")
{
    return 0;
}

else if (typeof parseInt(numbers) == 'number')
{        
    return parseInt(numbers);
}
else 
{
    let numArray = numbers.toString().split(',');
    console.log(numArray);
    
    let value = numArray.every(checkElement);
    if (value) {
        return (getSum(numArray));
    }
    else
    {
        return "Error in formatting";
    }
}
}
function checkElement(element)
{
    return (typeof parseInt(element) == 'number')
}
function getSum(numArray)
{
    let total = 0;
    for (let i = 0; i < numArray.length; i++)
    {
        total += numArray[i];
    }
    return total
}

module.exports = add 

My Jest code is:

const add = require('../sum.js')
test('Returns sum of numbers', () => {
    expect (
        add("225,75")
    ).toBe(300)
}) 

I am getting this error:

● Returns sum of numbers

expect(received).toBe(expected) // Object.is equality

Expected: 300
Received: 225

  17 |         add("225,75")
> 18 |     ).toBe(300)
     |       ^
  19 | })

  at Object.toBe (js/Testing/sum.test.js:18:7)

Moreover, my VS Code is not printing any console.log if I try to run the my js file using node filename.js command. It just starts a new terminal line. Not sure what's going wrong. The error looks like split() isn't working properly - it's only ever returning the 1st element (don't understand why) and VS Code won't print my console logs to check where it is stuck.

Kritzii
  • 23
  • 7
  • Do some basic debugging - why do you think the split is even reached? – jonrsharpe May 24 '22 at 06:46
  • 1
    your code says `toEqual` but the error says `toBe`????? Maybe read the doc pages of all functions used – rioV8 May 24 '22 at 06:51
  • @jonrsharpe , yes, I tested and found that the control is entering the 2nd condition, even if the entire string passed is separated by a comma whose parseInt is still returning the part of the string before a comma. But when I pass a string like "12,abc" and then delimit them, then event the typeof parseInt("abc") is coming out as a number. I guess, this type checking itself is faulty. – Kritzii May 24 '22 at 08:16
  • @rioV8 - yes, corrected the snippet – Kritzii May 24 '22 at 08:26

3 Answers3

0

instead of typeof parseInt(numbers) , you should have done typeof numbers as even typeof NaN is also a number and thus wrong result.

  • yes, I tested and found that the control is entering the 2nd condition, even if the entire string passed is separated by a comma whose parseInt is still returning the part of the string before a comma. But when I pass a string like "12,abc" and then delimit them, then even the typeof parseInt("abc") is coming out as a number. I guess, this type checking itself is faulty. – Kritzii May 24 '22 at 08:17
0

My process of checking the typeof parseInt("some possible not number") itself is faulty. As parsing anything to int produces a number, I should have checked with isNaN instead. I think we can close off this question. It certainly did help in enhancing my knowledge of small things like parseInt's actions.

Kritzii
  • 23
  • 7
-1

The issue is with the attempt to handle the case of "just one number" in a special way. It turns out the result of parseInt("") is always of type "number". So, the answer is:

Scrap the special case and all will be well.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
flowtron
  • 854
  • 7
  • 20
  • Why would the environment matter? The input is a literal string with a comma in it. – jonrsharpe May 24 '22 at 07:24
  • You have apparently never had this issue but it happens! Compare (among others) https://stackoverflow.com/a/7431873/3022387 – flowtron May 24 '22 at 08:59
  • I'm aware that it _can_ happen, in some contexts, but just look at the code in the OP's post: `add("225,75")`, `.split(',')`. Neither has anything to do with the locale. – jonrsharpe May 24 '22 at 09:00
  • the code never gets to that line - because of """ else if (typeof parseInt(numbers) == 'number') """ – flowtron May 24 '22 at 09:06
  • Yes, [I'm aware of that too](https://stackoverflow.com/questions/72358047/why-is-a-simple-test-failing-and-split-not-working-properly/72358563?noredirect=1#comment127829847_72358047) - all the more reason that your suggestion around the locale's decimal delimiter has absolutely nothing to do with the actual problem. – jonrsharpe May 24 '22 at 09:06
  • upon closer inspection the locale is not at fault, but the line mentioned is for sure .. because """ typeof parseInt("") """ is also "number" .. so, thanks @jonrsharpe for making me dig a little deeper! ;-) – flowtron May 24 '22 at 09:08
  • [`parseInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt) takes as much of the input as it can up to the first non-numeric character. Neither `.` nor `,` is considered numeric, so the locale is irrelevant. There's also [`parseFloat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat), but I don't think that's locale-aware, only `.` matters. – jonrsharpe May 24 '22 at 09:11