CoffeeScript Ranges, Loops and Comprehensions

by ctoestreich

HTML

<script src="http://codemirror.net/lib/codemirror.js"></script>
<link rel="stylesheet" href="http://codemirror.net/lib/codemirror.css">
<script src="http://codemirror.net/mode/javascript/javascript.js"></script>
<script type="text/javascript">$.get('http://fiddle.jshell.net/bh88/SKMpV/show/',function(){$('#code').val(CoffeeScript.compile($('script[type*=coffeescript]').html()));var editor=CodeMirror.fromTextArea(document.getElementById('code'),{lineNumbers:1,matchBrackets:1,mode:'javascript'});});</script><textarea id="code"></textarea>

CSS

/* here's that gist btw https://gist.github.com/1293230 */

#code {
    display: none;
}

.CodeMirror-scroll {
    height: 100% !important;            
}

CoffeeScript

### See: http://jsfiddle.net/ctoestreich/zqC8E/ ###

### Iterate a list ###
favoritePodcasts = ['Astronomy Cast', 'Hardcore History',
  'Talking Shop Down Under', 'Pluralcast']

for podcast in favoritePodcasts
  console.log podcast

### Iterating over maps (key value pairs) ###
podcastsMap =
    'Astronomy Cast': 'http://www.astronomycast.com/',
    'Hardcore History': 'http://www.dancarlin.com/disp.php/hh',
    'Talking Shop Down Under': 'http://www.talkingshopdownunder.com/',
    'Pluralcast': 'http://www.pluralsight-training.net/microsoft/pluralcast/default.aspx'

for key, value of podcastsMap
  console.log key + ' - ' + value

### Conditional processing of data in loops ###
for number in [1..10] when number > 5
  console.log number        # Outputs '6, 7, 8, 9, 10'


### dealing with ranges ###
numbers = [1..10]
console.log numbers

reverseNumbers = [10..1]
console.log reverseNumbers

###
Comprehensions replace (and compile into) for loops, with optional guard clauses and the
value of the current array index. Unlike for loops, array comprehensions
are expressions, and can be returned and assigned.
###
foods = ['broccoli', 'spinach', 'chocolate']
console.log food for food in foods when food isnt 'chocolate'

evenNumbers = (number for number in [1..10] when number % 2 is 0)
console.log evenNumbers        # Outputs [ 2, 4, 6, 8, 10 ]

# same as above as a function call
evenNumbers = () ->
  number for number in [1..10] when number % 2 is 0
console.log evenNumbers()        # Outputs [ 2, 4, 6, 8, 10 ]