jdsteinbach / eleventy-plugin-toc

11ty plugin to generate a TOC from page content
61 stars 19 forks source link

fix array.sort bug #4

Closed KyleMit closed 4 years ago

KyleMit commented 5 years ago

Okay, so this is an odd bug in node, but when I get a Table of Contents with exactly 11 headers, they come back in the wrong order, with the 6th one first.

Here's a simple reproducible example

$ node
> var objects = [ { o: 0 }, {o: 1}, {o: 2}, {o: 3}, {o: 5}, { o: 6 }, {o: 7}, {o: 8}, {o: 9}, {o: 10}, {o: 11} ];
> objects.sort((a,b) => a.o > b.o ).map(x => x.o);
> // [ 6, 0, 1, 2, 3, 5, 7, 8, 9, 10, 11 ]
> objects.sort((a,b) => a.o - b.o ).map(x => x.o);
> // [ 0, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11 ]

According to the docs on MDN, the compareFunction for Array.sort() should return an integer of -1, 0, or 1. Although returning false works in most other browsers and javascript engines I've tried, it might be better to return the expected values.

In the docs on MDN, they suggest using a - sign for comparing numbers:

To compare numbers instead of strings, the compare function can simply subtract b from a.

function compareNumbers(a, b) {
 return a - b;
}

So a super minor edit, but one that hits this odd edge case.