From c2636cc3455f779eed89ca7ab66f9f81b2b1a3a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o?= Date: Sun, 19 Jun 2011 20:17:37 +0200 Subject: [PATCH] Added Reducing Arrays recipe --- chapters/arrays/reducing-arrays.textile | 43 +++++++++++++++++++++++++ wanted-recipes.textile | 6 ---- 2 files changed, 43 insertions(+), 6 deletions(-) create mode 100644 chapters/arrays/reducing-arrays.textile diff --git a/chapters/arrays/reducing-arrays.textile b/chapters/arrays/reducing-arrays.textile new file mode 100644 index 0000000..2f43560 --- /dev/null +++ b/chapters/arrays/reducing-arrays.textile @@ -0,0 +1,43 @@ +--- +layout: recipe +title: Reducing Arrays +chapter: Arrays +--- + +h2. Problem + +You have an array of objects and want to reduce them to a value, similar to Ruby's reduce() and reduceRight(). + +h2. Solution + +You can simply use Array's reduce() and reduceRight() methods along with an anonoymous function, keeping the code clean and readable. The reduction may be something simple such as using the + operator with numbers or strings. + +{% highlight coffeescript %} +[1,2,3,4].reduce (x,y) -> x + y +# => 10 +{% endhighlight %} + +{% highlight coffeescript %} +["words", "of", "bunch", "A"].reduceRight (x, y) -> x + " " + y +# => 'A bunch of words' +{% endhighlight %} + +Or it may be something more complex such as aggregating elements from a list into a combined object. + +{% highlight coffeescript %} +people = + { name: '', age: 10 } + { name: '', age: 16 } + { name: '', age: 17 } + +people.reduce (x, y) -> + x[y.name]= y.age + x +, {} +# => { alec: 10, bert: 16, chad: 17 } +{% endhighlight %} + +h2. Discussion + +Javascript introduced reduce and reduceRight in version 1.8. Coffeescript provides a natural and simple way to express anonymous functions. Both go together cleanly in the problem of merging a collection's items into a combined result. + diff --git a/wanted-recipes.textile b/wanted-recipes.textile index 994cf6b..33a3cd5 100644 --- a/wanted-recipes.textile +++ b/wanted-recipes.textile @@ -26,12 +26,6 @@ h2. Strings h2. Arrays -* 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 %} -["example", "contrived ", "pretty ", "a ", "is ", "here "].reduceRight (x,y) -> x+y -# => 'here is a pretty contrived example' -{% endhighlight %} * Testing every element in an array {% highlight coffeescript %} evens = (x for x in [0..10] by 2)