diff --git a/.travis.yml b/.travis.yml index 8acd460..0300130 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,7 +5,3 @@ os: language: node_js node_js: - node - - '6' - - '4' - - '0.12' - - '0.10' diff --git a/index.js b/index.js index 4459afd..ad09b18 100644 --- a/index.js +++ b/index.js @@ -43,11 +43,19 @@ function repeat(str, num) { throw new TypeError('expected a string'); } + // no need to repeat an empty string + if (str === '') return ''; + // cover common, quick use cases if (num === 1) return str; if (num === 2) return str + str; var max = str.length * num; + + if (max === Infinity) { + throw new TypeError('cannot repeat indefinitely'); + } + if (cache !== str || typeof cache === 'undefined') { cache = str; res = ''; diff --git a/package.json b/package.json index fc0d190..cb77aaf 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,7 @@ "benchmarked": "^0.2.5", "gulp-format-md": "^0.1.11", "isobject": "^2.1.0", - "mocha": "^3.1.2", + "mocha": "^8.3.2", "repeating": "^3.0.0", "text-table": "^0.2.0", "yargs-parser": "^4.0.2" @@ -74,4 +74,4 @@ "verb" ] } -} \ No newline at end of file +} diff --git a/test.js b/test.js index a1249d3..d2c9563 100644 --- a/test.js +++ b/test.js @@ -8,8 +8,9 @@ 'use strict'; require('mocha'); -var assert = require('assert'); -var repeat = require('./'); +const assert = require('assert'); +const { it } = require('mocha'); +const repeat = require('./'); describe('repeat', function() { it('should return an empty string when a number is not given:', function() { @@ -23,6 +24,18 @@ describe('repeat', function() { assert.equal(repeat('a', null), ''); }); + it('shoud not round numbers:', function() { + assert.equal(repeat('A', 6.9), repeat('A', 6)); + assert.equal(repeat('A', '6.9'), repeat('A', 6)); + }); + + it('should return an empty string for negative numbers:', function () { + assert.equal(repeat('A', -42), ''); + assert.equal(repeat('A', '-42'), ''); + assert.equal(repeat('A', -Infinity), ''); + assert.equal(repeat('A', '-Infinity'), ''); + }); + it('should repeat the given string n times', function() { assert.equal(repeat(' ', 0), ''); assert.equal(repeat('a', 0), ''); @@ -59,4 +72,11 @@ describe('repeat', function() { assert.throws(function() {repeat(10); }, /expected a string/); assert.throws(function() {repeat(null); }, /expected a string/); }); + + it('should throw an error when attempting to repeat ad infinitum', function () { + assert.throws(function () { repeat('foo', Infinity); }); + assert.throws(function () { repeat('foo', 'Infinity'); }); + assert.doesNotThrow(function () { repeat('foo', -Infinity); }); + assert.doesNotThrow(function () { repeat('foo', '-Infinity'); }); + }); });