Skip to content

Commit

Permalink
refactor(semver): compute formatted value lazily
Browse files Browse the repository at this point in the history
This improves bench-parse results by up to 40%.

The external interface of the Range class is kept as-is except that the .version property is not writable anymore.
  • Loading branch information
jviide committed Jul 9, 2024
1 parent 9af34d5 commit 266fe0b
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
17 changes: 12 additions & 5 deletions classes/semver.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,20 @@ class SemVer {
}

this.build = m[5] ? m[5].split('.') : []
this.format()
this.formatted = undefined
}

format () {
this.version = `${this.major}.${this.minor}.${this.patch}`
if (this.prerelease.length) {
this.version += `-${this.prerelease.join('.')}`
get version () {
if (this.formatted === undefined) {
this.formatted = `${this.major}.${this.minor}.${this.patch}`
if (this.prerelease.length) {
this.formatted += `-${this.prerelease.join('.')}`
}
}
return this.formatted
}

format () {
return this.version
}

Expand Down Expand Up @@ -291,6 +297,7 @@ class SemVer {
default:
throw new Error(`invalid increment argument: ${release}`)
}
this.formatted = undefined
this.raw = this.format()
if (this.build.length) {
this.raw += `+${this.build.join('.')}`
Expand Down
2 changes: 1 addition & 1 deletion functions/inc.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const inc = (version, release, options, identifier, identifierBase) => {

try {
return new SemVer(
version instanceof SemVer ? version.version : version,
version instanceof SemVer ? version.raw : version,
options
).inc(release, identifier, identifierBase).version
} catch (er) {
Expand Down

0 comments on commit 266fe0b

Please sign in to comment.