A deep dive in the Vue.js source code (#14): the repeat function

If you are just joining, this is the 14th post in a series going over the entire Vue.js source code line by line. In the last post, we landed on the repeat function in the midst of the return statement for the generateComponentTrace function. In this post, we examine the repeat function:

var repeat = function (str, n) {
var res = '';
while (n) {
if (n % 2 === 1) { res += str; }
if (n > 1) { str += str; }
n >>= 1;
}
return res
};

The repeat function takes a string and number as parameters:

(str, n)

A result variable — res — is set to an empty string:

var res = '';

And the repeat function then loops while the passed n parameter is not 0:

while (n) {
if (n % 2 === 1) { res += str; }
if (n > 1) { str += str; }
n >>= 1;
}

If the remainder after dividing the number (n) by 2 is 1, res is concatenated withstr:

while (n) {
if (n % 2 === 1) { res += str; }
if (n > 1) { str += str; }
n >>= 1;
}

If the number is greater than 1, str is doubled/repeated:

while (n) {
if (n % 2 === 1) { res += str; }
if (n > 1) { str += str; }
n >>= 1;
}

n is then right shift assigned 1:

n >>= 1;

Right shift assignment “moves the specified amount of bits to the right and assigns the result to the variable.”

After the loop exits, the repeat function returns res:

return res

In the next post, we will turn back to the generateComponentTrace function and see how the repeat function plays out there.

Next Post: