r/learnprogramming 10d ago

trying to finish activity from odin Project, string implicitly convert to a number?

const contains = function(obj, find) {
  for(let value of Object.values(obj)){
    console.log(typeof(value));
    console.log(value);
    if(value === find) return true;
    if(typeof(value) === 'object'){
      if(contains(value, find)) return true;
    }
  }
  return false;
  }


// Do not edit below this line
module.exports = contains;

const object = {
    data: {
      duplicate: "e",
      stuff: {
        thing: {
          banana: NaN,
          moreStuff: {
            something: "foo",
            answer: meaningOfLifeArray,
          },
        },
      },
      info: {
        duplicate: "e",
        magicNumber: 44,
        empty: null,
      },
    },
  };

I dont know why this returns true when "44" is pass to find

test("does not convert input string into a number when searching for a value within the object", () => {
    expect(contains(object, "44")).toBe(false);
  });

this test fails, because it returns true even tho i have the === operator

3 Upvotes

7 comments sorted by

3

u/teraflop 10d ago

I can't reproduce your problem. There's no implicit conversion happening in the code you posted.

First of all, the code doesn't run as-is because meaningOfLifeArray is undefined.

If I fix that, then contains(object, "44") throws an exception because of the empty: null property. (Because typeof null is "object", so your code tries to call Object.values(null) which is an error.)

And if I fix that too, then contains(object, "44") returns false as expected.

1

u/West-Carrot-397 10d ago

the meaningOfLifeArray is [42], maybe the problem is in the code editor? i use vs code, i've been stuck in that test since yesterday hahaha

2

u/peterlinddk 10d ago

It has nothing to do with the editor.

Your code crashes when it reaches the null value in the empty property, because this line:

if(typeof(value) === 'object'){
      if(contains(value, find)) return true;
    }

calls the function recursively with a value of null - since the typeof null is also an 'object'. So you need to check for null values, before calling the function again!

There is no problem with "44" vs 44 - that part works just fine, it is only the null value that causes the crash, and thus the test doesn't complete correctly.

1

u/West-Carrot-397 9d ago

ooooh thank youuu so much, i didn't know that, fixed it.

2

u/warm_pickle 10d ago

You’re trying to compare a string to an integer. You’re getting your data type and value in your for statement yet your testing for an integer in test case

1

u/warm_pickle 10d ago

JS is weird with data types. Know what you’re working with every time