mirror of
https://github.com/jashkenas/coffeescript.git
synced 2022-11-09 12:23:24 -05:00
Optimized repeat
and its tests
This commit is contained in:
parent
fbc8417263
commit
1db89d1589
3 changed files with 29 additions and 5 deletions
|
@ -12,8 +12,17 @@
|
|||
return literal === string.substr(string.length - len - (back || 0), len);
|
||||
};
|
||||
|
||||
exports.repeat = function(string, n) {
|
||||
return (Array(n + 1)).join(string);
|
||||
exports.repeat = function(str, n) {
|
||||
var res;
|
||||
res = '';
|
||||
while (n > 0) {
|
||||
if (n & 1) {
|
||||
res += str;
|
||||
}
|
||||
n >>>= 1;
|
||||
str += str;
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
exports.compact = function(array) {
|
||||
|
|
|
@ -12,8 +12,14 @@ exports.ends = (string, literal, back) ->
|
|||
literal is string.substr string.length - len - (back or 0), len
|
||||
|
||||
# Repeat a string `n` times.
|
||||
exports.repeat = (string, n) ->
|
||||
(Array n + 1).join string
|
||||
exports.repeat = (str, n) ->
|
||||
# Use clever algorithm to have O(lon(n)) string concatenation operations
|
||||
res = ''
|
||||
while n > 0
|
||||
res += str if n & 1
|
||||
n >>>= 1
|
||||
str += str
|
||||
res
|
||||
|
||||
# Trim out all falsy values from an array.
|
||||
exports.compact = (array) ->
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
# -------
|
||||
|
||||
# pull the helpers from `CoffeeScript.helpers` into local variables
|
||||
{starts, ends, compact, count, merge, extend, flatten, del, last} = CoffeeScript.helpers
|
||||
{starts, ends, repeat, compact, count, merge, extend, flatten, del, last} = CoffeeScript.helpers
|
||||
|
||||
|
||||
# `starts`
|
||||
|
@ -27,6 +27,15 @@ test "the `ends` helper can take an optional offset", ->
|
|||
ok not ends('01234', '234', 6)
|
||||
|
||||
|
||||
# `repeat`
|
||||
|
||||
test "the `repeat` helper concatenates a given number of times", ->
|
||||
eq 'asdasdasd', repeat('asd', 3)
|
||||
|
||||
test "`repeat`ing a string 0 times always returns the empty string", ->
|
||||
eq '', repeat('whatever', 0)
|
||||
|
||||
|
||||
# `compact`
|
||||
|
||||
test "the `compact` helper removes falsey values from an array, preserves truthy ones", ->
|
||||
|
|
Loading…
Add table
Reference in a new issue