Skip to content

Commit

Permalink
Optimize main.js (#20093)
Browse files Browse the repository at this point in the history
This Pull Request optimizes the functions used in
`/docs/_spec/public/scripts/main.js`.

## Changes made:

1. `currentChapter()` function was simplified using `split()` and
`pop()` instead of `lastIndexOf()` and `substring()`.
2. Used template literals for string interpolation.
3. Simplified the `heading` function by reducing repetitive code and
improving readability.
4. Changed `.removeClass()` and `.addClass()` to `.toggleClass()` for
toggling the class based on condition.
5. General cleanup and optimization for better readability and
performance.
[Cherry-picked 6d29951]
  • Loading branch information
RedYetiDev authored and WojciechMazur committed Jul 6, 2024
1 parent aa18455 commit 94fa4f7
Showing 1 changed file with 13 additions and 20 deletions.
33 changes: 13 additions & 20 deletions docs/_spec/public/scripts/main.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,29 @@
function currentChapter() {
var path = document.location.pathname;
var idx = path.lastIndexOf("/") + 1;
var chap = path.substring(idx, idx + 2);
return parseInt(chap, 10);
return parseInt(document.location.pathname.split('/').pop().substr(0, 2), 10);
}

function heading(i, heading, $heading) {
var currentLevel = parseInt(heading.tagName.substring(1));
var result = "";
const currentLevel = parseInt(heading.tagName.substring(1));

if (currentLevel === this.headerLevel) {
this.headerCounts[this.headerLevel] += 1;
return "" + this.headerCounts[this.headerLevel] + " " + $heading.text();
this.headerCounts[this.headerLevel]++;
} else if (currentLevel < this.headerLevel) {
while(currentLevel < this.headerLevel) {
while (currentLevel < this.headerLevel) {
this.headerCounts[this.headerLevel] = 1;
this.headerLevel -= 1;
this.headerLevel--;
}
this.headerCounts[this.headerLevel] += 1;
return "" + this.headerCounts[this.headerLevel]+ " " + $heading.text();
this.headerCounts[this.headerLevel]++;
} else {
while(currentLevel > this.headerLevel) {
this.headerLevel += 1;
while (currentLevel > this.headerLevel) {
this.headerLevel++;
this.headerCounts[this.headerLevel] = 1;
}
return "" + this.headerCounts[this.headerLevel]+ " " + $heading.text();
}
return `${this.headerCounts[this.headerLevel]} ${$heading.text()}`;
}

// ignore when using wkhtmltopdf, or it won't work...
if(window.jekyllEnv !== 'spec-pdf') {
if (window.jekyllEnv !== 'spec-pdf') {
$('#toc').toc(
{
'selectors': 'h1,h2,h3',
Expand Down Expand Up @@ -64,8 +59,6 @@ document.addEventListener("DOMContentLoaded", function() {
});

$("#chapters a").each(function (index) {
if (document.location.pathname.endsWith($(this).attr("href")))
$(this).addClass("chapter-active");
else
$(this).removeClass("chapter-active");
const href = $(this).attr("href");
$(this).toggleClass("chapter-active", document.location.pathname.endsWith(href));
});

0 comments on commit 94fa4f7

Please sign in to comment.