Skip to content

Commit

Permalink
Merge pull request #5 from namecheap/perf/remove-regexp
Browse files Browse the repository at this point in the history
perf: replace regex search with indexOf
  • Loading branch information
stas-nc authored Nov 18, 2024
2 parents 7be3e93 + d18cb8a commit 0921230
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions lib/streams/head-injector-stream.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ module.exports = class StringifierStream extends stream.Transform {
: '';

this.__injected = false;
this.__titleRe = /<title>.*<\/title>/is;
}

_transform(chunk, encoding, done) {
Expand All @@ -34,10 +33,18 @@ module.exports = class StringifierStream extends stream.Transform {
let schunk = chunk.toString();
let insertPosStart, insertPosEnd;

const titleMatch = this.__titleRe.exec(schunk);
if (titleMatch !== null) {
insertPosStart = titleMatch.index;
insertPosEnd = insertPosStart + titleMatch[0].length;
const titleMatch = schunk.indexOf('<title>');
if (titleMatch !== -1) {
insertPosStart = titleMatch;
const titleClosingTag = '</title>';
const titleClosingTagIndex = schunk.indexOf(
titleClosingTag,
insertPosStart
);
insertPosEnd =
titleClosingTagIndex !== -1
? titleClosingTagIndex + titleClosingTag.length
: undefined;
} else {
const pos = schunk.indexOf('</head>');
if (pos !== -1) {
Expand All @@ -46,7 +53,7 @@ module.exports = class StringifierStream extends stream.Transform {
}
}

if (insertPosStart !== undefined) {
if (insertPosStart !== undefined && insertPosEnd !== undefined) {
schunk =
schunk.substring(0, insertPosStart) +
this.__title +
Expand Down

0 comments on commit 0921230

Please sign in to comment.