version_compare.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Add zeros to an array until it reaches a specific length.
  2. function zeroPad (array, length) {
  3. for (var i = array.length; i < length; i++) {
  4. array[i] = 0
  5. }
  6. return array
  7. }
  8. function aLessB (a, b) {
  9. var maxLength = a.length > b.length ? a.length : b.length
  10. a = zeroPad(a.map(el => el === undefined ? 0 : parseInt(el)), maxLength)
  11. b = zeroPad(b.map(el => el === undefined ? 0 : parseInt(el)), maxLength)
  12. // Check if any of the declared items in a are less than their component in B.
  13. for (let i = 0; i < a.length; i++) {
  14. // If this component is less, the entire thing must be less
  15. if (a[i] < b[i]) {
  16. return true
  17. }
  18. // If this item is greater, the entire thing is greater.
  19. if (a[i] > b[i]) {
  20. return false
  21. }
  22. }
  23. return true
  24. }
  25. // Check if two arrays are equal.
  26. function aEqualB (a, b) {
  27. if (a.length !== b.length) return false
  28. for (var i = 0; i < a.length; i++) {
  29. if (a[i] !== b[i]) {
  30. return false
  31. }
  32. }
  33. return true
  34. }
  35. // Comparison types
  36. const comparisonFuncs = {
  37. '>=': (a, b) => { return !aLessB(a, b) || aEqualB(a, b) },
  38. '>': (a, b) => { return !aLessB(a, b) },
  39. '<=': (a, b) => { return aLessB(a, b) || aEqualB(a, b) },
  40. '<': (a, b) => { return aLessB(a, b) },
  41. '=': (a, b) => { return aEqualB(a, b) }
  42. }
  43. function comparison (backup, declared) {
  44. var backupComponents = /(>=|>|<|<=|=|~)?(?: +)?(\d+)(?:\.(\d+))?(?:\.(\d+))?/g.exec(backup)
  45. var declaredComponents = /(>=|>|<|<=|=|~)?(?: +)?(\d+)(?:\.(\d+))?(?:\.(\d+))?/g.exec(declared)
  46. const comparison = declaredComponents[1]
  47. return comparisonFuncs[comparison](backupComponents.slice(2, 5), declaredComponents.slice(2, 5))
  48. }
  49. // Check if a version satisfies a declared version constraint
  50. module.exports.versionCheck = function (backup, declared) {
  51. var declaredItems = declared.split(',').map(el => el.trim())
  52. for (var i = 0; i < declaredItems.length; i++) {
  53. if (!comparison(backup, declaredItems[i])) {
  54. return false
  55. }
  56. }
  57. return true
  58. }