simplify.js
 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  
28    const ranges = []
29    for (const [min, max] of set) {
30      if (min === max)
31        ranges.push(min)
32      else if (!max && min === v[0])
33        ranges.push('*')
34      else if (!max)
35        ranges.push(`>=${min}`)
36      else if (min === v[0])
37        ranges.push(`<=${max}`)
38      else
39        ranges.push(`${min} - ${max}`)
40    }
41    const simplified = ranges.join(' || ')
42    const original = typeof range.raw === 'string' ? range.raw : String(range)
43    return simplified.length < original.length ? simplified : range
44  }