underscore
underscore copied to clipboard
_.sortedLastIndex
Underscore has _.sortedIndex
but this could be expanded to _.sortedLastIndex
using a shared helper between them both (minimal code increase). This would allow _.lastIndexOf
to support binary searches as well.
Are you suggesting anything more complicated than below?
_.sortedLastIndex = function(arr, item) {
var index = _.sortedIndex(arr, item);
for (; arr[index] !== item; index++) {}
return index;
};
If it work's for you all then that's fine (it doesn't return the expected result so would need tweaking). I'm not sure how that implementation would do perf wise either but it's a start.
Usage example with expected results:
var a = [1, 2, 2, 2, 3];
_.sortedIndex(a, 2); // expected `1`
_.sortedLastIndex(a, 2) // expected `4`
My 2 cents in regards of @megawac code.
if item is not present in the array then it will go in infinite loop