You are reading a single comment by @zooeyzooey and its replies. Click here to read the full conversation.
  • I might be way off the mark with this, it's a long time since I did anything with JavaScript but does your use of indexof fail when there is only one number in the input string? As cyclotron mentioned an input of "1" and "one" should both produce 11, indexof will only find the first index and you need to also find the last index (which in this case is the same).

  • The short answer is no, it still works.

    The flow is it takes the string, pulls the number (word) or number (int) occurrences out into an object, then organises them into an array in the order they occurred in the original string, and then maps them to the relevant number. Then takes the first and last element of that array and concatenates them together. So 1 will result in an array of ['1'], so concatenating the first and last element of that array together results in 11.

    But ty for the thought.

  • Might require some refactoring, but findIndex and findLastIndex might be useful, as it means you don't need to care about any of the matches in between. Avoids most of the edge cases.

  • I think your problem is here:

    Object.keys(strNumMap).reduce((res, key) => {
      const index = str.indexOf(key);
      if (index > -1) {
        res[key] = index;
      }
      return res;
    }
    

    It's not handling strings with multiple of the same number correctly. E.g. 121 is getting mapped to 12 instead of 11.

About

Avatar for zooeyzooey @zooeyzooey started