From 3a480e4ab0a7c8b0a5d52f8cb7e7aa6d26e58e67 Mon Sep 17 00:00:00 2001 From: Eric Cornelissen Date: Wed, 2 Nov 2022 22:43:23 +0100 Subject: [PATCH] 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. --- src/ui/js/diff2html-ui-base.ts | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/src/ui/js/diff2html-ui-base.ts b/src/ui/js/diff2html-ui-base.ts index b25e209..9b2317f 100644 --- a/src/ui/js/diff2html-ui-base.ts +++ b/src/ui/js/diff2html-ui-base.ts @@ -137,16 +137,14 @@ export class Diff2HtmlUI { } highlightCode(): void { - if (this.hljs === null) { + const hljs = this.hljs; + if (hljs === null) { throw new Error('Missing a `highlight.js` implementation. Please provide one when instantiating Diff2HtmlUI.'); } // Collect all the diff files and execute the highlight on their lines const files = this.targetElement.querySelectorAll('.d2h-file-wrapper'); files.forEach(file => { - // HACK: help Typescript know that `this.hljs` is defined since we already checked it - if (this.hljs === null) return; - const language = file.getAttribute('data-lang'); if (!(this.config.highlightLanguages instanceof Map)) { @@ -164,16 +162,13 @@ export class Diff2HtmlUI { // Collect all the code lines and execute the highlight on them const codeLines = file.querySelectorAll('.d2h-code-line-ctn'); codeLines.forEach(line => { - // HACK: help Typescript know that `this.hljs` is defined since we already checked it - if (this.hljs === null) return; - const text = line.textContent; const lineParent = line.parentNode; if (text === null || lineParent === null || !this.isElement(lineParent)) return; const result: HighlightResult = closeTags( - this.hljs.highlight(text, { + hljs.highlight(text, { language: hljsLanguage, ignoreIllegals: true, }),