# These are my notes from the PragProg book on CoffeeScript of things that either # aren't in the main CS language reference or I didn't pick them up there. I wrote # them down before I forgot, and put it here for others but mainly as a reference for # myself. # assign arguments in constructor to properties of the same name: class Thingie constructor: (@name, @url) -> # is the same as: class Thingie constructor: (name, url) -> @name = name @url = url #execute a function with no arguments: lcword = do str.toLowerCase # is the same as: lcword = str.toLowerCase() # invoke a method on each object in an array (marker.remove()) for marker in @markers for key, value of object # do things with key and value for own key, value of object # do things with object's own properties only for key, value of object when key in ['foo', 'bar', 'baz'] # iterate through properties that meet the when condition # give me an array's values based on a condition: foobar = (value for key, value of object when key in ['foo', 'bar']) for x in [1..100] by 10 # iterate from 1 to 100 in steps of 10 # Call the "process" function on each property of results array that has "food" in the title process result for result in results when _.include(result.title, 'food') # Executing an anonymous function while a condition is met: a = 0 (do -> console.log(a++)) while a<10 (do -> console.log(a--)) until a is 1 # Put the comprehension in parentheses to return it as an array, including only those values that meet the by/when condition: evens = (x for x in [2..10] by 2) => evens = [2,4,6,8,10] # Given an alphabet: alphabet = 'abcdefghijklmnopqrstuvwxyz' # Iterate over part of the alphabet: console.log letter for letter in alphabet[4..8] => Logs 'e' through 'i' to the console # Iterate through the first part of the alphabet, up to e: console.log letter for letter in alphabet[..4] # Stop just before e (notice the 3 dots in the range: console.log letter for letter in alphabet[...4] # Start at e and go to the end alphabet: console.log letter for letter in alphabet[4..] # Useful for pagination: paginate = (start, end) -> @results[start..end] # Just JS but useful to remember: break # stop iterating continue # jump to the next iteration # Iterate using "for" but have each iteration run in closure: for x in arr do (x) -> # do something in own scope