Lodash project .findKey() confirmation

I am having trouble believing I wrote the correct code when I compare my solution with Codecademy’s.

This is my solution which checks all tests but uses less code than Codecademy’s:

findKey(obj, func){
for (let key in obj){
if (func(obj[key]) == true){
return key;
} else {
return undefined;
};
};
},

I am missing something or is this a case where this is one of many roads that lead to Rome?

Lets compare both your solution and the one from Codecademy:

Codecademy solution:

findKey (object, predicate) {
    // Check each key of object
    for(let key in object) {
      
      // Find the value of the object key
      let value = object[key];
      // Call the predicate function on the value of the object key
      let predicateReturnValue = predicate(value);
      
      // Check if the functions gives a truthy
      if (predicateReturnValue) {
        return key;
      };
    };
    
    // if the for...in loop gives no truthy values return undefined
    return undefined;
  
  },

Your solution:

findKey(obj, func){
    for (let key in obj){
       if (func(obj[key]) == true){
          return key;
       } else {
          return undefined;
      };
   };
},

Both solutions take two input parameters, and object and a function: check
Both solutions loop through the keys of the object: check
Both solutions check if the returned value of the function with the object[key] as input is true: check
Both solutions return the key when the above mentioned condition is met: check
Both solutions return undefined when the above mentioned condition is not met: check

Only difference I see is that your function returns undefined inside the loop whilst the solution does this after the loop. Apart from that your solution is the same. You merely condensed

      let value = object[key];
      let predicateReturnValue = predicate(value);
      if (predicateReturnValue) {
        return key;
      };

Into

if (func(obj[key]) == true){
          return key;
}

Happy coding!

2 Likes