For most such operations, we're using the lodash library. I'm open to other suggestions, but would likely just write the function myself before importing a new lib.
lodash has sortedIndexOf
, which performs a binary search in a sorted array (returns index of match or -1 if not found). It also has sortedIndexBy
, which, using a binary search, finds the index to insert a new element where you can specify a function to use to do the sort comparison (returns a valid index if not found)
I cannot find a function to do a find (return index only if found) using an efficient sorted search allowing you to specify the sort value function. It might look something like this:
_.sortedFindBy(array, value, function(x){x.timestamp})
I believe I could use
var idx = _.sortedIndexBy(array, value, function(x){x.timestamp})
return (array[idx] && array[idx].timestamp === value.timestamp) ? idx : -1
but it just seems odd to me to not have the syntactically more compact and intuitive form of an already feature-rich set of sorted search functions.
Am I missing something from the lodash docs? Is there a built in way to do this more idiomatically? Or should I go with my extra-check method?