voca
Version:
The ultimate JavaScript string library
47 lines (38 loc) • 1.07 kB
JavaScript
;
var is_nil = require('./internal/is_nil.js');
require('./is_string.js');
var coerce_to_string = require('./internal/coerce_to_string.js');
var to_integer = require('./internal/to_integer.js');
/**
* Repeats the `subject` number of `times`.
*
* @function repeat
* @static
* @since 1.0.0
* @memberOf Manipulate
* @param {string} [subject=''] The string to repeat.
* @param {number} [times=1] The number of times to repeat.
* @return {string} Returns the repeated string.
* @example
* v.repeat('w', 3);
* // => 'www'
*
* v.repeat('world', 0);
* // => ''
*/
function repeat(subject, times) {
var subjectString = coerce_to_string.coerceToString(subject);
var timesInt = is_nil.isNil(times) ? 1 : to_integer.clipNumber(to_integer.toInteger(times), 0, to_integer.MAX_SAFE_INTEGER);
var repeatString = '';
while (timesInt) {
if (timesInt & 1) {
repeatString += subjectString;
}
if (timesInt > 1) {
subjectString += subjectString;
}
timesInt >>= 1;
}
return repeatString;
}
module.exports = repeat;