Skip to content

Commit

Permalink
refactor(range): compute formatted value lazily
Browse files Browse the repository at this point in the history
This speeds bench-subset and bench-satisfies by up to 9%.

The external interface of the Range class is kept as-is except that the .range property is not writable anymore.
  • Loading branch information
jviide committed Jul 9, 2024
1 parent 3a88718 commit 9af34d5
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 13 deletions.
32 changes: 19 additions & 13 deletions classes/range.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,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 Down Expand Up @@ -65,23 +65,29 @@ class Range {
}
}

this.format()
this.formatted = undefined
}

format () {
this.range = ''
for (let i = 0; i < this.set.length; i++) {
if (i > 0) {
this.range += '||'
}
const comps = this.set[i]
for (let k = 0; k < comps.length; k++) {
if (k > 0) {
this.range += ' '
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()
}
this.range += comps[k].toString().trim()
}
}
return this.formatted
}

format () {
return this.range
}

Expand Down
7 changes: 7 additions & 0 deletions test/classes/range.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,13 @@ test('tostrings', (t) => {
t.end()
})

test('format', (t) => {
const r = new Range('>= v1.2.3')
t.equal(r.format(), '>=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

0 comments on commit 9af34d5

Please sign in to comment.