Array snippets
Use join
to convert an array into a string. It takes a string to use as the joining text between each item
['James ', 'Bond'].join '-'
Use slice
to extract part of an array:
['good', 'bad', 'ugly'].slice 0, 2
Use concat
to join two arrays together
['a', 'b'].concat ['c', 'd', 'z']
In CoffeeScript the in
operator has particular meaning for arrays. In JavaScript the in
operator is used for objects, but in CoffeeScript it’s used for arrays (the of
operator is used for objects).
Use in
to determine if an array contains a particular value:
'to be' in ['to be', 'not to be']
Array comprehensions allow you to evaluate an expression for each item in an array
number for number in [9,0,2,1,0] # [9,0,2,1,0]
Use by
to perform an array comprehension in jumps
days = [0..23] sleep = (hour) -> "Sleeping at #{hour}" sleep hour for hour in days by 6 # [ 'Sleeping at 0','Sleeping at 6','Sleeping at 12','Sleeping at 18' ]
Object snippets
If you want to check if an object contains a property, use the of
operator
'title' of objBook # true
The property names of an object are returned as an array using a comprehension
name for name of {bob: 152, john: 139, tracy: 209} # ['bob', 'john', 'tracy']
To get the property values from an object instead of the property names, use a slightly different comprehension format
value for property, value of object # example score for name, score
Suppose an object doesn’t yet have any properties. The long way to check it is to first use the existential operator to see if it exists, and then initialize it if it doesn’t:
if !objBook['author']? objBook['author'] = 'William Shakespeare'
This is a common pattern, so there’s a shorter version of it called existential assignment. Put an existential operator in front of the assignment operator
objBook['author'] ?= 'William Shakespeare'
Misc
switch
statement and alias for true
value
isFavorited = (title) -> switch title when "The Shawshank Redemption", "The Godfather" yes else no if isFavorited "The Godfather" is yes then watch() else suggestAnother() sendNotification()
These are provided by the then
keyword immediately after an if
to supply an expression as a block without a newline or indentation
year = 1985 if year is 1985 then isMyBirthday = yes
Or inside a switch
day = 5 daySuffix = switch day when 1 then 'st' when 2 then 'nd' when 3 then 'rd' else 'th'
An if
statement can also go after an expression:
isMyBirthday = yes if year is 1985
Use search
method on a string to find another string within
hasSomethig = (something) -> str.search(something) isnt -1
Use split
when you want to split a string into an array of strings. You can split a string on the comma character using the /,/
regular expression literal
'foo,boo'.split /,/