jashkenas / underscore

JavaScript's utility _ belt
https://underscorejs.org
MIT License
27.3k stars 5.53k forks source link

uniq doesn't use property "isSorted" if an iteratee function is passed #2940

Closed Relik77 closed 3 years ago

Relik77 commented 3 years ago

I have an array of objects that I want to make unique based on a property of the object, and I know the array is already sorted by that property.

const result = _.uniq([{a: 1}, {a: 1}, {a: 2}], true, obj => obj.a);

So I want to use the optimized algorithm but, according to the code of the function this is not the case:

function uniq(array, isSorted, iteratee, context) {
 // [...]
      if (isSorted && !iteratee) { // Why the condition "&& !iteratee" ? Juste "if(isSorted)" is fine no ?
        if (!i || seen !== computed) result.push(value);
        seen = computed;
      } else if (iteratee) {
// So we go here and isn't the optimized algorithm :/
        if (!contains(seen, computed)) {
          seen.push(computed);
          result.push(value);
        }
      } else if (!contains(result, value)) {
        result.push(value);
      }
jgonggrijp commented 3 years ago

Acknowledged. I'm considering to (partially) address this in version 2.0, as it would be a breaking change. See https://github.com/jashkenas/underscore/pull/2930 for further discussion.