M
M
MaximPatrushev2019-05-06 17:05:15
JavaScript
MaximPatrushev, 2019-05-06 17:05:15

How to optimize and increase the scalability of a particular example of javascript code?

In general, the task is to render a reactive table of contents for the contents of the WYSIWYG editor.
I use React as a JS framework and ckeditor as an editor. The task was to do the following - when filling the editor with content, headings 1-3 levels are parsed and reactively displayed as a table of contents next to the editor window. At the same time, the items in this table of contents should be clickable - on click, the editor window should scroll to the corresponding title. Available plugins only allow you to display a table with a table of contents, but do not make its elements clickable.
I solved the problem, but it seems to me that my code is very clumsy and does not scale well.
Link to the sandbox with an example
Suppose, if the conditions of the task change and it will be necessary to parse the headings of levels 1-6, then my code will grow by 2 times. I tried to find a more elegant solution using recursions at these points:

while (currentEl !== null) {
      if (currentEl.tagName === 'H1') {
        h1Array.push({
          text: currentEl.innerHTML,
          h2Array: []
        });
        i++;
        j = 0;
      } else if (currentEl.tagName === 'H2') {
        h1Array[i-1].h2Array.push({
          text: currentEl.innerHTML,
          h3Array: []
        });
        j++;
      } else if (currentEl.tagName === 'H3') {
        h1Array[i-1].h2Array[j-1].h3Array.push({
          text: currentEl.innerHTML
        });
      }

      currentEl = currentEl.nextElementSibling;
    }

and
// finding closest h2 tag
    let h2El = h1El.nextElementSibling;
    let i = 0;
    while (i <= +h2Index) {
      if (h2El.tagName === 'H2') {
        if (i === +h2Index) {
          break
        } else i++;
      }
      h2El = h2El.nextElementSibling;
    }

    // finding h3 tag
    let h3El = h2El.nextElementSibling;
    let j = 0;
    while (j <= +h3Index) {
      if (h3El.tagName === 'H3') {
        if (j === +h3Index) {
          break
        } else j++;
      }
      h3El = h3El.nextElementSibling;
    }

but I didn’t succeed, I just got completely confused and blew my brain. If anyone can at least suggest a direction in which to think - I will be grateful)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-05-06
@MaximPatrushev

https://codesandbox.io/s/jm6z4o0vy

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question