Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

_.sortedLastIndex #1882

Open
jdalton opened this issue Sep 29, 2014 · 3 comments · May be fixed by #2106
Open

_.sortedLastIndex #1882

jdalton opened this issue Sep 29, 2014 · 3 comments · May be fixed by #2106

Comments

@jdalton
Copy link
Contributor

jdalton commented Sep 29, 2014

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.

@megawac
Copy link
Collaborator

megawac commented Oct 1, 2014

Are you suggesting anything more complicated than below?

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

@jdalton
Copy link
Contributor Author

jdalton commented Oct 1, 2014

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`

@gabhi
Copy link

gabhi commented Oct 10, 2014

My 2 cents in regards of @megawac code.

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants