1

I want to track version numbers of an app and tell which versions are later than the previous.

If I have a value like 1.14.1 (but we're using underscores, so 1_14_1), what's a best way to determine that 1_14_2 (aka 1.14.2) is a later build, whereas 1_2_20 is not?

Anthony
  • 13,434
  • 14
  • 60
  • 80

2 Answers2

2

function natCompare(a, b) {
    var a = a.replace(/\d+/g, x => String.fromCharCode(x) )
    var b = b.replace(/\d+/g, x => String.fromCharCode(x) )

    return a < b ? -1 : a > b ? 1 : 0
}

x = ['1_14_10', '1_2', '1_14_9', '1_2_5', '3_1', '1_14']

console.log(x.sort(natCompare))
  
  
georg
  • 211,518
  • 52
  • 313
  • 390
0

Assuming that both versions have the same number of delimiters:

function compare(v1, v2) {
  const a = v1.split('_').map(s => parseInt(s))
  const b = v2.split('_').map(s => parseInt(s))
  for(let i = 0; i < a.length; i++) {
    if (a[i] !== b[i]) {
      return Math.sign(a[i] - b[i])
    }
  }
  return 0
}

compare('1_14_1', '1_14_1') // 0
compare('1_14_1', '1_14_2') // -1
compare('1_14_1', '1_2_20') // 1
madox2
  • 49,493
  • 17
  • 99
  • 99