DEV Community

Discussion on: React.js - Interview Question - duplicate hashtag remover.

Collapse
 
samselfridge profile image
samselfridge • Edited

You're calling set state for every new duplicate item, maybe react will batch this and save you, but don't count on it. You're better off initalizing a new array, pushing duplicates on to it then calling setState 1 time at the end.

  const findDuplicateTags = () => {
    let tagsMap = new Map();
    const duplicates = [];
    hashtags.split(" ").forEach((tag) => {
      tag = tag.trim();
      if (tag) {
        if (tagsMap.has(tag)) {
          duplicates.push(tag);
        } else {
          tagsMap.set(tag, 0);
        }
      }
    });
    setDuplicates(duplicates);
  };
Enter fullscreen mode Exit fullscreen mode

Other things to note:

  • This doesn't check for # as a tag so it would delete duplicate words
  • Doesn't handle additional whitespace, look at String.trim()

Nice use of Map. Not bad for a interview but that repeated setState will absolutely destroy your apps performance and due to the async nature of setState could even get you into unpredictable behavior.

Collapse
 
rajeshroyal profile image
Rajesh Royal

hehe true I should have used this method. But there were many factors - and the biggest one was time bounding and it makes person nervous. I will be keeping it in mind.
Thank you.