SlideShare ist ein Scribd-Unternehmen logo
1 von 60
Downloaden Sie, um offline zu lesen
Damn Fine




   CoffeeScript
Focus



Language
Some Kind of Holy
        Python

                 Ruby

JavaScrip t
Raw
var render = function (width, height, draw, filePath)
{
  var canvas = new Canvas(width, height),
       ctx = canvas.getContext('2d');
   draw.call(ctx);
  var out = fs.createWriteStream(filePath),
       stream = canvas.createPNGStream();
   stream.on('data', function(chunk) {
     out.write(chunk);
   });
   stream.on('end', function() {
     console.log("Created: " + filePath);
   });
};
Brewed

render = (width, height, draw, filePath) ->
  canvas = new Canvas(width, height)
  draw.call canvas.getContext '2d'
  out = fs.createWriteStream filePath
  stream = canvas.createPNGStream()
  stream.on 'data', (chunk) ->
    out.write chunk
  stream.on 'end', ->
    console.log "Created: #{filePath}"
Basically



● function is () ->
● local variables

● indentation

● omittable parentheses
True To JavaScript



The golden rule of CoffeeScript is: "It's just
                JavaScript"
Less Syntactic Noise


stream.on('end', function() {
  console.log("Created: " +
filePath);
});
stream.on 'end', ->
  console.log "Created: #{filePath}"
My perspective



Node

A platform: JS machine + CommonJS stdlib
Runtimes
It's just



Coffee In Coffee
Browser




Just JS (generated)
Convert & Eval...



<script src="/extras/coffee-script.js"></script>
<script type="text/coffeescript">
  # coffee time
</script>
Node




$ npm install coffee-script
REPL




$ coffee
101



# Assignment:
number   = 42
opposite = true
Conditions

if happy and knowsIt
  clapsHands()
  chaChaCha()
else
  showIt()

date = if friday then sue else jill

options or= defaults

number = -42 if opposite
Functions


square = (x) -> x * x

cube = (x) -> square(x) * x

fill = (container, liquid="coffee") ->
  "Filling the #{container} with #{liquid}..."

noop = ->
In JQuery



$('span').each ->
  it = $(this)
  if it.is('.style-1, .style-20') or
      not it.attr('class')
    it.replaceWith(it.html())
Data


# Arrays:
list = [1, 2, 3, 4, 5]

# Objects:
math =
  root:    Math.sqrt
  square: square
  cube:    (x) -> x * square x
modes = {ready: yes, balance: off}

bitlist   = [
  1, 0,   1
  0, 0,   1
  1, 1,   0
]
How True To JavaScript?
Compile


$ coffee -c some.coffee

# or just print out
$ coffee -p some.coffee
number   = 42
opposite = true

number = -42 if opposite

list = [1, 2, 3, 4, 5]

math =
  root:   Math.sqrt
  square: square
  cube:   (x) -> x * square x
var list, math, number, opposite;
number = 42;
opposite = true;
if (opposite) {
   number = -42;
}
list = [1, 2, 3, 4, 5];
math = {
   root: Math.sqrt,
   square: square,
   cube: function(x) {
     return x * square(x);
   }
};
Lexical Scopes & Safety



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


Thin Coat of Sugar

And Some Boilerplate
Sugar++


# Splats:
race = (winner, runners...) ->
  print winner, runners

# Existence:
alert "I knew it!" if elvis?
var race;
var __slice = Array.prototype.slice;
var race = function() {
   var runners, winner;
   winner = arguments[0], runners = 2 <= arguments.length ?
__slice.call(arguments, 1) : [];
   return print(winner, runners);
};
if (typeof elvis !== "undefined" && elvis !== null) {
   alert("I knew it!");
}
Expressions, Implicitness, Return
Unpacking



[first, second] = [1, 2, 3, 4]


_ref = [1, 2, 3], first = _ref[0], second = _ref[1];
{puts, inspect} = require 'util'


_ref2 = require('util'), puts = _ref2.puts, inspect =
_ref2.inspect;
Comprehensions!




cubes = (math.cube num for num in list)
var cubes;
cubes = (function() {
  var _i, _len, _results;
  _results = [];
  for (_i = 0, _len = list.length; _i < _len; _i++) {
    num = list[_i];
    _results.push(math.cube(num));
  }
  return _results;
})();
Comprehensive



yearsOld = max: 10, ida: 9, tim: 11

ages = for child, age of yearsOld
  child + " is " + age
Closing Over Loops



for filename in list
  do (filename) ->
    fs.readFile filename, (err, contents) ->
      compile filename, contents.toString()
Operator Names
CoffeeScript            JavaScript

is, isnt                ===, !==

and, or, not            &&, ||, !

true, yes, on           true

false, no, off          false

in, of                  in, N/A

@, this                 this

::                      prototype
Different Kinds of Else


● unless
● a?

●a ? b

● a ?= b

● a?.b
Classes
class Animal
  constructor: (@name) ->

 move: (meters) ->
   alert @name + " moved " + meters + "m."

class Snake extends Animal
  move: ->
    alert "Slithering..."
    super 5

class Horse extends Animal
  move: ->
    alert "Galloping..."
    super 45

sam = new Snake "Sammy the Python"
tom = new Horse "Tommy the Palomino"

sam.move()
tom.move()
var Animal, Horse, Snake, sam, tom;
var __hasProp = Object.prototype.hasOwnProperty, __extends =
function(child, parent) {
   for (var key in parent) { if (__hasProp.call(parent, key))
child[key] = parent[key]; }
   function ctor() { this.constructor = child; }
   ctor.prototype = parent.prototype;
   child.prototype = new ctor;
   child.__super__ = parent.prototype;
   return child;
};
Animal = (function() {
  function Animal(name) {
     this.name = name;
  }
  Animal.prototype.move = function(meters) {
     return alert(this.name + " moved " + meters + "m.");
  };
  return Animal;
})();
Snake = (function() {
  __extends(Snake, Animal);
  function Snake() {
     Snake.__super__.constructor.apply(this, arguments);
  }
  Snake.prototype.move = function() {
     alert("Slithering...");
     return Snake.__super__.move.call(this, 5);
  };
  return Snake;
})();
Binding => This


Account = (customer, cart) ->
  @customer = customer
  @cart = cart

  $('.shopping_cart').bind 'click', (event) =>
    @customer.purchase @cart
var Account;
var __bind = function(fn, me){ return function(){ return
fn.apply(me, arguments); }; };
Account = function(customer, cart) {
   this.customer = customer;
   this.cart = cart;
   return $('.shopping_cart').bind('click', __bind(function(event)
{
     return this.customer.purchase(this.cart);
   }, this));
};
And more...
● Literals: Functions, Objects and Arrays
● If, Else, Unless, and Conditional Assignment
● Splats...
● Array Slicing and Splicing

● Loops and Comprehensions

● Destructuring Assignment




●   Everything is an Expression
● Operators and Aliases
● Lexical Scoping and Variable Safety

● Classes, Inheritance, and Super

● Function Binding
● Switch and Try/Catch
● Chained Comparisons

● String Interpolation, Heredocs, and Block

   Comments
● Extended Regular Expressions

● Embedded JavaScript
Future/Now
Coding in Coffee

    sameness?

   seeing clearly..

  transparencies..

     choices...
Paths Ahead?




Harmony...
Tinkering Fun!



Node goodies: Zombie.js, Canvas, ...
Developing a
CommonJS Lib
$ npm link .

$ coffee --watch src

$ cake
Cakefile
{spawn, exec} = require 'child_process'

SRC = 'js/src'
LIB = 'js/lib'

task 'build', "compile coffee to js", -> build onErrorExit

task 'watch', "continously compile coffee to js", ->
  cmd = spawn "coffee", ["-cw", "-o", LIB, SRC]
  cmd.stdout.on "data", (data)-> process.stdout.write data
  cmd.on "error", onErrorExit

build = (cb)->
  console.log "Coffee compiling..."
  exec "rm -rf #{LIB} && coffee -c -l -b -o #{LIB} #{SRC}",
       (err, out)-> cb err

onErrorExit = (err)->
  if err
    process.stdout.write "#{err.stack}n"
    process.exit -1
Thanks!
Image Tributes (CC)


"Black as midnight on a moonless night."
Knight of the Holy Grail
Reflecting on a Sunday afternoon
In The Red Room
Fall down mountains, just don't fall on me
Midnight Black
Orrery Steam Punk Assemblage by urbandon
Steampunk Time Contraption

Weitere Àhnliche Inhalte

Was ist angesagt?

Swift - á„’á…©á†«á„Œá…Ą á„€á…©á†Œá„‡á…źá„’á…Ąá„†á…§á†« á„‡á…źá†«á„†á…§á†Œá„’á…” 언헐ᄐᅊᄂᅔ꺼 겉ᄋᅔ á„€á…©á†Œá„‡á…źá„’á…Ąá„€á…”
Swift - á„’á…©á†«á„Œá…Ą á„€á…©á†Œá„‡á…źá„’á…Ąá„†á…§á†« á„‡á…źá†«á„†á…§á†Œá„’á…” 언헐ᄐᅊᄂᅔ꺼 겉ᄋᅔ á„€á…©á†Œá„‡á…źá„’á…Ąá„€á…”Swift - á„’á…©á†«á„Œá…Ą á„€á…©á†Œá„‡á…źá„’á…Ąá„†á…§á†« á„‡á…źá†«á„†á…§á†Œá„’á…” 언헐ᄐᅊᄂᅔ꺼 겉ᄋᅔ á„€á…©á†Œá„‡á…źá„’á…Ąá„€á…”
Swift - á„’á…©á†«á„Œá…Ą á„€á…©á†Œá„‡á…źá„’á…Ąá„†á…§á†« á„‡á…źá†«á„†á…§á†Œá„’á…” 언헐ᄐᅊᄂᅔ꺼 겉ᄋᅔ á„€á…©á†Œá„‡á…źá„’á…Ąá„€á…”Suyeol Jeon
 
Functional Pe(a)rls - the Purely Functional Datastructures edition
Functional Pe(a)rls - the Purely Functional Datastructures editionFunctional Pe(a)rls - the Purely Functional Datastructures edition
Functional Pe(a)rls - the Purely Functional Datastructures editionosfameron
 
Rust ⇋ JavaScript
Rust ⇋ JavaScriptRust ⇋ JavaScript
Rust ⇋ JavaScriptIngvar Stepanyan
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsMichael Pirnat
 
Clustering com numpy e cython
Clustering com numpy e cythonClustering com numpy e cython
Clustering com numpy e cythonAnderson Dantas
 
Frege is a Haskell for the JVM
Frege is a Haskell for the JVMFrege is a Haskell for the JVM
Frege is a Haskell for the JVMjwausle
 
An Elephant of a Different Colour: Hack
An Elephant of a Different Colour: HackAn Elephant of a Different Colour: Hack
An Elephant of a Different Colour: HackVic Metcalfe
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015Binary Studio
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a bossgsterndale
 
珏äșŒèźČ PythonćŸș瀎
珏äșŒèźČ PythonćŸș瀎珏äșŒèźČ PythonćŸș瀎
珏äșŒèźČ PythonćŸș瀎juzihua1102
 
珏äșŒèźČ 鹄怇-PythonćŸș瀎
珏äșŒèźČ 鹄怇-PythonćŸș瀎珏äșŒèźČ 鹄怇-PythonćŸș瀎
珏äșŒèźČ 鹄怇-PythonćŸș瀎anzhong70
 
PHP 7 – What changed internally? (Forum PHP 2015)
PHP 7 – What changed internally? (Forum PHP 2015)PHP 7 – What changed internally? (Forum PHP 2015)
PHP 7 – What changed internally? (Forum PHP 2015)Nikita Popov
 
Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2Evgeny Borisov
 
Groovy
GroovyGroovy
GroovyZen Urban
 
Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a tryEugene Zharkov
 
Adventures in Optimization
Adventures in OptimizationAdventures in Optimization
Adventures in OptimizationDavid Golden
 
PubNative Tracker
PubNative TrackerPubNative Tracker
PubNative TrackerAndrew Djoga
 
Cycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveCycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveEugene Zharkov
 

Was ist angesagt? (20)

Swift - á„’á…©á†«á„Œá…Ą á„€á…©á†Œá„‡á…źá„’á…Ąá„†á…§á†« á„‡á…źá†«á„†á…§á†Œá„’á…” 언헐ᄐᅊᄂᅔ꺼 겉ᄋᅔ á„€á…©á†Œá„‡á…źá„’á…Ąá„€á…”
Swift - á„’á…©á†«á„Œá…Ą á„€á…©á†Œá„‡á…źá„’á…Ąá„†á…§á†« á„‡á…źá†«á„†á…§á†Œá„’á…” 언헐ᄐᅊᄂᅔ꺼 겉ᄋᅔ á„€á…©á†Œá„‡á…źá„’á…Ąá„€á…”Swift - á„’á…©á†«á„Œá…Ą á„€á…©á†Œá„‡á…źá„’á…Ąá„†á…§á†« á„‡á…źá†«á„†á…§á†Œá„’á…” 언헐ᄐᅊᄂᅔ꺼 겉ᄋᅔ á„€á…©á†Œá„‡á…źá„’á…Ąá„€á…”
Swift - á„’á…©á†«á„Œá…Ą á„€á…©á†Œá„‡á…źá„’á…Ąá„†á…§á†« á„‡á…źá†«á„†á…§á†Œá„’á…” 언헐ᄐᅊᄂᅔ꺼 겉ᄋᅔ á„€á…©á†Œá„‡á…źá„’á…Ąá„€á…”
 
Functional Pe(a)rls - the Purely Functional Datastructures edition
Functional Pe(a)rls - the Purely Functional Datastructures editionFunctional Pe(a)rls - the Purely Functional Datastructures edition
Functional Pe(a)rls - the Purely Functional Datastructures edition
 
Rust ⇋ JavaScript
Rust ⇋ JavaScriptRust ⇋ JavaScript
Rust ⇋ JavaScript
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
 
Clustering com numpy e cython
Clustering com numpy e cythonClustering com numpy e cython
Clustering com numpy e cython
 
Frege is a Haskell for the JVM
Frege is a Haskell for the JVMFrege is a Haskell for the JVM
Frege is a Haskell for the JVM
 
An Elephant of a Different Colour: Hack
An Elephant of a Different Colour: HackAn Elephant of a Different Colour: Hack
An Elephant of a Different Colour: Hack
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a boss
 
珏äșŒèźČ PythonćŸș瀎
珏äșŒèźČ PythonćŸș瀎珏äșŒèźČ PythonćŸș瀎
珏äșŒèźČ PythonćŸș瀎
 
珏äșŒèźČ 鹄怇-PythonćŸș瀎
珏äșŒèźČ 鹄怇-PythonćŸș瀎珏äșŒèźČ 鹄怇-PythonćŸș瀎
珏äșŒèźČ 鹄怇-PythonćŸș瀎
 
PHP 7 – What changed internally? (Forum PHP 2015)
PHP 7 – What changed internally? (Forum PHP 2015)PHP 7 – What changed internally? (Forum PHP 2015)
PHP 7 – What changed internally? (Forum PHP 2015)
 
Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2
 
Groovy
GroovyGroovy
Groovy
 
Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a try
 
Adventures in Optimization
Adventures in OptimizationAdventures in Optimization
Adventures in Optimization
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
PubNative Tracker
PubNative TrackerPubNative Tracker
PubNative Tracker
 
Functional programming with php7
Functional programming with php7Functional programming with php7
Functional programming with php7
 
Cycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveCycle.js: Functional and Reactive
Cycle.js: Functional and Reactive
 

Ähnlich wie Damn Fine CoffeeScript

CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScriptNone
 
Introduction Ă  CoffeeScript pour ParisRB
Introduction Ă  CoffeeScript pour ParisRB Introduction Ă  CoffeeScript pour ParisRB
Introduction Ă  CoffeeScript pour ParisRB jhchabran
 
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
 
Internal Project: Under the Hood
Internal Project: Under the HoodInternal Project: Under the Hood
Internal Project: Under the HoodVladik Khononov
 
DataMapper
DataMapperDataMapper
DataMapperYehuda Katz
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with GroovyArturo Herrero
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Coffee scriptisforclosers nonotes
Coffee scriptisforclosers nonotesCoffee scriptisforclosers nonotes
Coffee scriptisforclosers nonotesBrandon Satrom
 
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
 
Groovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony CodeGroovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony Codestasimus
 
AST - the only true tool for building JavaScript
AST - the only true tool for building JavaScriptAST - the only true tool for building JavaScript
AST - the only true tool for building JavaScriptIngvar Stepanyan
 
谈谈JavascriptèźŸèźĄ
谈谈JavascriptèźŸèźĄè°ˆè°ˆJavascriptèźŸèźĄ
谈谈JavascriptèźŸèźĄAlipay
 
谈谈JavascriptèźŸèźĄ
谈谈JavascriptèźŸèźĄè°ˆè°ˆJavascriptèźŸèźĄ
谈谈JavascriptèźŸèźĄAilsa126
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescriptDavid Furber
 

Ähnlich wie Damn Fine CoffeeScript (20)

CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
Introduction Ă  CoffeeScript pour ParisRB
Introduction Ă  CoffeeScript pour ParisRB Introduction Ă  CoffeeScript pour ParisRB
Introduction Ă  CoffeeScript pour ParisRB
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love Affair
 
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
 
Internal Project: Under the Hood
Internal Project: Under the HoodInternal Project: Under the Hood
Internal Project: Under the Hood
 
DataMapper
DataMapperDataMapper
DataMapper
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Coffee scriptisforclosers nonotes
Coffee scriptisforclosers nonotesCoffee scriptisforclosers nonotes
Coffee scriptisforclosers nonotes
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
Php functions
Php functionsPhp functions
Php functions
 
ddd+scala
ddd+scaladdd+scala
ddd+scala
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
 
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)
 
Groovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony CodeGroovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony Code
 
AST - the only true tool for building JavaScript
AST - the only true tool for building JavaScriptAST - the only true tool for building JavaScript
AST - the only true tool for building JavaScript
 
谈谈JavascriptèźŸèźĄ
谈谈JavascriptèźŸèźĄè°ˆè°ˆJavascriptèźŸèźĄ
谈谈JavascriptèźŸèźĄ
 
谈谈JavascriptèźŸèźĄ
谈谈JavascriptèźŸèźĄè°ˆè°ˆJavascriptèźŸèźĄ
谈谈JavascriptèźŸèźĄ
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescript
 

Mehr von niklal

Something Specific and Simple
Something Specific and SimpleSomething Specific and Simple
Something Specific and Simpleniklal
 
LĂ€nkad Data
LĂ€nkad DataLĂ€nkad Data
LĂ€nkad Dataniklal
 
(first '(Clojure.))
(first '(Clojure.))(first '(Clojure.))
(first '(Clojure.))niklal
 
Webbens Arkitektur
Webbens ArkitekturWebbens Arkitektur
Webbens Arkitekturniklal
 
Python utan-stodhjul-motorsag
Python utan-stodhjul-motorsagPython utan-stodhjul-motorsag
Python utan-stodhjul-motorsagniklal
 
Groovy Fly Through
Groovy Fly ThroughGroovy Fly Through
Groovy Fly Throughniklal
 

Mehr von niklal (6)

Something Specific and Simple
Something Specific and SimpleSomething Specific and Simple
Something Specific and Simple
 
LĂ€nkad Data
LĂ€nkad DataLĂ€nkad Data
LĂ€nkad Data
 
(first '(Clojure.))
(first '(Clojure.))(first '(Clojure.))
(first '(Clojure.))
 
Webbens Arkitektur
Webbens ArkitekturWebbens Arkitektur
Webbens Arkitektur
 
Python utan-stodhjul-motorsag
Python utan-stodhjul-motorsagPython utan-stodhjul-motorsag
Python utan-stodhjul-motorsag
 
Groovy Fly Through
Groovy Fly ThroughGroovy Fly Through
Groovy Fly Through
 

KĂŒrzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
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
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
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
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
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
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 

KĂŒrzlich hochgeladen (20)

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
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
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 

Damn Fine CoffeeScript

  • 1. Damn Fine CoffeeScript
  • 3. Some Kind of Holy Python Ruby JavaScrip t
  • 4. Raw var render = function (width, height, draw, filePath) { var canvas = new Canvas(width, height), ctx = canvas.getContext('2d'); draw.call(ctx); var out = fs.createWriteStream(filePath), stream = canvas.createPNGStream(); stream.on('data', function(chunk) { out.write(chunk); }); stream.on('end', function() { console.log("Created: " + filePath); }); };
  • 5. Brewed render = (width, height, draw, filePath) -> canvas = new Canvas(width, height) draw.call canvas.getContext '2d' out = fs.createWriteStream filePath stream = canvas.createPNGStream() stream.on 'data', (chunk) -> out.write chunk stream.on 'end', -> console.log "Created: #{filePath}"
  • 6. Basically ● function is () -> ● local variables ● indentation ● omittable parentheses
  • 7. True To JavaScript The golden rule of CoffeeScript is: "It's just JavaScript"
  • 8. Less Syntactic Noise stream.on('end', function() { console.log("Created: " + filePath); });
  • 9. stream.on 'end', -> console.log "Created: #{filePath}"
  • 10. My perspective Node A platform: JS machine + CommonJS stdlib
  • 14. Convert & Eval... <script src="/extras/coffee-script.js"></script> <script type="text/coffeescript"> # coffee time </script>
  • 15. Node $ npm install coffee-script
  • 17. 101 # Assignment: number = 42 opposite = true
  • 18. Conditions if happy and knowsIt clapsHands() chaChaCha() else showIt() date = if friday then sue else jill options or= defaults number = -42 if opposite
  • 19. Functions square = (x) -> x * x cube = (x) -> square(x) * x fill = (container, liquid="coffee") -> "Filling the #{container} with #{liquid}..." noop = ->
  • 20. In JQuery $('span').each -> it = $(this) if it.is('.style-1, .style-20') or not it.attr('class') it.replaceWith(it.html())
  • 21. Data # Arrays: list = [1, 2, 3, 4, 5] # Objects: math = root: Math.sqrt square: square cube: (x) -> x * square x
  • 22. modes = {ready: yes, balance: off} bitlist = [ 1, 0, 1 0, 0, 1 1, 1, 0 ]
  • 23. How True To JavaScript?
  • 24. Compile $ coffee -c some.coffee # or just print out $ coffee -p some.coffee
  • 25. number = 42 opposite = true number = -42 if opposite list = [1, 2, 3, 4, 5] math = root: Math.sqrt square: square cube: (x) -> x * square x
  • 26. var list, math, number, opposite; number = 42; opposite = true; if (opposite) { number = -42; } list = [1, 2, 3, 4, 5]; math = { root: Math.sqrt, square: square, cube: function(x) { return x * square(x); } };
  • 27. Lexical Scopes & Safety outer = 1 changeNumbers = -> inner = -1 outer = 10 inner = changeNumbers()
  • 28. var changeNumbers, inner, outer; outer = 1; changeNumbers = function() { var inner; inner = -1; return outer = 10; }; inner = changeNumbers();
  • 29. Syntactic Thin Coat of Sugar And Some Boilerplate
  • 30. Sugar++ # Splats: race = (winner, runners...) -> print winner, runners # Existence: alert "I knew it!" if elvis?
  • 31. var race; var __slice = Array.prototype.slice; var race = function() { var runners, winner; winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : []; return print(winner, runners); }; if (typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); }
  • 33. Unpacking [first, second] = [1, 2, 3, 4] _ref = [1, 2, 3], first = _ref[0], second = _ref[1];
  • 34. {puts, inspect} = require 'util' _ref2 = require('util'), puts = _ref2.puts, inspect = _ref2.inspect;
  • 35. Comprehensions! cubes = (math.cube num for num in list)
  • 36. var cubes; cubes = (function() { var _i, _len, _results; _results = []; for (_i = 0, _len = list.length; _i < _len; _i++) { num = list[_i]; _results.push(math.cube(num)); } return _results; })();
  • 37. Comprehensive yearsOld = max: 10, ida: 9, tim: 11 ages = for child, age of yearsOld child + " is " + age
  • 38. Closing Over Loops for filename in list do (filename) -> fs.readFile filename, (err, contents) -> compile filename, contents.toString()
  • 39. Operator Names CoffeeScript JavaScript is, isnt ===, !== and, or, not &&, ||, ! true, yes, on true false, no, off false in, of in, N/A @, this this :: prototype
  • 40. Different Kinds of Else ● unless ● a? ●a ? b ● a ?= b ● a?.b
  • 41. Classes class Animal constructor: (@name) -> move: (meters) -> alert @name + " moved " + meters + "m." class Snake extends Animal move: -> alert "Slithering..." super 5 class Horse extends Animal move: -> alert "Galloping..." super 45 sam = new Snake "Sammy the Python" tom = new Horse "Tommy the Palomino" sam.move() tom.move()
  • 42. var Animal, Horse, Snake, sam, tom; var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };
  • 43. Animal = (function() { function Animal(name) { this.name = name; } Animal.prototype.move = function(meters) { return alert(this.name + " moved " + meters + "m."); }; return Animal; })();
  • 44. Snake = (function() { __extends(Snake, Animal); function Snake() { Snake.__super__.constructor.apply(this, arguments); } Snake.prototype.move = function() { alert("Slithering..."); return Snake.__super__.move.call(this, 5); }; return Snake; })();
  • 45. Binding => This Account = (customer, cart) -> @customer = customer @cart = cart $('.shopping_cart').bind 'click', (event) => @customer.purchase @cart
  • 46. var Account; var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; Account = function(customer, cart) { this.customer = customer; this.cart = cart; return $('.shopping_cart').bind('click', __bind(function(event) { return this.customer.purchase(this.cart); }, this)); };
  • 48. ● Literals: Functions, Objects and Arrays ● If, Else, Unless, and Conditional Assignment
  • 49. ● Splats... ● Array Slicing and Splicing ● Loops and Comprehensions ● Destructuring Assignment ● Everything is an Expression
  • 50. ● Operators and Aliases ● Lexical Scoping and Variable Safety ● Classes, Inheritance, and Super ● Function Binding
  • 51. ● Switch and Try/Catch ● Chained Comparisons ● String Interpolation, Heredocs, and Block Comments ● Extended Regular Expressions ● Embedded JavaScript
  • 53. Coding in Coffee sameness? seeing clearly.. transparencies.. choices...
  • 55. Tinkering Fun! Node goodies: Zombie.js, Canvas, ...
  • 57. $ npm link . $ coffee --watch src $ cake
  • 58. Cakefile {spawn, exec} = require 'child_process' SRC = 'js/src' LIB = 'js/lib' task 'build', "compile coffee to js", -> build onErrorExit task 'watch', "continously compile coffee to js", -> cmd = spawn "coffee", ["-cw", "-o", LIB, SRC] cmd.stdout.on "data", (data)-> process.stdout.write data cmd.on "error", onErrorExit build = (cb)-> console.log "Coffee compiling..." exec "rm -rf #{LIB} && coffee -c -l -b -o #{LIB} #{SRC}", (err, out)-> cb err onErrorExit = (err)-> if err process.stdout.write "#{err.stack}n" process.exit -1
  • 60. Image Tributes (CC) "Black as midnight on a moonless night." Knight of the Holy Grail Reflecting on a Sunday afternoon In The Red Room Fall down mountains, just don't fall on me Midnight Black Orrery Steam Punk Assemblage by urbandon Steampunk Time Contraption