Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: optimize Range parsing and formatting #726

Merged
merged 3 commits into from
Jul 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 24 additions & 10 deletions classes/range.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
const SPACE_CHARACTERS = /\s+/g
wraithgar marked this conversation as resolved.
Show resolved Hide resolved

// hoisted class for cyclic dependency
class Range {
constructor (range, options) {
Expand All @@ -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
}

Expand All @@ -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.
jviide marked this conversation as resolved.
Show resolved Hide resolved
this.raw = range
.trim()
.split(/\s+/)
.join(' ')
this.raw = range.trim().replace(SPACE_CHARACTERS, ' ')

// First, split on ||
this.set = this.raw
Expand Down Expand Up @@ -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
}

Expand Down
9 changes: 9 additions & 0 deletions test/classes/range.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {
Expand Down