Skip to content

Same score Matches don't respect their original order #27

@SayYoungMan

Description

@SayYoungMan

Hello! First of all, thank you for making this package, I've been using it for my project.

Problem

I noticed this behaviour, that the relative input ordering is not preserved if two matches have the same score.
I'm not sure it's intentional but I think it's better to preserve the original order.

Example

From your test case:

emps := employees{
		{
			name: "Alice",
		},
		{
			name: "Bob",
		},
		{
			name: "Allie",
		},
	}
want := fuzzy.Matches{
	{
		Str:            "Allie",
		Index:          2,
		MatchedIndexes: []int{0, 1},
		Score:          12,
	}, {
		Str:            "Alice",
		Index:          0,
		MatchedIndexes: []int{0, 1},
		Score:          12,
	},
}

We notice that Alice was given before Allie but in the result Allie comes first.

Potential Fix

fuzzy/fuzzy.go

Line 43 in 5ed613f

func (a Matches) Less(i, j int) bool { return a[i].Score >= a[j].Score }

Change this to check for when score is strictly less

func (a Matches) Less(i, j int) bool { return a[i].Score > a[j].Score }

So that when it's getting sorted in sort.Stable it doesn't treat equal score as being "less" and swap the order.

Let me know what you think! I can raise the PR if you like.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions