Skip to content

Instantly share code, notes, and snippets.

@pranavgarg
Last active August 29, 2015 14:23
Show Gist options
  • Save pranavgarg/b2e46ae0b275ddce2a56 to your computer and use it in GitHub Desktop.
Save pranavgarg/b2e46ae0b275ddce2a56 to your computer and use it in GitHub Desktop.
Coffeescript to Javascript
1. Conditionals & Operators
coffeescript Javascript
------------ -------------
== is ===
!= isnt !==
not !
and &&
or ||
true yes on true
false no off false
if age < 18 if (age < 18) { alert("Under age") }
alert "Under age"
alert "under age" if age < 18
if newLevel? if (typeof newLevel !== "undefined" && newLevel !== null){
checkLevel(newLevel) checkLevel(newLevel);
else } else {
resetLevel resetLevel();
}
COFFEESCRIPT
---------------
check if a function exists before calling it
==> funct?()
Ranges
------
range = [1..4] inclusive var range = [1,2,3,4]
range = [1...4] not inclusive var range = [1,2,3]
Variables & Subsets
----------------
start = 5
end = 10
range = [start..end]
range[1..4]
range[1...range.length] :- returns all the elements in the list
range[1..-1] :- -1 means very last item
List
---------
storeLocations = [
'Orlando'
'Winter Park'
'Sanford'
]
for location in storeLocations
alert "Location #{location}"
OR
alert "Location #{location}" for location in storeLocations
changing the original list comprehension to have FL added
storeLocations = ("#{loc}, FL" for loc in storeLocations)
geoLocate(loc) for loc in storeLocations when loc isnt 'Sanford'
#create a new Array without Sanford
storeLocations = (loc for loc in storeLocations when loc isnt 'Sanford')
#Splats () - for a variable number of arguments
searchLocations = (brand, cities...) ->
"#{brand} exists in #{cities.join(',')}"
#Objects - hash
coffee = {name: "French", strength: 1}
OR
coffee =
name: "French"
strength: 1
brew: -> alert("brewing #{@name}")
pour: (amount=1) ->
if amount is 1
"Poured a single cup"
else
"Poured #{amount} cups"
Coffee Classes (Constructors and Properties)
------------------------------------------------
class Coffee
constructor: (@name, @strength=1) ->
brew: -> alert "brewing #{@name}"
pour: (amount=1) ->
if amount is 1
"Poured a single cup"
else
"Poured #{name} cups"
#calling the coffee object
french = new Coffee("Indian", 2)
french.brew()
#Inheritance
class IndianCoffee extends Coffee
constructor: (@name, @strength=0) ->
@brand = "Nescafe"
#new coffee
ice_coffee = new IndianCoffee("Indian")
ice_coffee.brew()
#when you need the reference "this" for incrementing the class parameters
please use the "=>" instead of "->" in the function definition of a class.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment