_baseRepeat.js 952 B

1234567891011121314151617181920212223242526272829303132333435
  1. /** Used as references for various `Number` constants. */
  2. var MAX_SAFE_INTEGER = 9007199254740991;
  3. /* Built-in method references for those with the same name as other `lodash` methods. */
  4. var nativeFloor = Math.floor;
  5. /**
  6. * The base implementation of `_.repeat` which doesn't coerce arguments.
  7. *
  8. * @private
  9. * @param {string} string The string to repeat.
  10. * @param {number} n The number of times to repeat the string.
  11. * @returns {string} Returns the repeated string.
  12. */
  13. function baseRepeat(string, n) {
  14. var result = '';
  15. if (!string || n < 1 || n > MAX_SAFE_INTEGER) {
  16. return result;
  17. }
  18. // Leverage the exponentiation by squaring algorithm for a faster repeat.
  19. // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
  20. do {
  21. if (n % 2) {
  22. result += string;
  23. }
  24. n = nativeFloor(n / 2);
  25. if (n) {
  26. string += string;
  27. }
  28. } while (n);
  29. return result;
  30. }
  31. module.exports = baseRepeat;