An open API service indexing awesome lists of open source software.

https://github.com/tmpfs/string-repeater

Repeat a string
https://github.com/tmpfs/string-repeater

Last synced: 10 months ago
JSON representation

Repeat a string

Awesome Lists containing this project

README

          

Table of Contents
=================

* [String Repeat](#string-repeat)
* [Install](#install)
* [Usage](#usage)
* [Benchmark](#benchmark)
* [Source](#source)
* [Developer](#developer)
* [Test](#test)
* [Cover](#cover)
* [Lint](#lint)
* [Clean](#clean)
* [Readme](#readme)

String Repeat
=============

[Build Status](https://travis-ci.org/tmpfs/string-repeater)
[npm version](https://npmjs.org/package/string-repeater)
[Coverage Status](https://coveralls.io/github/tmpfs/string-repeater?branch=master).

Repeat a string.

## Install

```
npm i string-repeater --save
```

## Usage

```javascript
var repeat = require('string-repeater')
, str = repeat('foo ', 7);
// 'foo foo foo foo foo '
```

Or if you prefer to polyfill `String.prototype`:

```javascript
var repeat = require('string-repeater');
String.prototype.repeat = String.prototype.repeat || repeat.impl;
```

## Benchmark

```javascript
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

```javascript
"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 test
```

### Cover

To generate code coverage run:

```
npm run cover
```

### Lint

Run the source tree through [jshint](http://jshint.com) and [jscs](http://jscs.info):

```
npm run lint
```

### Clean

Remove generated files:

```
npm run clean
```

### Readme

To build the readme file from the partial definitions:

```
npm run readme
```

Generated by [mdp(1)](https://github.com/tmpfs/mdp).

[jshint]: http://jshint.com
[jscs]: http://jscs.info