didYouMean.js.flow 1017 B

123456789101112131415161718192021222324252627282930313233343536373839
  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, suggestions] =
  15. typeof firstArg === 'string'
  16. ? [firstArg, secondArg]
  17. : [undefined, firstArg];
  18. let message = ' Did you mean ';
  19. if (subMessage) {
  20. message += subMessage + ' ';
  21. }
  22. switch (suggestions.length) {
  23. case 0:
  24. return '';
  25. case 1:
  26. return message + suggestions[0] + '?';
  27. case 2:
  28. return message + suggestions[0] + ' or ' + suggestions[1] + '?';
  29. }
  30. const selected = suggestions.slice(0, MAX_SUGGESTIONS);
  31. const lastItem = selected.pop();
  32. return message + selected.join(', ') + ', or ' + lastItem + '?';
  33. }