-
Notifications
You must be signed in to change notification settings - Fork 135
Expand file tree
/
Copy pathrepeat.js
More file actions
38 lines (37 loc) · 1.03 KB
/
Copy pathrepeat.js
File metadata and controls
38 lines (37 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import clipNumber from 'helper/number/clip_number';
import coerceToString from 'helper/string/coerce_to_string';
import isNil from 'helper/object/is_nil';
import { MAX_SAFE_INTEGER } from 'helper/number/const';
import toInteger from 'helper/number/to_integer';
/**
* 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);
* // => ''
*/
export default function repeat(subject, times) {
let subjectString = coerceToString(subject);
let timesInt = isNil(times) ? 1 : clipNumber(toInteger(times), 0, MAX_SAFE_INTEGER);
let repeatString = '';
while (timesInt) {
if (timesInt & 1) {
repeatString += subjectString;
}
if (timesInt > 1) {
subjectString += subjectString;
}
timesInt >>= 1;
}
return repeatString;
}