Skip to content

Commit 6605c5a

Browse files
author
David Brady
committed
Updated strings/repeating.textile to an AWESOME string repeat idiom thanks to sstephensson on #coffeescript
1 parent e32351a commit 6605c5a

File tree

1 file changed

+4
-19
lines changed

1 file changed

+4
-19
lines changed

chapters/strings/repeating.textile

Lines changed: 4 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -10,32 +10,17 @@ You want to repeat a string.
1010

1111
h2. Solution
1212

13-
Use a map or a list comprehension, and flatten it:
13+
Create an array of n+1 nulls, and then join it with the repetition string as the glue:
1414

1515
{% highlight coffeescript %}
16-
('foo' for dummy in [1..10]).join ''
17-
# => "foofoofoofoofoofoofoofoofoofoo"
18-
19-
([1..10].map (x) -> 'foo').join ''
20-
# => "foofoofoofoofoofoofoofoofoofoo"
21-
{% endhighlight %}
22-
23-
Or a simple (but stateful) loop:
16+
# create a string of 10 foos
17+
Array(11).join('foo')
2418

25-
{% highlight coffeescript %}
26-
repeatString = (str, times) ->
27-
s = ''
28-
while times > 0
29-
s += str
30-
--times
31-
s
32-
33-
repeatString "foo", 10
3419
# => "foofoofoofoofoofoofoofoofoofoo"
3520
{% endhighlight %}
3621

3722
h2. Discussion
3823

39-
JavaScript lacks a string repeat function, as does CoffeeScript. List comprehensions can be pressed into service here, however it remains to be seen if this use is considered idiomatic.
24+
JavaScript lacks a string repeat function, as does CoffeeScript. List comprehensions and maps can be pressed into service here, but in the case of a simple string repeat it's easier to simply build an array of n+1 nulls and then glue them together.
4025

4126

0 commit comments

Comments
 (0)