Script     by  Scott Leberknight
Created by Jeremy Ashkenashttps://github.com/jashkenas/coffee-script      Compiles to JavaScript
"Its just JavaScript"
var cube, cubes, num;cube = function(x) {   return Math.pow(x, 3);};cubes = (function() {   var _i, _len, _ref, _results; ...
cube = (x) -> x * x * xcubes = (cube num for num in [1, 2, 3, 4, 5])console.log cubes
Lets Get Started..
OS X Install Homebrew brew install node curl http://npmjs.org/install.sh | sh npm install coffee-script coffee -v         ...
Linux* install node and npm       (http://joyeur.com/2010/12/10/installing-node-and-npm/ ) npm install coffee-script coffe...
Drinking some Coffee..
⌘-R
⌘-B
$ coffee -c my.coffee$ node my.js[ 2048, 4096, 6144, 8192, 10240 ]
$ coffeecoffee> nums = (x * 1024 for x in [2..10] by 2)2048,4096,6144,8192,10240coffee> typeof(nums)objectcoffee> nums.len...
$ coffee --watch my.coffee[ 2048, 4096, 6144, 8192, 10240 ][ 1024, 2048, 3072, 4096, 5120 ]
<script type="text/coffeescript">  nums = (x * 1024 for x in [2..10] by 2)  console.log nums</script>
Everythings an expressionresult = if (2 > 1) then "Yep" else "Hmmmm..."console.log result=> Yep
Look Ma! No var needed
book = "I Am America (And So Can You!)"    var book;    book = "I Am America (And So Can You!)";                   JavaScr...
Significant Whitespace                     if isFood(animal)                       strangle()                       eat() ...
Significant Whitespace                     if isFood(animal)                       strangle()                       eat() ...
Functions.. the basics
noop = ->-> The answer is 42console.log do -> What is the question?answerer -> The answer is 42mult = (x, y) -> x * y
mult = (x, y) -> x * y             var mult;             mult = function(x, y) {JavaScript                return x * y;   ...
console.log do -> What is the question?       console.log((function() {         return What is the question?;       })());...
Arrays & Objects
a = [1, 2, 3, 4, 5]a[1..2]    #   inclusive range: [2, 3]a[1...2]   #   exclusive range: [2]a[0..-1]   #   [1, 2, 3, 4, 5]...
range   =   [1..10]range   =   [1..21]range   =   [1..22] # Inflection pt! (*)range   =   [1..100]range   =   [1..100000] ...
fellowship =  wizard: Gandalf  hobbits: [Frodo, Pippin, Sam]
delta = u0394greekUnicode = { delta }                 var delta, greekUnicode;                 delta = u0394;             ...
Operators & Aliases
CoffeeScript        JavaScript   ==, is             ===   !=, isnt           !===    and                &&     or         ...
goodStudent = yes if grade in [A, B]stop() unless greenLight is onif (book is "1984")  removeFromAllKindles()
Existential operatorbeliever = if aliens? then yes else noconsole.log "I Believe" if believeroptions ?= {}options or= defa...
Getting Loopy
Iterating Arrays using "in"a = [1, 2, 3, 4, 5]for val in a  doSomethingWith(val)
Loops return a valuea = [1, 2, 3, 4, 5]timesTwo = for val in a  val * 2=> [2, 4, 6, 8, 10 ]
Loops do not create scope.. countdown = [10..0] for num in countdown   break if errorDetected() if num is 0   console.log ...
Iterating objects using "of"for prop, val of someObject  # do something...
Iterating objects with "for         own" (hasOwnProperty)Human = ->Human::species = Homo-Sapiensceo = new Human()ceo.name ...
What do vampires do while its           dark?
while isDarkOutside()  suckBlood()
. .or until its day time?
until isDayTime()  suckBlood()
¿Comprendo?
Array Comprehensionsfoods = [pizza, soda, beer]consume food for food in foodsconsume food if food is beer for food in food...
nums = [1..10]doubles = (n * 2 for n in nums)squares = (n * n for n in nums)evens = (n for n in nums when n % 2 is 0)evens...
Ripping things apart..     (a.k.a. de-structuring assignment)
[a, b] = [b, a]
[firstName, mi, lastName] = [Wile, E, Coyote]
weatherReport = (location) ->  # Get the weather for real...  [location, 70, "Partly Cloudy"][city, temp, forecast] = weat...
fellowship =  maiar: [Gandalf]  hobbits: [Frodo, Sam, Merry, Pippin]  elves: [Legolas]  dwarves: [Gimli]  men: [Aragorn, B...
[sauce, toppings..., crust] = [meat, pepperoni, banana peppers, green peppers, thin]console.log "Your pizza is a #{crust} ...
Functions.. the Good Stuff
Functions are bound or unboundFunctions create scopeVariable declarations are pushed to the top of theclosest scopeVariabl...
weirdAl = function() {  a = a + 1;  // Whats as value at this point?  var a = 10;  return a;}result = weirdAl();          ...
Scoping..outer = 1                      var changeNumbers, inner, outer;changeNumbers = ->             outer = 1;  inner =...
Context is key.. but what is          this?
@ is this, this is @
Bound function  setAnswer = (answer) -> @answer = answer  deepThought = {}  deepThought.setAnswer = setAnswer  deepThought...
Applying context.. setAnswer = (answer) -> @answer = answer deepThought = {} setAnswer.apply deepThought, [ 42 ] console.l...
Context via new.. Computer = (answer) ->   @answer = answer deepThought = new Computer(42) watson = new Computer("What is ...
Capturing this..callback = (message) => @voicemail.push message          => binds a function to the current scope
default argumentsselectMeals = (breakfast = Chick Fil A,     lunch = Macaroni Grill, dinner = Thai Noy) ->  "You chose #{b...
pizza = (sauce = tomato, toppings..., crust) ->  "A #{crust} pizza with #{sauce} sauce #{listOf(toppings)}"console.log piz...
Class-based OO
Prototypal inheritancevar Animal = function(name, species) {  this.name = name;  this.species = species;}Animal.prototype....
class Bike  constructor: (@brand) ->    @gear = 1  changeGear: (newGear) ->    @gear = newGear  currentGear: ->    @gear  ...
class MtnBike extends Bike  changeGear: (newGear) ->    # do something special for mtn bikes...    super newGearcruiser = ...
Grab-Bag..
string interpolationembedded JS using `...` (backticks)switch/when/elsetry/catch/finallymulti-line stringsenhanced regular ...
Other Considerations..  Debugging  Compilation  Deployment  Testing
Lets Review..
"Its just JavaScript"
"Because DHH says so..."      (yes, this is a joke)
Refs
CoffeeScript: Accelerated JavaScript Development                  http://pragprog.com/titles/tbcoffee/coffeescript        ...
http://lmgtfy.com/?q=coffeescript
photo attributions  Coffee # 1 -  http://www.flickr.com/photos/dyobmit/18588671/  Coffee # 2 -  http://www.flickr.com/photos...
(my info)scott.leberknight@nearinfinity.comwww.nearinfinity.com/blogs/twitter: sleberknight
CoffeeScript
CoffeeScript
CoffeeScript
Upcoming SlideShare
Loading in...5
×

CoffeeScript

9,896

Published on

Presentation on CoffeeScript programming language.

Published in: Technology
1 Comment
7 Likes
Statistics
Notes
No Downloads
Views
Total Views
9,896
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
84
Comments
1
Likes
7
Embeds 0
No embeds

No notes for slide

CoffeeScript

  1. 1. Script by Scott Leberknight
  2. 2. Created by Jeremy Ashkenashttps://github.com/jashkenas/coffee-script Compiles to JavaScript
  3. 3. "Its just JavaScript"
  4. 4. var cube, cubes, num;cube = function(x) { return Math.pow(x, 3);};cubes = (function() { var _i, _len, _ref, _results; _ref = [1, 2, 3, 4, 5]; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { num = _ref[_i]; _results.push(cube(num)); } return _results;})();console.log(cubes); JavaScript
  5. 5. cube = (x) -> x * x * xcubes = (cube num for num in [1, 2, 3, 4, 5])console.log cubes
  6. 6. Lets Get Started..
  7. 7. OS X Install Homebrew brew install node curl http://npmjs.org/install.sh | sh npm install coffee-script coffee -v http://mxcl.github.com/homebrew/
  8. 8. Linux* install node and npm (http://joyeur.com/2010/12/10/installing-node-and-npm/ ) npm install coffee-script coffee -v (* Windoze people can uze these instructions on Cygwin)
  9. 9. Drinking some Coffee..
  10. 10. ⌘-R
  11. 11. ⌘-B
  12. 12. $ coffee -c my.coffee$ node my.js[ 2048, 4096, 6144, 8192, 10240 ]
  13. 13. $ coffeecoffee> nums = (x * 1024 for x in [2..10] by 2)2048,4096,6144,8192,10240coffee> typeof(nums)objectcoffee> nums.length5coffee> nums[4]10240coffee> quit()
  14. 14. $ coffee --watch my.coffee[ 2048, 4096, 6144, 8192, 10240 ][ 1024, 2048, 3072, 4096, 5120 ]
  15. 15. <script type="text/coffeescript"> nums = (x * 1024 for x in [2..10] by 2) console.log nums</script>
  16. 16. Everythings an expressionresult = if (2 > 1) then "Yep" else "Hmmmm..."console.log result=> Yep
  17. 17. Look Ma! No var needed
  18. 18. book = "I Am America (And So Can You!)" var book; book = "I Am America (And So Can You!)"; JavaScript http://www.amazon.com/Am-America-So-Can-You/dp/0446580503
  19. 19. Significant Whitespace if isFood(animal) strangle() eat() else slitherAlong()22
  20. 20. Significant Whitespace if isFood(animal) strangle() eat() else slitherAlong() 23
  21. 21. Functions.. the basics
  22. 22. noop = ->-> The answer is 42console.log do -> What is the question?answerer -> The answer is 42mult = (x, y) -> x * y
  23. 23. mult = (x, y) -> x * y var mult; mult = function(x, y) {JavaScript return x * y; };
  24. 24. console.log do -> What is the question? console.log((function() { return What is the question?; })()); JavaScript
  25. 25. Arrays & Objects
  26. 26. a = [1, 2, 3, 4, 5]a[1..2] # inclusive range: [2, 3]a[1...2] # exclusive range: [2]a[0..-1] # [1, 2, 3, 4, 5]a[2..-2] # [3, 4]
  27. 27. range = [1..10]range = [1..21]range = [1..22] # Inflection pt! (*)range = [1..100]range = [1..100000] (* in version 1.0.1 )
  28. 28. fellowship = wizard: Gandalf hobbits: [Frodo, Pippin, Sam]
  29. 29. delta = u0394greekUnicode = { delta } var delta, greekUnicode; delta = u0394; greekUnicode = { JavaScript delta: delta };
  30. 30. Operators & Aliases
  31. 31. CoffeeScript JavaScript ==, is === !=, isnt !=== and && or || of in in (no equivalent) @, this thistrue, yes, on truefalse, no, off false
  32. 32. goodStudent = yes if grade in [A, B]stop() unless greenLight is onif (book is "1984") removeFromAllKindles()
  33. 33. Existential operatorbeliever = if aliens? then yes else noconsole.log "I Believe" if believeroptions ?= {}options or= defaultscustomer?.contactInfo?.emailAddress
  34. 34. Getting Loopy
  35. 35. Iterating Arrays using "in"a = [1, 2, 3, 4, 5]for val in a doSomethingWith(val)
  36. 36. Loops return a valuea = [1, 2, 3, 4, 5]timesTwo = for val in a val * 2=> [2, 4, 6, 8, 10 ]
  37. 37. Loops do not create scope.. countdown = [10..0] for num in countdown break if errorDetected() if num is 0 console.log Blast-off! else console.log "Aborted with #{num} seconds left!"
  38. 38. Iterating objects using "of"for prop, val of someObject # do something...
  39. 39. Iterating objects with "for own" (hasOwnProperty)Human = ->Human::species = Homo-Sapiensceo = new Human()ceo.name = "Chris DAgostino"ceo.company = Near Infinityceo.yearFounded = 2002for own prop, val of ceo console.log "#{prop} = #{val}"
  40. 40. What do vampires do while its dark?
  41. 41. while isDarkOutside() suckBlood()
  42. 42. . .or until its day time?
  43. 43. until isDayTime() suckBlood()
  44. 44. ¿Comprendo?
  45. 45. Array Comprehensionsfoods = [pizza, soda, beer]consume food for food in foodsconsume food if food is beer for food in foodsconsume food for food in foods when food is beer
  46. 46. nums = [1..10]doubles = (n * 2 for n in nums)squares = (n * n for n in nums)evens = (n for n in nums when n % 2 is 0)evensSquared = (n * n for n in evens)
  47. 47. Ripping things apart.. (a.k.a. de-structuring assignment)
  48. 48. [a, b] = [b, a]
  49. 49. [firstName, mi, lastName] = [Wile, E, Coyote]
  50. 50. weatherReport = (location) -> # Get the weather for real... [location, 70, "Partly Cloudy"][city, temp, forecast] = weatherReport "Reston, VA"
  51. 51. fellowship = maiar: [Gandalf] hobbits: [Frodo, Sam, Merry, Pippin] elves: [Legolas] dwarves: [Gimli] men: [Aragorn, Boromir]{hobbits: theHobbits, men: theMen} = fellowship# or simply...{hobbits, men} = fellowship
  52. 52. [sauce, toppings..., crust] = [meat, pepperoni, banana peppers, green peppers, thin]console.log "Your pizza is a #{crust} crust with #{sauce}sauce and #{toppings.join(, )} on top" spl at! 55
  53. 53. Functions.. the Good Stuff
  54. 54. Functions are bound or unboundFunctions create scopeVariable declarations are pushed to the top of theclosest scopeVariables are not visible outside declared scope
  55. 55. weirdAl = function() { a = a + 1; // Whats as value at this point? var a = 10; return a;}result = weirdAl(); JavaScript
  56. 56. Scoping..outer = 1 var changeNumbers, inner, outer;changeNumbers = -> outer = 1; inner = -1 changeNumbers = function() { outer = 10 var inner; inner = -1;inner = changeNumbers() return outer = 10; }; inner = changeNumbers(); JavaScript Example from: http://jashkenas.github.com/coffee-script/
  57. 57. Context is key.. but what is this?
  58. 58. @ is this, this is @
  59. 59. Bound function setAnswer = (answer) -> @answer = answer deepThought = {} deepThought.setAnswer = setAnswer deepThought.setAnswer 42 console.log deepThought.answer => 42
  60. 60. Applying context.. setAnswer = (answer) -> @answer = answer deepThought = {} setAnswer.apply deepThought, [ 42 ] console.log deepThought.answer => 42
  61. 61. Context via new.. Computer = (answer) -> @answer = answer deepThought = new Computer(42) watson = new Computer("What is Toronto?") console.log deepThought.answer => 42 console.log watson.answer => "What is Toronto?"
  62. 62. Capturing this..callback = (message) => @voicemail.push message => binds a function to the current scope
  63. 63. default argumentsselectMeals = (breakfast = Chick Fil A, lunch = Macaroni Grill, dinner = Thai Noy) -> "You chose #{breakfast}, #{lunch}, and #{dinner}"console.log selectMeals("McDonalds", Subway, Outback)=> You chose McDonalds, Subway, and Outbackconsole.log selectMeals(null, Subway, null)=> You chose Chick Fil A, Subway, and Thai Noyconsole.log selectMeals(null, null, null)=> You chose Chick Fil A, Macaroni Grill, and Thai Noy
  64. 64. pizza = (sauce = tomato, toppings..., crust) -> "A #{crust} pizza with #{sauce} sauce #{listOf(toppings)}"console.log pizza(white, thin crust)console.log pizza(tomato, pepperoni, pan)console.log pizza(null, pepperoni, peppers, thin crust) 67
  65. 65. Class-based OO
  66. 66. Prototypal inheritancevar Animal = function(name, species) { this.name = name; this.species = species;}Animal.prototype.eat = function(food) { ... }Animal.prototype.sleep = function() { ... }Animal.prototype.play = function() { ... }var felix = new Animal(Felix, Feline);felix.sleep();var fido = new Animal(Fido, Canine);fido.play();fido.eat(); JavaScript
  67. 67. class Bike constructor: (@brand) -> @gear = 1 changeGear: (newGear) -> @gear = newGear currentGear: -> @gear status: -> "#{@brand} cruising in gear #{@gear}"
  68. 68. class MtnBike extends Bike changeGear: (newGear) -> # do something special for mtn bikes... super newGearcruiser = new Bike("Schwinn")cruiser.changeGear(4)console.log cruiser.status()mtn = new MtnBike("Specialized")mtn.changeGear(8)console.log mtn.status()
  69. 69. Grab-Bag..
  70. 70. string interpolationembedded JS using `...` (backticks)switch/when/elsetry/catch/finallymulti-line stringsenhanced regular expressionsCake and Cakefiles
  71. 71. Other Considerations.. Debugging Compilation Deployment Testing
  72. 72. Lets Review..
  73. 73. "Its just JavaScript"
  74. 74. "Because DHH says so..." (yes, this is a joke)
  75. 75. Refs
  76. 76. CoffeeScript: Accelerated JavaScript Development http://pragprog.com/titles/tbcoffee/coffeescript CoffeeScript GitHub page http://jashkenas.github.com/coffee-script/
  77. 77. http://lmgtfy.com/?q=coffeescript
  78. 78. photo attributions Coffee # 1 - http://www.flickr.com/photos/dyobmit/18588671/ Coffee # 2 - http://www.flickr.com/photos/ibcbulk/86885289/ Python - http://www.flickr.com/photos/lesmontsdore/5513104816/ Rip Apart Napkin - http://www.flickr.com/photos/benreichelt/5543115344/ Weird Al - http://www.flickr.com/photos/schilder/4749864091/ Splat Wallpaper - http://wallpaperstock.net/digital-splat_wallpapers_11732_1600x1200_1.html Grab Bag - http://www.flickr.com/photos/maynard/2126229821/ (others from iStockPhoto...)
  79. 79. (my info)scott.leberknight@nearinfinity.comwww.nearinfinity.com/blogs/twitter: sleberknight
  1. Gostou de algum slide específico?

    Recortar slides é uma maneira fácil de colecionar informações para acessar mais tarde.

×