Skip to content

Commit

Permalink
improve string/repeat performance
Browse files Browse the repository at this point in the history
  • Loading branch information
n3okill authored and millermedeiros committed Jan 30, 2014
1 parent 7d4f18a commit ea1c8e7
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 4 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
.project
.settings/
.livereload
.idea

.DS_Store?
ehthumbs.db
Expand Down
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ mout changelog

next
----

- improve `string/repeat` performance.
- add `function/constant`

v0.8.0 (2013/11/22)
Expand Down
16 changes: 14 additions & 2 deletions src/string/repeat.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,23 @@
define(['../lang/toString'], function(toString){
define(['../lang/toString', '../number/toInt'], function(toString, toInt){

/**
* Repeat string n times
*/
function repeat(str, n){
var result = '';
str = toString(str);
return (new Array(n + 1)).join(str);
n = toInt(n);
if (n < 1) {
return '';
}
while (n > 0) {
if (n % 2) {
result += str;
}
n = Math.floor(n / 2);
str += str;
}
return result;
}

return repeat;
Expand Down
4 changes: 3 additions & 1 deletion tests/spec/string/spec-repeat.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ define(['mout/string/repeat'], function (repeat) {
it('should tread undefined as empty string', function(){
expect( repeat(void 0, 1) ).toEqual('');
});

it('should treat "ab" as not a number', function(){
expect( repeat('a','ab') ).toEqual('');
});
});

});

0 comments on commit ea1c8e7

Please sign in to comment.