Skip to content

Commit

Permalink
fix(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.

format test
  • Loading branch information
jviide committed Jul 13, 2024
1 parent a9f61b8 commit 3f5ec0b
Show file tree
Hide file tree
Showing 2 changed files with 28 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
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

0 comments on commit 3f5ec0b

Please sign in to comment.