Skip to content

Commit 3a480e4

Browse files
perf: check hljs is not null only once
Update the `highlightCode` method of `Diff2HtmlUI` to check if the hljs reference is null only once (at the start). This address the "HACK" comments by using a locally scoped variable for hljs. This way, TypeScript is able to deduce that, after the initial null-check, hljs is in fact not null.
1 parent 6db4aae commit 3a480e4

1 file changed

Lines changed: 3 additions & 8 deletions

File tree

src/ui/js/diff2html-ui-base.ts

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -137,16 +137,14 @@ export class Diff2HtmlUI {
137137
}
138138

139139
highlightCode(): void {
140-
if (this.hljs === null) {
140+
const hljs = this.hljs;
141+
if (hljs === null) {
141142
throw new Error('Missing a `highlight.js` implementation. Please provide one when instantiating Diff2HtmlUI.');
142143
}
143144

144145
// Collect all the diff files and execute the highlight on their lines
145146
const files = this.targetElement.querySelectorAll('.d2h-file-wrapper');
146147
files.forEach(file => {
147-
// HACK: help Typescript know that `this.hljs` is defined since we already checked it
148-
if (this.hljs === null) return;
149-
150148
const language = file.getAttribute('data-lang');
151149

152150
if (!(this.config.highlightLanguages instanceof Map)) {
@@ -164,16 +162,13 @@ export class Diff2HtmlUI {
164162
// Collect all the code lines and execute the highlight on them
165163
const codeLines = file.querySelectorAll('.d2h-code-line-ctn');
166164
codeLines.forEach(line => {
167-
// HACK: help Typescript know that `this.hljs` is defined since we already checked it
168-
if (this.hljs === null) return;
169-
170165
const text = line.textContent;
171166
const lineParent = line.parentNode;
172167

173168
if (text === null || lineParent === null || !this.isElement(lineParent)) return;
174169

175170
const result: HighlightResult = closeTags(
176-
this.hljs.highlight(text, {
171+
hljs.highlight(text, {
177172
language: hljsLanguage,
178173
ignoreIllegals: true,
179174
}),

0 commit comments

Comments
 (0)