+ All Categories
Home > Technology > CoffeeScript

CoffeeScript

Date post: 15-May-2015
Category:
Upload: scott-leberknight
View: 9,817 times
Download: 1 times
Share this document with a friend
Description:
Presentation on CoffeeScript programming language.
Popular Tags:
82
Script Scott Leberknight by
Transcript
Page 1: CoffeeScript

ScriptScott Leberknight

by

Page 2: CoffeeScript

Compiles to JavaScript

Created by Jeremy Ashkenas

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

Page 3: CoffeeScript

"It's just JavaScript"

Page 4: CoffeeScript
Page 5: CoffeeScript
Page 6: CoffeeScript

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

Page 7: CoffeeScript

cube = (x) -> x * x * xcubes = (cube num for num in [1, 2, 3, 4, 5])console.log cubes

Page 8: CoffeeScript

Let's Get Started...

Page 9: CoffeeScript

OS XInstall Homebrew

brew install node

curl http://npmjs.org/install.sh | sh

npm install coffee-script

coffee -v

http://mxcl.github.com/homebrew/

Page 10: CoffeeScript

Linux*

npm install coffee-script

install node and npm(http://joyeur.com/2010/12/10/installing-node-and-npm/ )

coffee -v

(* Windoze people can uze these instructions on Cygwin)

Page 11: CoffeeScript

Drinking some Coffee...

Page 12: CoffeeScript

⌘-R

Page 13: CoffeeScript

⌘-B

Page 14: CoffeeScript

$ coffee -c my.coffee$ node my.js[ 2048, 4096, 6144, 8192, 10240 ]

Page 15: CoffeeScript

$ coffeecoffee> nums = (x * 1024 for x in [2..10] by 2)2048,4096,6144,8192,10240

coffee> typeof(nums)object

coffee> nums.length5

coffee> nums[4]10240

coffee> quit()

Page 16: CoffeeScript

$ coffee --watch my.coffee[ 2048, 4096, 6144, 8192, 10240 ][ 1024, 2048, 3072, 4096, 5120 ]

Page 17: CoffeeScript
Page 18: CoffeeScript

<script type="text/coffeescript"> nums = (x * 1024 for x in [2..10] by 2) console.log nums</script>

Page 19: CoffeeScript

Everything's an expression

result = if (2 > 1) then "Yep" else "Hmmmm..."console.log result=> Yep

Page 20: CoffeeScript

Look Ma! No var needed

Page 21: CoffeeScript

book = "I Am America (And So Can You!)"

var book;book = "I Am America (And So Can You!)";

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

JavaScript

Page 22: CoffeeScript

22

if isFood(animal) strangle() eat()else slitherAlong()

Significant Whitespace

Page 23: CoffeeScript

23

if isFood(animal) strangle() eat()elseslitherAlong()

Significant Whitespace

Page 24: CoffeeScript

Functions...the basics

Page 25: CoffeeScript

noop = ->

-> 'The answer is 42'

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

answerer -> 'The answer is 42'

mult = (x, y) -> x * y

Page 26: CoffeeScript

mult = (x, y) -> x * y

var mult;mult = function(x, y) { return x * y;};

JavaScript

Page 27: CoffeeScript

console.log((function() { return 'What is the question?';})());

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

JavaScript

Page 28: CoffeeScript

Arrays Objects&

Page 29: CoffeeScript

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]

Page 30: CoffeeScript

range = [1..10]range = [1..21]range = [1..22] # Inflection pt! (*)range = [1..100]range = [1..100000]

(* in version 1.0.1 )

Page 31: CoffeeScript

fellowship = wizard: 'Gandalf' hobbits: ['Frodo', 'Pippin', 'Sam']

Page 32: CoffeeScript

delta = '\u0394'greekUnicode = { delta }

var delta, greekUnicode;delta = '\u0394';greekUnicode = { delta: delta};

JavaScript

Page 33: CoffeeScript

Operators & Aliases

Page 34: CoffeeScript

CoffeeScript JavaScript

==, is ===

!=, isnt !===

and &&

or ||

of in

in (no equivalent)

@, this this

true, yes, on true

false, no, off false

Page 35: CoffeeScript

goodStudent = yes if grade in ['A', 'B']

stop() unless greenLight is on

if (book is "1984") removeFromAllKindles()

Page 36: CoffeeScript

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

options ?= {}

options or= defaults

customer?.contactInfo?.emailAddress

Existential operator

Page 37: CoffeeScript

Getting Loopy

Page 38: CoffeeScript

a = [1, 2, 3, 4, 5]for val in a doSomethingWith(val)

Iterating Arrays using "in"

Page 39: CoffeeScript

a = [1, 2, 3, 4, 5]timesTwo = for val in a val * 2

=> [2, 4, 6, 8, 10 ]

Loops return a value

Page 40: CoffeeScript

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!"

Loops do not create scope...

Page 41: CoffeeScript

for prop, val of someObject # do something...

Iterating objects using "of"

Page 42: CoffeeScript

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}"

Iterating objects with "for

own" (hasOwnProperty)

Page 43: CoffeeScript

What do vampires do while it's

dark?

Page 44: CoffeeScript

while isDarkOutside() suckBlood()

Page 45: CoffeeScript

...or until it's day time?

Page 46: CoffeeScript

until isDayTime() suckBlood()

Page 47: CoffeeScript

¿Comprendo?

Page 48: CoffeeScript

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'

Array Comprehensions

Page 49: CoffeeScript

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)

Page 50: CoffeeScript

Ripping things apart...

(a.k.a. de-structuring assignment)

Page 51: CoffeeScript

[a, b] = [b, a]

Page 52: CoffeeScript

[firstName, mi, lastName] = ['Wile', 'E', 'Coyote']

Page 53: CoffeeScript

weatherReport = (location) -> # Get the weather for real... [location, 70, "Partly Cloudy"]

[city, temp, forecast] = weatherReport "Reston, VA"

Page 54: CoffeeScript

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

Page 55: CoffeeScript

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"

splat!

Page 56: CoffeeScript

Functions...the Good Stuff

Page 57: CoffeeScript

Functions create scope

Variable declarations are pushed to the top of the closest scope

Variables are not visible outside declared scope

Functions are bound or unbound

Page 58: CoffeeScript

weirdAl = function() { a = a + 1; // What's a's value at this point? var a = 10; return a;}result = weirdAl();

JavaScript

Page 59: CoffeeScript

Scoping...

Example from: http://jashkenas.github.com/coffee-script/

outer = 1changeNumbers = -> inner = -1 outer = 10inner = changeNumbers()

var changeNumbers, inner, outer;outer = 1;changeNumbers = function() { var inner; inner = -1; return outer = 10;};inner = changeNumbers();

JavaScript

Page 60: CoffeeScript

Context is key...but what is

this?

Page 61: CoffeeScript

@ is this, this is @

Page 62: CoffeeScript

setAnswer = (answer) -> @answer = answerdeepThought = {}deepThought.setAnswer = setAnswerdeepThought.setAnswer 42console.log deepThought.answer=> 42

Bound function

Page 63: CoffeeScript

setAnswer = (answer) -> @answer = answerdeepThought = {}setAnswer.apply deepThought, [ 42 ]console.log deepThought.answer=> 42

Applying context...

Page 64: CoffeeScript

Computer = (answer) -> @answer = answerdeepThought = new Computer(42)watson = new Computer("What is Toronto?")console.log deepThought.answer=> 42

console.log watson.answer=> "What is Toronto?"

Context via new...

Page 65: CoffeeScript

Capturing this...

=> binds a function to the current scope

callback = (message) => @voicemail.push message

Page 66: CoffeeScript

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

default arguments

Page 67: CoffeeScript

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')

Page 68: CoffeeScript

Class-based OO

Page 69: CoffeeScript

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

Page 70: CoffeeScript

class Bike constructor: (@brand) -> @gear = 1

changeGear: (newGear) -> @gear = newGear

currentGear: -> @gear

status: -> "#{@brand} cruising in gear #{@gear}"

Page 71: CoffeeScript

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()

Page 72: CoffeeScript

Grab-Bag...

Page 73: CoffeeScript

string interpolation

embedded JS using `...` (backticks)

switch/when/else

try/catch/finally

multi-line strings

enhanced regular expressions

Cake and Cakefiles

Page 74: CoffeeScript

Other Considerations...

Debugging

Compilation

Deployment

Testing

Page 75: CoffeeScript

Let's Review...

Page 76: CoffeeScript

"It's just JavaScript"

Page 77: CoffeeScript

"Because DHH says so..."

(yes, this is a joke)

Page 78: CoffeeScript

Refs

Page 79: CoffeeScript

CoffeeScript: Accelerated JavaScript Developmenthttp://pragprog.com/titles/tbcoffee/coffeescript

CoffeeScript GitHub pagehttp://jashkenas.github.com/coffee-script/

Page 80: CoffeeScript

http://lmgtfy.com/?q=coffeescript

Page 81: 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/

Splat Wallpaper -http://wallpaperstock.net/digital-splat_wallpapers_11732_1600x1200_1.html

(others from iStockPhoto...)

Weird Al - http://www.flickr.com/photos/schilder/4749864091/

Grab Bag -http://www.flickr.com/photos/maynard/2126229821/

Page 82: CoffeeScript

[email protected]

www.nearinfinity.com/blogs/

twitter: sleberknight

(my info)


Recommended