Skip to content

Commit

Permalink
feat: add String.prototype.count
Browse files Browse the repository at this point in the history
  • Loading branch information
medikoo committed May 9, 2017
1 parent 5109192 commit 2e53241
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
17 changes: 17 additions & 0 deletions string/#/count.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
'use strict';

var ensureString = require('../../object/validate-stringifiable-value');

module.exports = function (search) {
var string = ensureString(this), count = 0, index = 0;

search = ensureString(search);
if (!search) throw new TypeError("Search string cannot be empty");
while (true) {
index = string.indexOf(search, index);
if (index === -1) break;
++count;
index += search.length;
}
return count;
};
1 change: 1 addition & 0 deletions string/#/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
module.exports = {
'@@iterator': require('./@@iterator'),
at: require('./at'),
count: require('./count'),
camelToHyphen: require('./camel-to-hyphen'),
capitalize: require('./capitalize'),
caseInsensitiveCompare: require('./case-insensitive-compare'),
Expand Down
14 changes: 14 additions & 0 deletions test/string/#/count.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
'use strict';

module.exports = function (t, a) {
a.throws(function () {
t.call('', '');
});
a(t.call('x', 'x'), 1);
a(t.call('xx', 'x'), 2);
a(t.call('xxx', 'xx'), 1);
a(t.call('xxxx', 'xx'), 2);
a(t.call('xx', 'xxx'), 0);
a(t.call('', 'elo'), 0);
a(t.call('fooo', 'foofooo'), 0);
};

0 comments on commit 2e53241

Please sign in to comment.