simplify.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // given a set of versions and a range, create a "simplified" range
  2. // that includes the same versions that the original range does
  3. // If the original range is shorter than the simplified one, return that.
  4. const satisfies = require('../functions/satisfies.js')
  5. const compare = require('../functions/compare.js')
  6. module.exports = (versions, range, options) => {
  7. const set = []
  8. let min = null
  9. let prev = null
  10. const v = versions.sort((a, b) => compare(a, b, options))
  11. for (const version of v) {
  12. const included = satisfies(version, range, options)
  13. if (included) {
  14. prev = version
  15. if (!min)
  16. min = version
  17. } else {
  18. if (prev) {
  19. set.push([min, prev])
  20. }
  21. prev = null
  22. min = null
  23. }
  24. }
  25. if (min)
  26. set.push([min, null])
  27. const ranges = []
  28. for (const [min, max] of set) {
  29. if (min === max)
  30. ranges.push(min)
  31. else if (!max && min === v[0])
  32. ranges.push('*')
  33. else if (!max)
  34. ranges.push(`>=${min}`)
  35. else if (min === v[0])
  36. ranges.push(`<=${max}`)
  37. else
  38. ranges.push(`${min} - ${max}`)
  39. }
  40. const simplified = ranges.join(' || ')
  41. const original = typeof range.raw === 'string' ? range.raw : String(range)
  42. return simplified.length < original.length ? simplified : range
  43. }