From 9f229be704a8e6b229ffc90a3ba125c1e8718f00 Mon Sep 17 00:00:00 2001 From: Dan Cojocaru Date: Sun, 28 Aug 2022 04:09:10 +0200 Subject: [PATCH] Improve train search sorting --- train.js | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/train.js b/train.js index 7b10371..239a7a5 100644 --- a/train.js +++ b/train.js @@ -30,13 +30,27 @@ function rebuildSuggestions() { var trainNumber = trainNumberInput.value.trim() var suggestions = [] - for (var i = 0; i < knownTrains.length; i++) { - if (trainNumber) { + if (!trainNumber) { + suggestions = knownTrains.slice() + } + else { + for (var i = 0; i < knownTrains.length; i++) { if (!knownTrains[i].number.includes(trainNumber)) { continue } + suggestions.push(knownTrains[i]) } - suggestions.push(knownTrains[i]) + suggestions.sort((s1, s2) => { + if (s1.number.indexOf(trainNumber) != s2.number.indexOf(trainNumber)) { + return s1.number.indexOf(trainNumber) - s2.number.indexOf(trainNumber); + } + + if (s1.number.length != s2.number.length) { + return s1.number.length - s2.number.length; + } + + return s1.number.localeCompare(s2.number); + }) } suggestions.forEach(function (suggestion, index) {