Hi!
I am building a simple app that counts words and characters. It is built using vanilla JS.
I need your comments and suggestions for improvement.
You can find it here and the code on github
Thank you!
For further actions, you may consider blocking this person and/or reporting abuse
Mahmud R. Farhan -
Said MOUNAIM -
Daksh Kataria -
Ankush Goyal -
Top comments (4)
Hi, you aren't specific for the kind of suggestions you expect, but here are some:
Dear Florian,
Thank you so much for your comment. I'll try to take them in account.
I am not sure I understand the last point well, can you color it again, please?
I don't know your knowledge about computational complexity (best, worst, average case complexity), so I'll try to be as clear as possible:
Each time the user changes the input, what you do is go through the complete input and count again how many words and characters are in it. To do that, you first split the input. Behind this operation, what's happening? In fact, this function will go character by character and try to match the specified splitter (in your case: a blank space). So as the input grows, the number of steps (and thus: time) it takes will grow linearly. Moreover, it will create a new array of N words.
Then you go through this array N times to verify if it's a word and if it's the case: you increment your counter.
So if you type M characters and have N words, you'll end up doing (at least) M+N operations each time the user changes at least 1 character. As the input grows (and M and N grows), this operation will become more and more expensive in time. This is not optimal and there are many ways to improve it.
You can take a look at the API of the InputEvent (on MDN) to see that there is a selectionStart and selectionEnd property that can help you to know where the input was done and only counting this part.
Tips: You can create a variable to store the current count of characters and another to store the current count of words. Then, you only count from what the input was. If it starts with a blank space and there is a character after it, increment character counter and word counter. If it starts with a character and you have a blank space before it, then increment the characters counter and words counter. If it starts with a character and there is a character before it, only increment the characters counter. For the rest of the input, you should be able to use your existing algorithm to return the number of words and characters in it, and use its result to increment your counters. Doing so, you don't go through the whole text each time, you only go through the newly inputted text.
Dear Florian,
I thank you so much for your time and clarification. You remember me to put in practice the big O notation notion.
I'll try to improve my program.