didYouMean.js.flow 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // @flow strict
  2. const MAX_SUGGESTIONS = 5;
  3. /**
  4. * Given [ A, B, C ] return ' Did you mean A, B, or C?'.
  5. */
  6. declare function didYouMean(suggestions: $ReadOnlyArray<string>): string;
  7. // eslint-disable-next-line no-redeclare
  8. declare function didYouMean(
  9. subMessage: string,
  10. suggestions: $ReadOnlyArray<string>,
  11. ): string;
  12. // eslint-disable-next-line no-redeclare
  13. export default function didYouMean(firstArg, secondArg) {
  14. const [subMessage, suggestionsArg] =
  15. typeof firstArg === 'string'
  16. ? [firstArg, secondArg]
  17. : [undefined, firstArg];
  18. let message = ' Did you mean ';
  19. if (subMessage) {
  20. message += subMessage + ' ';
  21. }
  22. const suggestions = suggestionsArg.map((x) => `"${x}"`);
  23. switch (suggestions.length) {
  24. case 0:
  25. return '';
  26. case 1:
  27. return message + suggestions[0] + '?';
  28. case 2:
  29. return message + suggestions[0] + ' or ' + suggestions[1] + '?';
  30. }
  31. const selected = suggestions.slice(0, MAX_SUGGESTIONS);
  32. const lastItem = selected.pop();
  33. return message + selected.join(', ') + ', or ' + lastItem + '?';
  34. }