truncate.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /**
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @format
  8. * @flow
  9. */
  10. 'use strict';
  11. type truncateOptions = {
  12. breakOnWords: boolean,
  13. minDelta: number,
  14. elipsis: string,
  15. ...
  16. };
  17. const defaultOptions = {
  18. breakOnWords: true,
  19. minDelta: 10, // Prevents truncating a tiny bit off the end
  20. elipsis: '...',
  21. };
  22. // maxChars (including ellipsis)
  23. const truncate = function(
  24. str: ?string,
  25. maxChars: number,
  26. options?: truncateOptions,
  27. ): ?string {
  28. options = Object.assign({}, defaultOptions, options);
  29. if (
  30. str &&
  31. str.length &&
  32. str.length - options.minDelta + options.elipsis.length >= maxChars
  33. ) {
  34. // If the slice is happening in the middle of a wide char, add one more char
  35. const extraChar =
  36. str.charCodeAt(maxChars - options.elipsis.length) > 255 ? 1 : 0;
  37. str = str.slice(0, maxChars - options.elipsis.length + 1 + extraChar);
  38. if (options.breakOnWords) {
  39. const ii = Math.max(str.lastIndexOf(' '), str.lastIndexOf('\n'));
  40. str = str.slice(0, ii);
  41. }
  42. str = str.trim() + options.elipsis;
  43. }
  44. return str;
  45. };
  46. module.exports = truncate;