模拟实现repeat的实现原理

普通的实现

累加n次初始值

String.prototype.nRepeat = function(count){
    let str = this.valueOf();
    let res = '';
    while(count > 0){
        res =res + str;
        count--;
    }
}

优化方案

思路:每次以2的幂次方来判断,累加的初始值是否更新为之前的2倍数

String.prototype.myRepeat = function(num){
    let str = this.valueOf();
    if(num === 0) return '';
    if(num === 1) return str;
    while(num > 0){
        if(num % 2 !=0){ // 为奇数则先加一遍初始值
            string += str;
        }
        num =  Math.floor(num/2); // 然后把需要叠加的次数
        str += str;  // 更新初始值
    }
    return string
}
原文地址:https://www.cnblogs.com/jwenming/p/14579069.html