simplify.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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 first = 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 (!first) {
  16. first = version
  17. }
  18. } else {
  19. if (prev) {
  20. set.push([first, prev])
  21. }
  22. prev = null
  23. first = null
  24. }
  25. }
  26. if (first) {
  27. set.push([first, null])
  28. }
  29. const ranges = []
  30. for (const [min, max] of set) {
  31. if (min === max) {
  32. ranges.push(min)
  33. } else if (!max && min === v[0]) {
  34. ranges.push('*')
  35. } else if (!max) {
  36. ranges.push(`>=${min}`)
  37. } else if (min === v[0]) {
  38. ranges.push(`<=${max}`)
  39. } else {
  40. ranges.push(`${min} - ${max}`)
  41. }
  42. }
  43. const simplified = ranges.join(' || ')
  44. const original = typeof range.raw === 'string' ? range.raw : String(range)
  45. return simplified.length < original.length ? simplified : range
  46. }