E_Jovi E_Jovi - 5 months ago 15
Javascript Question

algorithm of findKey in lodash

I want to find key via value from object, and I find that lodash provide us convenient api

findKey
could help me.

but my question is, how could
findKey
work? is that different from hash common key value mapping?

I don't know anything about that, if possible, could you provide me some example to compare?

thanks for your time!

Answer

Lodash is an open-source library, you can inspect its source to check their implementations of all functions.

https://github.com/lodash/lodash/blob/master/lodash.js

findKey can probably be traced down to line 716's baseFindKey function:

function baseFindKey(collection, predicate, eachFunc) {
  var result;
  eachFunc(collection, function(value, key, collection) {
    if (predicate(value, key, collection)) {
      result = key;
      return false;
    }
  });
  return result;
}

What it does is it runs through the collection, and for every member inside the collection, run the predicate check to see if the member matches the predicate.

If it matches, the key would be returned as the result.