Skip to content Skip to sidebar Skip to footer

How To Simplify Javascript Program?

I would love to minimize the program. Maybe putting p1-16 in one line of code, same with count and gefunden? Since my language skills are minimal I can't find the right information

Solution 1:

Why not use an array called p?

const p = []
for (let i=1; i<18; i++) {
    p.push(document.getElementById(`pdf${i}`).innerHTML)
}

You can do the same for gefunden and count. The rest of your code, if repetitive, could go in a function and be called in another for loop.

Solution 2:

I agree that this should be on code review. But you have a working code and ask how to make it better. So here you go.

  • replace all those variables that have the format variableN with an array. As soon as you have such a naming format you most of the time either want to use an array or change the name.

  • And you definitely want to clean up that function that searches for the occurrence of the given string.

  • Always define variables using const or let. And add comments to the code.

  • If something reflects a boolean, then use one instead of 0 or 1.

  • Make use of comments, that will also help others when looking at your code (and it also helps you if you look at your code after a while).

  • Use variables instead of magic numbers like 10.

  • and even if your preferred language is not the one used of the programming language, you should stick with the one the programming language use.

So here is a reworked version of your code:

// use an options parameter to make the function more flexiblefunctionsearch(str , options) {
  // destructuring the options into variables const {maxCount, pdfCount} = options;

  const items = [];

  for (let i = 1; i <= pdfCount; i++) {
    items.push({
      p: document.getElementById(`pdf${i}`).innerHTML,
      found: false,
      count: 0
    })
  }

  items.forEach(item => {
    let count = 0;
    let currentPosition = 0; // position where to start searchinglet foundAtPosition;

    // do-while loop to do at least one searchdo {
      foundAtPosition = item.p.indexOf(str, currentPosition);
      
      // check if we found an occurenceif (foundAtPosition != -1) {
        // increase the count
        count++;
        // set the current position after the found occurence
        currentPosition = foundAtPosition + str.length;
      }
      
      // if we found more then maxCount we can leave the loopif (count > maxCount) {
        break;
      }

      // only continue the loop when something was found// you could move "count > maxCount" to the while condition// but the main purpose of the while loop is to iterate over the content
    } while (foundAtPosition != -1);

    // do the composing the information to be set for the item after the for loop, // that makes many things clearer as it is not part of the searching process// set found to true or false by checking if count is larger then 0
    item.found = count > 0;

    
    if (count > maxCount) {
      item.count = `Mehr als ${maxCount}`;
    } else {
      item.count = count;
    }
  })

  return items;
}

console.dir(search('hey', {maxCount: 10, pdfCount: 3}))
<divid="pdf1">
heyheyaaheyaaahey
</div><divid="pdf2">
heyheyaaheyaaahey
heyheyaaheyaaahey
heyheyaaheyaaahey

</div><divid="pdf3">
foo
</div>

You could also utelize str.split([separator[, limit]]) as mention here How to count string occurrence in string? and utilize the limit function.

But if you do that you really need to document the item.p.split(str, maxCount+2).length - 1 construct because that's hard to understand otherwise.

// use an options parameter to make the function more flexiblefunctionsearch(str , options) {
  // destructuring the options into variables const {maxCount, pdfCount} = options;

  const items = [];

  for (let i = 1; i <= pdfCount; i++) {
    items.push({
      p: document.getElementById(`pdf${i}`).innerHTML,
      found: false,
      count: 0
    })
  }

  items.forEach(item => {
    // use maxCount + 2 to figure out if we have more then max count subtract 1 from length to get the actual countconst count = item.p.split(str, maxCount+2).length - 1// set found to true or false by checking if count is larger then 0
    item.found = count > 0;

    if (count > maxCount) {
      item.count = `Mehr als ${maxCount}`;
    } else {
      item.count = count;
    }
  })

  return items;
}

console.dir(search('hey', {maxCount: 10, pdfCount: 3}))
<divid="pdf1">
heyheyaaheyaaahey
</div><divid="pdf2">
heyheyaaheyaaahey
heyheyaaheyaaahey
heyheyaaheyaaahey

</div><divid="pdf3">
foo
</div>

Solution 3:

You can use arrays.

Arrays, in a simple way, put lots of info into one variable. For example:

var this_is_an_array=[0,1,2,3,4,5]

Arrays count from 0 and onwards, so do take note to start counting from 0

More in detail at w3 schools: https://www.w3schools.com/js/js_arrays.asp

Post a Comment for "How To Simplify Javascript Program?"