Skip to content

Commit

Permalink
perf: faster memoOpts for range
Browse files Browse the repository at this point in the history
  • Loading branch information
H4ad committed Mar 31, 2023
1 parent ca185a0 commit 2cea1a4
Showing 1 changed file with 41 additions and 3 deletions.
44 changes: 41 additions & 3 deletions classes/range.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class Range {
this.set = range
.split('||')
// map the range to a 2d array of comparators
.map(r => this.parseRange(r.trim()))
.map(r => this.parseRange(r))
// throw out any comparator lists that are empty
// this generally means that it was not a valid range, which is allowed
// in loose mode, but will still throw if the WHOLE range is invalid.
Expand Down Expand Up @@ -81,8 +81,8 @@ class Range {

// memoize range parsing for performance.
// this is a very hot path, and fully deterministic.
const memoOpts = Object.keys(this.options).join(',')
const memoKey = `parseRange:${memoOpts}:${range}`
const memoOpts = buildMemoKeyFromOptions(this.options)
const memoKey = memoOpts + range
const cached = cache.get(memoKey)
if (cached) {
return cached
Expand Down Expand Up @@ -190,6 +190,44 @@ class Range {
return false
}
}

const memoKeyAllOpts = '1';
const memoKeyPreReleaseAndLooseOpts = '2';
const memoKeyPreReleaseAndRtlOpts = '3';
const memoKeyPreReleaseOpts = '4';
const memoKeyLooseAndRtlOpts = '5';
const memoKeyLooseOpts = '6';
const memoKeyRtlOpts = '7';
const memoKeyEmptyOpts = '8';

function buildMemoKeyFromOptions(options) {
if (options.includePrerelease === true) {
if (options.loose === true && options.rtl === true) {
return memoKeyAllOpts;
}

if (options.loose === true) {
return memoKeyPreReleaseAndLooseOpts;
}

if (options.rtl === true) {
return memoKeyPreReleaseAndRtlOpts;
}

return memoKeyPreReleaseOpts;
} else if (options.loose === true) {
if (options.rtl === true) {
return memoKeyLooseAndRtlOpts;
}

return memoKeyLooseOpts;
} else if (options.rtl === true) {
return memoKeyRtlOpts;
} else {
return memoKeyEmptyOpts;
}
}

module.exports = Range

const LRU = require('lru-cache')
Expand Down

0 comments on commit 2cea1a4

Please sign in to comment.