DEV Community

Discussion on: Daily Challenge #298 - Find the Shortest Word

Collapse
 
alvaromontoro profile image
Alvaro Montoro

Here is a silly answer in the same spirit as the sorting by using time outs. The idea is, instead of trying to calculate/compare sizes, setting a timeout for each word with a delay equal to its length. The timeout callback will show the result and cancel the other timeouts.

Here is the code (demo with the code running on Codepen):

function find_short(str) {
  let timers = {};

  const removeTimers = () => {
    Object.keys(timers).forEach(el => clearTimeout(timers[el]));
  }

  const setTimer = word => {
    timers[word] = setTimeout(
      function() { 
        alert(`The shortest word has ${word.length} characters`);
        removeTimers();
      }, 
      word.length
    );
  };

  str.split(" ").forEach(word => setTimer(word));
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
bugb profile image
bugb • Edited

nice, you are so creative!