SlideShare uma empresa Scribd logo
1 de 82
Baixar para ler offline
Script
     by
  Scott Leberknight
Created by Jeremy Ashkenas



https://github.com/jashkenas/coffee-script



      Compiles to JavaScript
"It's just JavaScript"
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
cube = (x) -> x * x * x
cubes = (cube num for num in [1, 2, 3, 4, 5])
console.log cubes
Let's Get Started..
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/
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)
Drinking some Coffee..
⌘-R
⌘-B
$ coffee -c my.coffee
$ node my.js
[ 2048, 4096, 6144, 8192, 10240 ]
$ coffee
coffee> nums = (x * 1024 for x in [2..10] by 2)
2048,4096,6144,8192,10240

coffee> typeof(nums)
object

coffee> nums.length
5

coffee> nums[4]
10240

coffee> quit()
$ 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>
Everything's an expression
result = 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!)";

                   JavaScript

             http://www.amazon.com/Am-America-So-Can-You/dp/0446580503
Significant Whitespace



                     if isFood(animal)
                       strangle()
                       eat()
                     else
                       slitherAlong()22
Significant Whitespace



                     if isFood(animal)
                       strangle()
                       eat()
                     else
                     slitherAlong()  23
Functions.. the basics
noop = ->

-> 'The answer is 42'

console.log do -> 'What is the question?'

answerer -> 'The answer is 42'

mult = (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?';
       })());

              JavaScript
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]
a[2..-2]   #   [3, 4]
range   =   [1..10]
range   =   [1..21]
range   =   [1..22] # Inflection pt! (*)
range   =   [1..100]
range   =   [1..100000]




                              (* in version 1.0.1 )
fellowship =
  wizard: 'Gandalf'
  hobbits: ['Frodo', 'Pippin', 'Sam']
delta = 'u0394'
greekUnicode = { delta }




                 var delta, greekUnicode;
                 delta = 'u0394';
                 greekUnicode = {
    JavaScript
                    delta: delta
                 };
Operators & Aliases
CoffeeScript        JavaScript
   ==, is             ===
   !=, isnt           !===
    and                &&
     or                 ||
     of                in
     in          (no equivalent)
  @, this             this
true, yes, on         true
false, no, off        false
goodStudent = yes if grade in ['A', 'B']



stop() unless greenLight is on



if (book is "1984")
  removeFromAllKindles()
Existential operator

believer = if aliens? then yes else no
console.log "I Believe" if believer



options ?= {}



options or= defaults



customer?.contactInfo?.emailAddress
Getting Loopy
Iterating Arrays using "in"

a = [1, 2, 3, 4, 5]
for val in a
  doSomethingWith(val)
Loops return a value
a = [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 'Blast-off!'
 else
   console.log "Aborted with #{num} seconds left!"
Iterating objects using "of"

for prop, val of someObject
  # do something...
Iterating objects with "for
         own" (hasOwnProperty)
Human = ->
Human::species = 'Homo-Sapiens'

ceo = new Human()
ceo.name = "Chris D'Agostino"
ceo.company = 'Near Infinity'
ceo.yearFounded = 2002

for own prop, val of ceo
  console.log "#{prop} = #{val}"
What do vampires do while it's
           dark?
while isDarkOutside()
  suckBlood()
. .or until it's day time?
until isDayTime()
  suckBlood()
¿Comprendo?
Array Comprehensions

foods = ['pizza', 'soda', 'beer']

consume food for food in foods

consume food if food is 'beer' for food in foods

consume food for food in foods when food is 'beer'
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)
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] = weatherReport "Reston, VA"
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
[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
Functions.. the Good Stuff
Functions are bound or unbound


Functions create scope


Variable declarations are pushed to the top of the
closest scope


Variables are not visible outside declared scope
weirdAl = function() {
  a = a + 1;
  // What's a's value at this point?
  var a = 10;
  return a;
}
result = weirdAl();




                                       JavaScript
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/
Context is key.. but what is
          this?
@ is this, this is @
Bound function
  setAnswer = (answer) -> @answer = answer
  deepThought = {}
  deepThought.setAnswer = setAnswer
  deepThought.setAnswer 42
  console.log deepThought.answer
  => 42
Applying context..
 setAnswer = (answer) -> @answer = answer
 deepThought = {}
 setAnswer.apply deepThought, [ 42 ]
 console.log deepThought.answer
 => 42
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?"
Capturing this..
callback = (message) => @voicemail.push message


          => binds a function to the current scope
default arguments
selectMeals = (breakfast = 'Chick Fil A', 
    lunch = 'Macaroni Grill', dinner = 'Thai Noy') ->
  "You chose #{breakfast}, #{lunch}, and #{dinner}"



console.log selectMeals("McDonald's", 'Subway', 'Outback')
=> You chose McDonald's, Subway, and Outback

console.log selectMeals(null, 'Subway', null)
=> You chose Chick Fil A, Subway, and Thai Noy

console.log selectMeals(null, null, null)
=> You chose Chick Fil A, Macaroni Grill, and Thai Noy
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
Class-based OO
Prototypal inheritance
var 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
class Bike
  constructor: (@brand) ->
    @gear = 1

  changeGear: (newGear) ->
    @gear = newGear

  currentGear: ->
    @gear

  status: ->
    "#{@brand} cruising in gear #{@gear}"
class MtnBike extends Bike
  changeGear: (newGear) ->
    # do something special for mtn bikes...
    super newGear



cruiser = new Bike("Schwinn")
cruiser.changeGear(4)
console.log cruiser.status()

mtn = new MtnBike("Specialized")
mtn.changeGear(8)
console.log mtn.status()
Grab-Bag..
string interpolation

embedded JS using `...` (backticks)

switch/when/else

try/catch/finally

multi-line strings

enhanced regular expressions

Cake and Cakefiles
Other Considerations..
  Debugging

  Compilation

  Deployment

  Testing
Let's Review..
"It's just JavaScript"
"Because DHH says so..."



      (yes, this is a joke)
Refs
CoffeeScript: Accelerated JavaScript Development
                  http://pragprog.com/titles/tbcoffee/coffeescript



                         CoffeeScript GitHub page
                        http://jashkenas.github.com/coffee-script/
http://lmgtfy.com/?q=coffeescript
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...)
(my info)


scott.leberknight@nearinfinity.com
www.nearinfinity.com/blogs/
twitter: sleberknight

Mais conteúdo relacionado

Mais procurados

Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonUC San Diego
 
RxSwift 시작하기
RxSwift 시작하기RxSwift 시작하기
RxSwift 시작하기Suyeol Jeon
 
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Suyeol Jeon
 
Python 표준 라이브러리
Python 표준 라이브러리Python 표준 라이브러리
Python 표준 라이브러리용 최
 
Pyimproved again
Pyimproved againPyimproved again
Pyimproved againrik0
 
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebBDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebChristian Baranowski
 
How to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftHow to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftGiordano Scalzo
 
Postgres can do THAT?
Postgres can do THAT?Postgres can do THAT?
Postgres can do THAT?alexbrasetvik
 
Beyond Breakpoints: Advanced Debugging with XCode
Beyond Breakpoints: Advanced Debugging with XCodeBeyond Breakpoints: Advanced Debugging with XCode
Beyond Breakpoints: Advanced Debugging with XCodeAijaz Ansari
 
Snakes for Camels
Snakes for CamelsSnakes for Camels
Snakes for Camelsmiquelruizm
 
Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2Evgeny Borisov
 
Python decorators (中文)
Python decorators (中文)Python decorators (中文)
Python decorators (中文)Yiwei Chen
 
Google Go For Ruby Hackers
Google Go For Ruby HackersGoogle Go For Ruby Hackers
Google Go For Ruby HackersEleanor McHugh
 
Indexing thousands of writes per second with redis
Indexing thousands of writes per second with redisIndexing thousands of writes per second with redis
Indexing thousands of writes per second with redispauldix
 
Advanced Python, Part 2
Advanced Python, Part 2Advanced Python, Part 2
Advanced Python, Part 2Zaar Hai
 
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev FedorProgramming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev FedorFedor Lavrentyev
 
Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка TwistedMaxim Kulsha
 

Mais procurados (20)

Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
RxSwift 시작하기
RxSwift 시작하기RxSwift 시작하기
RxSwift 시작하기
 
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
 
Python 표준 라이브러리
Python 표준 라이브러리Python 표준 라이브러리
Python 표준 라이브러리
 
Pyimproved again
Pyimproved againPyimproved again
Pyimproved again
 
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebBDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
 
How to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftHow to Clone Flappy Bird in Swift
How to Clone Flappy Bird in Swift
 
Postgres can do THAT?
Postgres can do THAT?Postgres can do THAT?
Postgres can do THAT?
 
PubNative Tracker
PubNative TrackerPubNative Tracker
PubNative Tracker
 
Beyond Breakpoints: Advanced Debugging with XCode
Beyond Breakpoints: Advanced Debugging with XCodeBeyond Breakpoints: Advanced Debugging with XCode
Beyond Breakpoints: Advanced Debugging with XCode
 
Snakes for Camels
Snakes for CamelsSnakes for Camels
Snakes for Camels
 
Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2
 
Presentatie - Introductie in Groovy
Presentatie - Introductie in GroovyPresentatie - Introductie in Groovy
Presentatie - Introductie in Groovy
 
Python decorators (中文)
Python decorators (中文)Python decorators (中文)
Python decorators (中文)
 
Google Go For Ruby Hackers
Google Go For Ruby HackersGoogle Go For Ruby Hackers
Google Go For Ruby Hackers
 
Indexing thousands of writes per second with redis
Indexing thousands of writes per second with redisIndexing thousands of writes per second with redis
Indexing thousands of writes per second with redis
 
Advanced Python, Part 2
Advanced Python, Part 2Advanced Python, Part 2
Advanced Python, Part 2
 
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev FedorProgramming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
 
ES6 and BEYOND
ES6 and BEYONDES6 and BEYOND
ES6 and BEYOND
 
Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка Twisted
 

Destaque (17)

Polyglot Persistence
Polyglot PersistencePolyglot Persistence
Polyglot Persistence
 
Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0
 
Rack
RackRack
Rack
 
jps & jvmtop
jps & jvmtopjps & jvmtop
jps & jvmtop
 
wtf is in Java/JDK/wtf7?
wtf is in Java/JDK/wtf7?wtf is in Java/JDK/wtf7?
wtf is in Java/JDK/wtf7?
 
iOS
iOSiOS
iOS
 
httpie
httpiehttpie
httpie
 
Cloudera Impala
Cloudera ImpalaCloudera Impala
Cloudera Impala
 
RESTful Web Services with Jersey
RESTful Web Services with JerseyRESTful Web Services with Jersey
RESTful Web Services with Jersey
 
Hadoop
HadoopHadoop
Hadoop
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Dropwizard
DropwizardDropwizard
Dropwizard
 
HBase Lightning Talk
HBase Lightning TalkHBase Lightning Talk
HBase Lightning Talk
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
Apache ZooKeeper
Apache ZooKeeperApache ZooKeeper
Apache ZooKeeper
 
Awesomizing your Squarespace Website
Awesomizing your Squarespace WebsiteAwesomizing your Squarespace Website
Awesomizing your Squarespace Website
 
AWS Lambda
AWS LambdaAWS Lambda
AWS Lambda
 

Semelhante a CoffeeScript

Damn Fine CoffeeScript
Damn Fine CoffeeScriptDamn Fine CoffeeScript
Damn Fine CoffeeScriptniklal
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with GroovyArturo Herrero
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairMark
 
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRaimonds Simanovskis
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScriptNone
 
Functional programming in ruby
Functional programming in rubyFunctional programming in ruby
Functional programming in rubyKoen Handekyn
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchainedEduard Tomàs
 
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup itPROIDEA
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
谈谈Javascript设计
谈谈Javascript设计谈谈Javascript设计
谈谈Javascript设计Alipay
 
谈谈Javascript设计
谈谈Javascript设计谈谈Javascript设计
谈谈Javascript设计Ailsa126
 
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)MongoSF
 
Frege - consequently functional programming for the JVM
Frege - consequently functional programming for the JVMFrege - consequently functional programming for the JVM
Frege - consequently functional programming for the JVMDierk König
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonAlex Payne
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 

Semelhante a CoffeeScript (20)

Damn Fine CoffeeScript
Damn Fine CoffeeScriptDamn Fine CoffeeScript
Damn Fine CoffeeScript
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love Affair
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
Functional programming in ruby
Functional programming in rubyFunctional programming in ruby
Functional programming in ruby
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Coffee script
Coffee scriptCoffee script
Coffee script
 
Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a try
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 
谈谈Javascript设计
谈谈Javascript设计谈谈Javascript设计
谈谈Javascript设计
 
谈谈Javascript设计
谈谈Javascript设计谈谈Javascript设计
谈谈Javascript设计
 
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
 
Frege - consequently functional programming for the JVM
Frege - consequently functional programming for the JVMFrege - consequently functional programming for the JVM
Frege - consequently functional programming for the JVM
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the Horizon
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 

Mais de Scott Leberknight (6)

JShell & ki
JShell & kiJShell & ki
JShell & ki
 
JUnit Pioneer
JUnit PioneerJUnit Pioneer
JUnit Pioneer
 
JDKs 10 to 14 (and beyond)
JDKs 10 to 14 (and beyond)JDKs 10 to 14 (and beyond)
JDKs 10 to 14 (and beyond)
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
SDKMAN!
SDKMAN!SDKMAN!
SDKMAN!
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 

Último

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 

Último (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 

CoffeeScript

  • 1. Script by Scott Leberknight
  • 2. Created by Jeremy Ashkenas https://github.com/jashkenas/coffee-script Compiles to JavaScript
  • 4.
  • 5.
  • 6. 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
  • 7. cube = (x) -> x * x * x cubes = (cube num for num in [1, 2, 3, 4, 5]) console.log cubes
  • 9. 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/
  • 10. 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)
  • 12. ⌘-R
  • 13. ⌘-B
  • 14. $ coffee -c my.coffee $ node my.js [ 2048, 4096, 6144, 8192, 10240 ]
  • 15. $ coffee coffee> nums = (x * 1024 for x in [2..10] by 2) 2048,4096,6144,8192,10240 coffee> typeof(nums) object coffee> nums.length 5 coffee> nums[4] 10240 coffee> quit()
  • 16. $ coffee --watch my.coffee [ 2048, 4096, 6144, 8192, 10240 ] [ 1024, 2048, 3072, 4096, 5120 ]
  • 17.
  • 18. <script type="text/coffeescript"> nums = (x * 1024 for x in [2..10] by 2) console.log nums </script>
  • 19. Everything's an expression result = if (2 > 1) then "Yep" else "Hmmmm..." console.log result => Yep
  • 20. Look Ma! No var needed
  • 21. 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
  • 22. Significant Whitespace if isFood(animal) strangle() eat() else slitherAlong()22
  • 23. Significant Whitespace if isFood(animal) strangle() eat() else slitherAlong() 23
  • 25. noop = -> -> 'The answer is 42' console.log do -> 'What is the question?' answerer -> 'The answer is 42' mult = (x, y) -> x * y
  • 26. mult = (x, y) -> x * y var mult; mult = function(x, y) { JavaScript return x * y; };
  • 27. console.log do -> 'What is the question?' console.log((function() { return 'What is the question?'; })()); JavaScript
  • 29. 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]
  • 30. range = [1..10] range = [1..21] range = [1..22] # Inflection pt! (*) range = [1..100] range = [1..100000] (* in version 1.0.1 )
  • 31. fellowship = wizard: 'Gandalf' hobbits: ['Frodo', 'Pippin', 'Sam']
  • 32. delta = 'u0394' greekUnicode = { delta } var delta, greekUnicode; delta = 'u0394'; greekUnicode = { JavaScript delta: delta };
  • 34. CoffeeScript JavaScript ==, is === !=, isnt !=== and && or || of in in (no equivalent) @, this this true, yes, on true false, no, off false
  • 35. goodStudent = yes if grade in ['A', 'B'] stop() unless greenLight is on if (book is "1984") removeFromAllKindles()
  • 36. Existential operator believer = if aliens? then yes else no console.log "I Believe" if believer options ?= {} options or= defaults customer?.contactInfo?.emailAddress
  • 38. Iterating Arrays using "in" a = [1, 2, 3, 4, 5] for val in a doSomethingWith(val)
  • 39. Loops return a value a = [1, 2, 3, 4, 5] timesTwo = for val in a val * 2 => [2, 4, 6, 8, 10 ]
  • 40. 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!"
  • 41. Iterating objects using "of" for prop, val of someObject # do something...
  • 42. Iterating objects with "for own" (hasOwnProperty) Human = -> Human::species = 'Homo-Sapiens' ceo = new Human() ceo.name = "Chris D'Agostino" ceo.company = 'Near Infinity' ceo.yearFounded = 2002 for own prop, val of ceo console.log "#{prop} = #{val}"
  • 43. What do vampires do while it's dark?
  • 44. while isDarkOutside() suckBlood()
  • 45. . .or until it's day time?
  • 46. until isDayTime() suckBlood()
  • 48. Array Comprehensions foods = ['pizza', 'soda', 'beer'] consume food for food in foods consume food if food is 'beer' for food in foods consume food for food in foods when food is 'beer'
  • 49. 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)
  • 50. Ripping things apart.. (a.k.a. de-structuring assignment)
  • 51. [a, b] = [b, a]
  • 52. [firstName, mi, lastName] = ['Wile', 'E', 'Coyote']
  • 53. weatherReport = (location) -> # Get the weather for real... [location, 70, "Partly Cloudy"] [city, temp, forecast] = weatherReport "Reston, VA"
  • 54. 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
  • 55. [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
  • 57. Functions are bound or unbound Functions create scope Variable declarations are pushed to the top of the closest scope Variables are not visible outside declared scope
  • 58. weirdAl = function() { a = a + 1; // What's a's value at this point? var a = 10; return a; } result = weirdAl(); JavaScript
  • 59. 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/
  • 60. Context is key.. but what is this?
  • 61. @ is this, this is @
  • 62. Bound function setAnswer = (answer) -> @answer = answer deepThought = {} deepThought.setAnswer = setAnswer deepThought.setAnswer 42 console.log deepThought.answer => 42
  • 63. Applying context.. setAnswer = (answer) -> @answer = answer deepThought = {} setAnswer.apply deepThought, [ 42 ] console.log deepThought.answer => 42
  • 64. 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?"
  • 65. Capturing this.. callback = (message) => @voicemail.push message => binds a function to the current scope
  • 66. default arguments selectMeals = (breakfast = 'Chick Fil A', lunch = 'Macaroni Grill', dinner = 'Thai Noy') -> "You chose #{breakfast}, #{lunch}, and #{dinner}" console.log selectMeals("McDonald's", 'Subway', 'Outback') => You chose McDonald's, Subway, and Outback console.log selectMeals(null, 'Subway', null) => You chose Chick Fil A, Subway, and Thai Noy console.log selectMeals(null, null, null) => You chose Chick Fil A, Macaroni Grill, and Thai Noy
  • 67. 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
  • 69. Prototypal inheritance var 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
  • 70. class Bike constructor: (@brand) -> @gear = 1 changeGear: (newGear) -> @gear = newGear currentGear: -> @gear status: -> "#{@brand} cruising in gear #{@gear}"
  • 71. class MtnBike extends Bike changeGear: (newGear) -> # do something special for mtn bikes... super newGear cruiser = new Bike("Schwinn") cruiser.changeGear(4) console.log cruiser.status() mtn = new MtnBike("Specialized") mtn.changeGear(8) console.log mtn.status()
  • 73. string interpolation embedded JS using `...` (backticks) switch/when/else try/catch/finally multi-line strings enhanced regular expressions Cake and Cakefiles
  • 74. Other Considerations.. Debugging Compilation Deployment Testing
  • 77. "Because DHH says so..." (yes, this is a joke)
  • 78. Refs
  • 79. CoffeeScript: Accelerated JavaScript Development http://pragprog.com/titles/tbcoffee/coffeescript CoffeeScript GitHub page http://jashkenas.github.com/coffee-script/
  • 81. 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...)