findKey() - recreating Lodash Library


#1

Hi guys, I just got stuck at this task https://www.codecademy.com/paths/web-development/tracks/web-dev-js-arrays-loops-objects/modules/pjs-javascript-capstone/projects/lodash (task 29 point 5) which is:

“Still within the loop, create another variable called predicateReturnValue and set it equal to the result of calling predicate with value .”

This is my code and it doesn’t work. I know it’s a mess. Please, help.

findKey(object, predicate){
       for(let key in object){
        let value = object[key];
        let predicateReturnValue = predicate(value); 
        if (predicateReturnValue === 'true'){
          return value;
          }; 
        };
      	return undefined;
      },


#2

Okay, I know where the problem was:
To my surprise everything was OK until the if statement. It should go like this:

if (predicateReturnValue) {
      return key
      };
    }
      return;
}   

But I still don’t get it why the truthy value is checked in this way.
Could anyone explain?


#3

The conditional expression will always yield a boolean.

if ('a' === 'A'.toLowerCase())

can be interpreted as,

if (true)

since the resulting boolean of the above will be true.

if (truthy) {

} else {
    // must not be truthy
}

We need never compare a conditional expression to true. It is already that by virtue of its truthiness, and will toggle to the opposite boolean if not. if () and while () can only ever yield true or false from their condition.

We can boil your code down to this simple method…

findKey (object, predicate) {
    for (let key in object) {
      if (predicate(object[key])) {
        return key;
      }
    }
  },

Note that we don’t even need the final return. No return will be interpreted as undefined.


#4

Thank you very much for your reply. I must think about it for like an hour hahahah :slight_smile: Greetings from Poland mtf :slight_smile:


#5

Hi mtf,

Thank you for posting that. When I paste your code into jsfiddle as an expression, I get an error that predicate is not a function. Any idea why? Here is the code I pasted in:

let shortObj = {a: 1, b: 2, c: 1}

const findKey = (obj, predicate) => { 
      for (let key in obj){
        if(predicate(obj[key])){
          return key
        }
    	}
    } //close findKey

console.log(findKey(shortObj))

The reason I went to jsfiddle is to log out some lines to better understand what the code block does. BTW. using your code as a method inside the lodash lesson works fine.


#6

Because the function is supplied by the test module for this method.

const startsWithV = string => string.startsWith('v');

as in,

    _.findKey({"key": "value"}, startsWithV);    // "key"
                   object        predicate

#7

Thank you. Predicates are new to me. I’ll keep reading:

thanks.