1.0.3 • Published 10 years ago
string-repeater v1.0.3
Table of Contents
String Repeat
Repeat a string.
Install
npm i string-repeater --saveUsage
var repeat = require('string-repeater')
  , str = repeat('foo ', 7);
// 'foo foo foo foo foo 'Or if you prefer to polyfill String.prototype:
var repeat = require('string-repeater');
String.prototype.repeat = String.prototype.repeat || repeat.impl;Benchmark
string-repeater x 4,439,603 ops/sec ±2.15% (85 runs sampled)
string-repeat x 60,621 ops/sec ±4.63% (81 runs sampled)
string.prototype.repeat x 4,071,996 ops/sec ±2.14% (84 runs sampled)Source
"use strict"
/**
 *  Repeat a string.
 *
 *  @param input The string to repeat.
 *  @param times The number of times to repeat.
 *
 *  @return A new repeated string.
 */
function repeat(input, times) {
  return impl.call(input, times);
}
/**
 *  Prototype implementation called with the string as the scope.
 *
 *  Note that this implementation:
 *
 *  return new Array(Math.abs(times) + 1).join(this);
 *
 *  Is very, very slow.
 *
 *  This implementation:
 *
 *  var ret = '';
 *  for(var i = 0; i < times; i++) {
 *    ret += this;
 *  }
 *  return ret;
 *
 *  Is faster than `string-repeat` but slower than `string.prototype.repeat`.
 *
 *  @param times The number of times to repeat.
 *
 *  @return A new repeated string.
 */
function impl(times) {
  // conditional is faster than Math.abs()
  var n = times < 0 ? -times : times
    , result = ''
    , string = '' + this;
  // optimized loop from string.prototype.repeat
  while(n) {
    if(n % 2 === 1) {
      result += string;
    }
    if(n > 1) {
      string += string;
    }
    n >>= 1;
  }
  return result;
}
repeat.impl = impl;
module.exports = repeat;Developer
Test
To run the test suite:
npm testCover
To generate code coverage run:
npm run coverLint
Run the source tree through jshint and jscs:
npm run lintClean
Remove generated files:
npm run cleanReadme
To build the readme file from the partial definitions:
npm run readmeGenerated by mdp(1).