simplify.js 1.3 KB

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