diff options
-rw-r--r-- | lib/unitsToRanges.js | 19 | ||||
-rw-r--r-- | test/unitsToRanges.js | 8 |
2 files changed, 25 insertions, 2 deletions
diff --git a/lib/unitsToRanges.js b/lib/unitsToRanges.js index e73388a..764d8f2 100644 --- a/lib/unitsToRanges.js +++ b/lib/unitsToRanges.js @@ -65,7 +65,7 @@ module.exports = (units, sourceAddresses) => { } }) .flat() - .sort((a, b) => a - b) + .sort(sortNumbers) .reduce((acc, cur, idx, src) => { const curParts = cur.match(regexp) const prevParts = idx > 0 ? src[idx - 1].match(regexp) : null @@ -98,3 +98,20 @@ module.exports = (units, sourceAddresses) => { return unitRanges.length ? unitRanges.join(';') : null } + +/* custom sort function where 2 goes before 1A and 1A goes before 1B */ +function sortNumbers(a, b) { + if (Number.isInteger(Number(a)) && Number.isInteger(Number(b))) { + // both are integers + return a - b + } else if (Number.isInteger(Number(a)) && !Number.isInteger(Number(b))) { + // a is integer but b isn't, so a goes before b + return -1 + } else if (!Number.isInteger(Number(a)) && Number.isInteger(Number(b))) { + // a isn't integer but b is, so a goes after b + return 1 + } else { + // neither are integers + return a.localeCompare(b) + } +} diff --git a/test/unitsToRanges.js b/test/unitsToRanges.js index 7183ad1..0908b1e 100644 --- a/test/unitsToRanges.js +++ b/test/unitsToRanges.js @@ -65,7 +65,7 @@ test('units list to addr:flats', t => { t.same( unitsToRanges(['1A', '2A', '3']), - '1A-2A;3', + '3;1A-2A', 'partially with suffix' ) @@ -99,5 +99,11 @@ test('units list to addr:flats', t => { 'source duplicates removed with range' ) + t.same( + unitsToRanges('2,15,3,12,1,9,19,1C,1A,6,14,16,5,5-6,A,B,C,4,17-18,7-8'.split(',')), + '1-9;12;14-19;1A;1C;A;B;C', + 'complex real world data' + ) + t.end() }) |