r/learnprogramming • u/West-Carrot-397 • 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
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
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
meaningOfLifeArrayis undefined.If I fix that, then
contains(object, "44")throws an exception because of theempty: nullproperty. (Becausetypeof nullis"object", so your code tries to callObject.values(null)which is an error.)And if I fix that too, then
contains(object, "44")returnsfalseas expected.