Skip to content

Various updates #37

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 23, 2012
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
More elegant ES3 version to determine the maximum value of an Array
  • Loading branch information
fhemberger committed Feb 23, 2012
commit 7f951c91c717f718de245c978c71f124c5b0d672
8 changes: 3 additions & 5 deletions chapters/arrays/max-array-value.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,20 @@ You need to find the largest value contained in an array.

## Solution

In ECMAScript 5, use `Array#reduce`. In older javascripts, use Math.max over a list comprehension:
In ECMAScript 5, use `Array#reduce`. In older javascripts, use Math.max:

{% highlight coffeescript %}
# ECMAScript 5
[12,32,11,67,1,3].reduce (a,b) -> Math.max a, b
# => 67

# Pre-EC5
max = Math.max(max or= num, num) for num in [12,32,11,67,1,3]
max = Math.max.apply(null, [12,32,11,67,1,3])
# => [ 12, 32, 32, 67, 67, 67 ]
max
# => 67
{% endhighlight %}

## Discussion

`Math.max` compares two numbers and returns the larger of the two; the rest of this recipe (both versions) is just iterating over the array to find the largest one. It is interesting to note that when assigning from a list comprehension, the last item evaluated will be returned to the assignment but the expression itself (such as in the node.js coffeescript interpreter) evaluates to the list comprehension's complete mapping. This means that the Pre-EC5 version will duplicate the array.

For very large arrays in ECMAScript 4, a more memory efficient approach might be to initialize `max` to the first element of the array, and then loop over it with a traditional for loop. Since non-idiomatic CoffeeScript is discouraged in the Cookbook, this approach is left as an exercise to the reader.
`Math.max` compares two numbers and returns the larger of the two; the rest of this recipe (both versions) is just iterating over the array to find the largest one.