Skip to content

Instantly share code, notes, and snippets.

@joyrexus
Created March 12, 2013 21:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joyrexus/5147449 to your computer and use it in GitHub Desktop.
Save joyrexus/5147449 to your computer and use it in GitHub Desktop.
Literate CoffeeScript sample.

Quick Coffee

Examples and such to accompany J. Ashkenas' dotJS talk.

Preliminaries

{ok} = require 'assert'

A better comparator. See harmony docs.

egal = (a, b) ->
  if a is b
    a isnt 0 or 1/a is 1/b
  else
    a isnt a and b isnt b

eq = (a, b, msg) -> ok egal(a, b), msg ? a + ' is not ' + b

Yeah, we've got python roots.

print = console.log

Samples

Catch error resulting from missing object/property.

result = try
  missing.property
catch error
  "ERROR!"

Self-explanatory one-liners.

eq result, "ERROR!"

eq 3, if one? then 2 else 3

eq 3, if one? 
  2 
else 
  a = "alpha"
  if a?
    3

one = 1

eq 2, if one? then 2 else 3

eq 4, if b? then 2 else if c? then 3 else 4

eq [1..10][i-1], i for i in [1..10]

Sum the squares of first ten integers.

square = (x) -> x * x

eq 385, (square i for i in [1..10]).reduce (x, y) -> x + y

Ramping up

A quick demo of classes, decorators, and the fat arrow.

class Pirate 

  constructor: (@name) -> 

  hi: (name) ->
    "Hello there #{name}!"

  # Wrapped function.
  sayWithVigor = (f) -> 
    (name) ->           # new function to return
      f(name) + "!!!"

  ahoy: sayWithVigor (name) -> 
    "Ahoy #{name}"

  do: (f) -> f()

Note use of "fat arrow" function binding (=>) in the say method below. We're binding @name (i.e., this.name) to the unnamed method being passed as argument.

class Prisoner

  constructor: (@name, @captor) -> 

  say: (words) -> 
    "#{@name} says: #{words} ... #{@captor.name}'s got me!"

  hears: ->
    @captor.do => 
      "Greetings, I am #{@captor.name}! You must be #{@name}. " +
      "#{@captor.ahoy @name}"

Here's what happens.

ahab = new Pirate('Ahab')
mary = new Prisoner('Mary', captor=ahab)

eq ahab.name, "Ahab"

eq ahab.hi('Missy'), "Hello there Missy!"

eq ahab.ahoy('Missy'),
  "Ahoy Missy!!!"

eq mary.say("Oh no"),
  "Mary says: Oh no ... Ahab's got me!"

eq mary.hears(),
  "Greetings, I am Ahab! You must be Mary. Ahoy Mary!!!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment