Skip to content

Instantly share code, notes, and snippets.

@TheRolfFR
Last active September 16, 2024 18:55
Show Gist options
  • Save TheRolfFR/7e193d30c2a21e19bbebecf4f5fcbd1b to your computer and use it in GitHub Desktop.
Save TheRolfFR/7e193d30c2a21e19bbebecf4f5fcbd1b to your computer and use it in GitHub Desktop.
Minecraft version array sorter for js
// MinecraftVersionSorter.js 1.0 by TheRolf
// to use it, just just need to pass it as arg of the sort function for an array
// ["1.4.9","1.7","1.7.10","1.12.2","1.17.1","1.16.210","1.18"].sort(MinecraftSorter)
const MinecraftVersionSorter = (a, b) => {
const aSplit = a.split('.').map(s => parseInt(s))
const bSplit = b.split('.').map(s => parseInt(s))
if(aSplit.includes(NaN) || bSplit.includes(NaN)) {
return String(a).localeCompare(String(b)) // compare as strings
}
const upper = Math.min(aSplit.length, bSplit.length)
let i = 0
let result = 0
while(i < upper && result == 0) {
result = (aSplit[i] == bSplit[i]) ? 0 : (aSplit[i] < bSplit[i] ? -1 : 1) // each number
++i
}
if(result != 0) return result
result = (aSplit.length == bSplit.length) ? 0 : (aSplit.length < bSplit.length ? -1 : 1) // longer length wins
return result
}
try {
if(typeof process === 'object') {
module.exports = MinecraftVersionSorter
}
} catch (_error) {
// normal browser
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment