New recipes: Using arrays to swap variable, splitting a string #15

Merged
merged 2 commits into from Jun 13, 2011
Jump to file or symbol
Failed to load files and symbols.
+89 −2
Split
@@ -0,0 +1,52 @@
+---
+layout: recipe
+title: Using Arrays to Swap Variables
+chapter: Arrays
+---
+
+h1. Using Arrays to Swap Variables
+
+h2. Problem
+
+You want to use an array to swap variables.
+
+h2. Solution
+
+Use CoffeeScript's "destructuring assignment":http://jashkenas.github.com/coffee-script/#destructuring syntax:
+
+{% highlight coffeescript %}
+a = 1
+b = 3
+
+[a, b] = [b, a]
+
+a
+# => 3
+
+b
+# => 1
+{% endhighlight %}
+
+
+h2. Discussion
+
+Destructuring assignment allows swapping two values without the use of a temporary variable.
+
+This can be useful when traversing arrays and ensuring iteration only happens over the shortest one:
+
+{% highlight coffeescript %}
+
+ray1 = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
+ray2 = [ 5, 9, 14, 20 ]
+
+intersection = (a, b) ->
+ [a, b] = [b, a] if a.length > b.length
+ value for value in a when value in b
+
+intersection ray1, ray2
+# => [ 5, 9 ]
+
+intersection ray2, ray1
+# => [ 5, 9 ]
+
+{% endhighlight %}
@@ -0,0 +1,37 @@
+---
+layout: recipe
+title: Splitting a String
+chapter: Strings
+---
+
+h2. Problem
+
+You want to split a string.
+
+h2. Solution
+
+Use JavaScript's String split() method:
+
+{% highlight coffeescript %}
+"foo bar baz".split " "
+# => [ 'foo', 'bar', 'baz' ]
+{% endhighlight %}
+
+h2. Discussion
+
+String's split() is a standard JavaScript method. It can be used to split a string on any delimiter, including regular expressions. It also accepts a second parameter that specifies the number of splits to return.
+
+{% highlight coffeescript %}
+"foo-bar-baz".split "-"
+# => [ 'foo', 'bar', 'baz' ]
+{% endhighlight %}
+
+{% highlight coffeescript %}
+"foo bar \t baz".split /\s+/
+# => [ 'foo', 'bar', 'baz' ]
+{% endhighlight %}
+
+{% highlight coffeescript %}
+"the sun goes down and I sit on the old broken-down river pier".split " ", 2
+# => [ 'the', 'sun' ]
+{% endhighlight %}
View
@@ -18,7 +18,6 @@ h2. Objects
h2. Strings
* HTML methods # JS .sup(), .sub(), .blink(), .link(url), etc. May not exist in your JS impl!
-* Splitting a string # JS "foo bar baz".split ' ' # => [ 'foo', 'bar', 'baz' ]
* substr # str.substr(x,y) === str[x..x+y-1] === str[x...x+y]
* substring # str.substring(x,y) === str.slice(x,y) === str[x..y-1] === str[x...y]
* Uppercasing a string # JS toUpperCase()
@@ -28,7 +27,6 @@ h2. Strings
h2. Arrays
-* Using Arrays to Swap Variables # [x,y] = [y,x]
* Reducing arrays to values (ruby inject) with reduce # [1..10].reduce (a,b) -> a+b # 55
* Reducing arrays in reverse order # JS reduceRight
{% highlight coffeescript %}