From 68f4bd7cae1f6ca0136df18493b435c34c4101b3 Mon Sep 17 00:00:00 2001 From: Jakub Pawlowicz Date: Wed, 11 Jan 2017 08:40:03 +0100 Subject: [PATCH] See #425 - nitpicking natural sorting algorithm. Thanks to @alexlamsl for spotting these. --- lib/utils/natural-compare.js | 4 ++-- test/utils/natural-compare-test.js | 12 ++++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/lib/utils/natural-compare.js b/lib/utils/natural-compare.js index da828f40..7a524676 100644 --- a/lib/utils/natural-compare.js +++ b/lib/utils/natural-compare.js @@ -15,11 +15,11 @@ function naturalCompare(value1, value2) { key2 = keys2[i]; if (key1 != key2) { - return key1 > key2 ? 1 : (key1 === key2 ? 0 : -1); + return key1 > key2 ? 1 : -1; } } - return keys1.length > keys2.length ? 1 : -1; + return keys1.length > keys2.length ? 1 : (keys1.length == keys2.length ? 0 : -1); } function tryParseInt(value) { diff --git a/test/utils/natural-compare-test.js b/test/utils/natural-compare-test.js index b2eb40bd..6378ef52 100644 --- a/test/utils/natural-compare-test.js +++ b/test/utils/natural-compare-test.js @@ -43,4 +43,16 @@ vows.describe(naturalCompare) } } }) + .addBatch({ + 'objects': { + 'topic': [['a', 1], ['a0', 2], ['a0', 3], ['a1', 5], ['a0', 4], ['a0', 5], ['a0', 1]], + 'are sorted': function (list) { + var sortedList = list.sort(function (o1, o2) { + return naturalCompare(o1[0], o2[0]); + }); + + assert.deepEqual(sortedList, [['a', 1], ['a0', 2], ['a0', 3], ['a0', 4], ['a0', 5], ['a0', 1], ['a1', 5]]); + } + } + }) .export(module); -- 2.34.1