diff --git a/classes/range.js b/classes/range.js index 117b45a2..ceee2314 100644 --- a/classes/range.js +++ b/classes/range.js @@ -1,3 +1,5 @@ +const SPACE_CHARACTERS = /\s+/g + // hoisted class for cyclic dependency class Range { constructor (range, options) { @@ -18,7 +20,7 @@ class Range { // just put it in the set and return this.raw = range.value this.set = [[range]] - this.format() + this.formatted = undefined return this } @@ -29,10 +31,7 @@ class Range { // First reduce all whitespace as much as possible so we do not have to rely // on potentially slow regexes like \s*. This is then stored and used for // future error messages as well. - this.raw = range - .trim() - .split(/\s+/) - .join(' ') + this.raw = range.trim().replace(SPACE_CHARACTERS, ' ') // First, split on || this.set = this.raw @@ -66,14 +65,29 @@ class Range { } } - this.format() + this.formatted = undefined + } + + get range () { + if (this.formatted === undefined) { + this.formatted = '' + for (let i = 0; i < this.set.length; i++) { + if (i > 0) { + this.formatted += '||' + } + const comps = this.set[i] + for (let k = 0; k < comps.length; k++) { + if (k > 0) { + this.formatted += ' ' + } + this.formatted += comps[k].toString().trim() + } + } + } + return this.formatted } format () { - this.range = this.set - .map((comps) => comps.join(' ').trim()) - .join('||') - .trim() return this.range } diff --git a/test/classes/range.js b/test/classes/range.js index 9547e23a..c1e6eb1b 100644 --- a/test/classes/range.js +++ b/test/classes/range.js @@ -82,6 +82,15 @@ test('tostrings', (t) => { t.end() }) +test('formatted value is calculated lazily and cached', (t) => { + const r = new Range('>= v1.2.3') + t.equal(r.formatted, undefined) + t.equal(r.format(), '>=1.2.3') + t.equal(r.formatted, '>=1.2.3') + t.equal(r.format(), '>=1.2.3') + t.end() +}) + test('ranges intersect', (t) => { rangeIntersection.forEach(([r0, r1, expect]) => { t.test(`${r0} <~> ${r1}`, t => {