From 750428379b17c4b9be599004d79250210ca06c45 Mon Sep 17 00:00:00 2001 From: Joachim Viide Date: Sun, 7 Jul 2024 02:27:16 +0000 Subject: [PATCH] refactor(semver): compute formatted value lazily 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. --- classes/semver.js | 17 ++++++++++++----- functions/inc.js | 2 +- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/classes/semver.js b/classes/semver.js index 13e66ce4..ca89012b 100644 --- a/classes/semver.js +++ b/classes/semver.js @@ -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 } @@ -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('.')}` diff --git a/functions/inc.js b/functions/inc.js index 7670b1be..73f3822e 100644 --- a/functions/inc.js +++ b/functions/inc.js @@ -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) {