Skip to content

Comparator edge-case handling #1768

@megawac

Description

@megawac

There are several inconsistencies with the comparator functions I feel should be addressed in 2.0. Mentioned this earlier in jashkenas/backbone#3243

  • max: NaN including undefined is considered the lowest item in the array. Even lower then no item
_.max([{a: {}}], 'a'); // => -Infinity
  • min: same as max but NaN values are considered the highest items
  • sortBy: special cases all undefined values to the end of the array. All NaN values are moved to the front of the array
  • sortedIndex: different from sortBy (see lodash/lodash@b07337f#commitcomment-7164123): computed NaN is moved to the end of the list instead of the front
var array = [{a: NaN}, {a: NaN}, {a: {}}, {a: 1}, {a: 2}];
_.sortedIndex(array, {a: 3}, 'a'); // => 0
var sorted = _.sortBy(array.concat({a: 3}), 'a');
_.findIndex(sorted, {a: 3}); // => 5

I propose a baseComparator(a, b) used by those 4 functions (special case min?) which handles these cases consistently. I feel strongly about changing sortBy's handling of NaN vs undefined. I think they should be considered NaN < -Infinity < x.

// Reasoning
_.sortBy([{a: 1}, {a: -Infinity}, {a: 2}, {}], 'a')
// Should => [{}, {a: -Infinity}, {a: 1}, {a: 2}]

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions