Damn Fine CoffeeScript

2,073 views
1,962 views

Published on

Introduction to CoffeeScript held at GTUG Sthlm May 2011.

Published in: Technology, Business
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,073
On SlideShare
0
From Embeds
0
Number of Embeds
6
Actions
Shares
0
Downloads
39
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide

Damn Fine CoffeeScript

  1. 1. Damn Fine CoffeeScript
  2. 2. FocusLanguage
  3. 3. Some Kind of Holy Python RubyJavaScrip t
  4. 4. Rawvar 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. 5. Brewedrender = (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. 6. Basically● function is () ->● local variables● indentation● omittable parentheses
  7. 7. True To JavaScriptThe golden rule of CoffeeScript is: "Its just JavaScript"
  8. 8. Less Syntactic Noisestream.on(end, function() { console.log("Created: " +filePath);});
  9. 9. stream.on end, -> console.log "Created: #{filePath}"
  10. 10. My perspectiveNodeA platform: JS machine + CommonJS stdlib
  11. 11. Runtimes
  12. 12. Its justCoffee In Coffee
  13. 13. BrowserJust JS (generated)
  14. 14. Convert & Eval...<script src="/extras/coffee-script.js"></script><script type="text/coffeescript"> # coffee time</script>
  15. 15. Node$ npm install coffee-script
  16. 16. REPL$ coffee
  17. 17. 101# Assignment:number = 42opposite = true
  18. 18. Conditionsif happy and knowsIt clapsHands() chaChaCha()else showIt()date = if friday then sue else jilloptions or= defaultsnumber = -42 if opposite
  19. 19. Functionssquare = (x) -> x * xcube = (x) -> square(x) * xfill = (container, liquid="coffee") -> "Filling the #{container} with #{liquid}..."noop = ->
  20. 20. In JQuery$(span).each -> it = $(this) if it.is(.style-1, .style-20) or not it.attr(class) it.replaceWith(it.html())
  21. 21. Data# Arrays:list = [1, 2, 3, 4, 5]# Objects:math = root: Math.sqrt square: square cube: (x) -> x * square x
  22. 22. modes = {ready: yes, balance: off}bitlist = [ 1, 0, 1 0, 0, 1 1, 1, 0]
  23. 23. How True To JavaScript?
  24. 24. Compile$ coffee -c some.coffee# or just print out$ coffee -p some.coffee
  25. 25. number = 42opposite = truenumber = -42 if oppositelist = [1, 2, 3, 4, 5]math = root: Math.sqrt square: square cube: (x) -> x * square x
  26. 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. 27. Lexical Scopes & Safetyouter = 1changeNumbers = -> inner = -1 outer = 10inner = changeNumbers()
  28. 28. var changeNumbers, inner, outer;outer = 1;changeNumbers = function() { var inner; inner = -1; return outer = 10;};inner = changeNumbers();
  29. 29. SyntacticThin Coat of SugarAnd Some Boilerplate
  30. 30. Sugar++# Splats:race = (winner, runners...) -> print winner, runners# Existence:alert "I knew it!" if elvis?
  31. 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!");}
  32. 32. Expressions, Implicitness, Return
  33. 33. Unpacking[first, second] = [1, 2, 3, 4]_ref = [1, 2, 3], first = _ref[0], second = _ref[1];
  34. 34. {puts, inspect} = require util_ref2 = require(util), puts = _ref2.puts, inspect =_ref2.inspect;
  35. 35. Comprehensions!cubes = (math.cube num for num in list)
  36. 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. 37. ComprehensiveyearsOld = max: 10, ida: 9, tim: 11ages = for child, age of yearsOld child + " is " + age
  38. 38. Closing Over Loopsfor filename in list do (filename) -> fs.readFile filename, (err, contents) -> compile filename, contents.toString()
  39. 39. Operator NamesCoffeeScript JavaScriptis, isnt ===, !==and, or, not &&, ||, !true, yes, on truefalse, no, off falsein, of in, N/A@, this this:: prototype
  40. 40. Different Kinds of Else● unless● a?●a ? b● a ?= b● a?.b
  41. 41. Classesclass Animal constructor: (@name) -> move: (meters) -> alert @name + " moved " + meters + "m."class Snake extends Animal move: -> alert "Slithering..." super 5class Horse extends Animal move: -> alert "Galloping..." super 45sam = new Snake "Sammy the Python"tom = new Horse "Tommy the Palomino"sam.move()tom.move()
  42. 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. 43. Animal = (function() { function Animal(name) { this.name = name; } Animal.prototype.move = function(meters) { return alert(this.name + " moved " + meters + "m."); }; return Animal;})();
  44. 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. 45. Binding => ThisAccount = (customer, cart) -> @customer = customer @cart = cart $(.shopping_cart).bind click, (event) => @customer.purchase @cart
  46. 46. var Account;var __bind = function(fn, me){ return function(){ returnfn.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));};
  47. 47. And more...
  48. 48. ● Literals: Functions, Objects and Arrays● If, Else, Unless, and Conditional Assignment
  49. 49. ● Splats...● Array Slicing and Splicing● Loops and Comprehensions● Destructuring Assignment● Everything is an Expression
  50. 50. ● Operators and Aliases● Lexical Scoping and Variable Safety● Classes, Inheritance, and Super● Function Binding
  51. 51. ● Switch and Try/Catch● Chained Comparisons● String Interpolation, Heredocs, and Block Comments● Extended Regular Expressions● Embedded JavaScript
  52. 52. Future/Now
  53. 53. Coding in Coffee sameness? seeing clearly.. transparencies.. choices...
  54. 54. Paths Ahead?Harmony...
  55. 55. Tinkering Fun!Node goodies: Zombie.js, Canvas, ...
  56. 56. Developing aCommonJS Lib
  57. 57. $ npm link .$ coffee --watch src$ cake
  58. 58. Cakefile{spawn, exec} = require child_processSRC = js/srcLIB = js/libtask build, "compile coffee to js", -> build onErrorExittask 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", onErrorExitbuild = (cb)-> console.log "Coffee compiling..." exec "rm -rf #{LIB} && coffee -c -l -b -o #{LIB} #{SRC}", (err, out)-> cb erronErrorExit = (err)-> if err process.stdout.write "#{err.stack}n" process.exit -1
  59. 59. Thanks!
  60. 60. Image Tributes (CC)"Black as midnight on a moonless night."Knight of the Holy GrailReflecting on a Sunday afternoonIn The Red RoomFall down mountains, just dont fall on meMidnight BlackOrrery Steam Punk Assemblage by urbandonSteampunk Time Contraption

×