写一个字符串重复的repeat函数

/**
 * 重复一个字符串指定的次数。
 *
 * @param {string} str 要重复的字符串。
 * @param {number} count 重复的次数。必须是非负整数。
 * @returns {string} 重复后的字符串。如果count为0,返回空字符串。如果count为负数,抛出错误。
 * @throws {RangeError} 如果 count 是负数。
 */
function repeat(str, count) {
  if (count < 0) {
    throw new RangeError("repeat count must be non-negative");
  }

  if (count === 0) {
    return "";
  }

  if (count === 1) {
    return str;
  }

  // 使用更高效的算法处理较大的重复次数
  let result = '';
  let pattern = str;
  while (count > 0) {
    if (count & 1) { // 检查count的最后一位是否为1
      result += pattern;
    }
    count >>= 1; // count右移一位,相当于除以2
    pattern += pattern; // pattern自身拼接,长度翻倍
  }
  return result;
}


// 测试用例
console.log(repeat('abc', 3)); // 输出 'abcabcabc'
console.log(repeat('abc', 0)); // 输出 ''
console.log(repeat('abc', 1)); // 输出 'abc'
console.log(repeat('abc', 5)); // 输出 'abcabcabcabcabc'

try {
  console.log(repeat('abc', -1));
} catch (e) {
  console.error(e); // 输出 RangeError: repeat count must be non-negative
}


// 性能测试 (大型字符串和重复次数)
const longString = 'This is a long string to test performance.';
const repeatCount = 10000;
console.time('repeat');
repeat(longString, repeatCount);
console.timeEnd('repeat');

//  原生String.prototype.repeat() 性能对比 (如果浏览器支持)
if (String.prototype.repeat) {
  console.time('native repeat');
  longString.repeat(repeatCount);
  console.timeEnd('native repeat');
}

代码解释和改进:

  1. 错误处理: 添加了对负数 count 的错误处理,抛出 RangeError,符合规范。

  2. 特殊情况优化:count 为 0 和 1 的情况进行了特殊处理,直接返回空字符串或原始字符串,提高效率。

  3. 高效算法: 使用位运算和字符串拼接的组合,实现更高效的重复逻辑,尤其是在重复次数较大时,性能显著提升。 避免了简单的 for 循环拼接,减少了字符串连接操作的次数。

  4. String.prototype.repeat() 兼容性: 考虑到旧版浏览器可能不支持原生的 String.prototype.repeat() 方法,该函数提供了一个独立的实现,保证了兼容性。 同时,代码中包含了性能测试,可以与原生方法进行对比。

  5. 注释: 添加了详细的 JSDoc 注释,解释函数的功能、参数和返回值,提高代码可读性和可维护性。

使用方法:

直接调用 repeat(str, count) 即可,其中 str 是要重复的字符串,count 是重复次数。

性能对比:

在现代浏览器中,原生 String.prototype.repeat() 方法通常具有最佳性能。 但是,提供的 repeat 函数在不支持原生方法的旧版浏览器中,以及在某些特定场景下,仍然具有竞争力,并且代码清晰易懂,方便维护。

posted @ 2024-11-23 08:52  王铁柱6  阅读(63)  评论(0)    收藏  举报