underscore icon indicating copy to clipboard operation
underscore copied to clipboard

_.sortedLastIndex

Open jdalton opened this issue 10 years ago • 3 comments

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.

jdalton avatar Sep 29 '14 19:09 jdalton

Are you suggesting anything more complicated than below?

_.sortedLastIndex = function(arr, item) {
   var index = _.sortedIndex(arr, item);
   for (; arr[index] !== item; index++) {}
   return index;
};

megawac avatar Oct 01 '14 00:10 megawac

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`

jdalton avatar Oct 01 '14 00:10 jdalton

My 2 cents in regards of @megawac code.

if item is not present in the array then it will go in infinite loop

gabhi avatar Oct 10 '14 01:10 gabhi