Skip to content

Instantly share code, notes, and snippets.

@lcaballero
Created December 10, 2013 18:22
Show Gist options
  • Save lcaballero/7895396 to your computer and use it in GitHub Desktop.
Save lcaballero/7895396 to your computer and use it in GitHub Desktop.
Coffee Quick Examples (mostly just a text file with coffee, js, and notes thrown together).
# Coffee Script
# Overview
# variable that is closed, var(ed) and not exposed to the global, or window
# object which reduces leaking variables
variable = "value"
# Thin Arrow
# Function one-liners
# The last expression in the funciton is implicity returned, in other word,
# you don't need an explicit return statement
f = -> "bar"
foo = ->
# Multi-line
"bar"
# multiple arguments
times = (a, b) -> a * b
# default arguments
times = (a = 2, b = 3, c = 4) -> a*a + b*b + c*c
# multiple (variadic) arguments
sum = (nums...) ->
result = 0
for n in nums
result += n
result
# calling a Function
n = sum 1, 2, 3
console.log "sum: " + n
# Very simple example showing off how the @ alias changes with the use of
# the 'fat' and 'thin' arrow
@greeting = "yo "
obj = {
greeting: "Hello "
greet: (name) -> @greeting + name
show: (name) => @greeting + name
}
console.log obj.greet("me")
console.log obj.show("yo")
############################################################################
# Object Literals
############################################################################
object1 = { one: 1, two : 2 }
# Without braces
object2 = one: 1, two: 2
# using newlines instead of commas
object3 =
one: 1
two: 2
# Calling a function with an object literal
console.log prop:"value"
############################################################################
# Array liters
############################################################################
# nothing really new here -- normal JS array literal
array1 = [1, 2, 3]
# now without commas using newline delimitters
array2 = [
1
2
3
]
# trailing comma problem
array3 = [ 1, 2, 3, ]
############################################################################
# Control flow 'if'
############################################################################
if true == true
console.log "True dat"
# Comparisons changed from != to !== in JS
if true != true then console.log "Panic yo."
# in JS this would output the log, but == is changed to === in JS
if "" == 0 then console.log "Comparing '' to 0 is true....in JS"
console.log "" == 0
# ternary equivalent
if 1 > 0 then console.log "OK" else console.log "Y2K!"
# suffix statements
proximity = 1
console.log "too close...." if proximity < .5
proximity = .1
console.log "too close...." if proximity < .5
# readable logical keywords
if not true then console.log "Panic"
unless true then console.log "Panic"
if true is 1 then console.log "Type coersion ... yet again."
if true isnt true then console.log "Then what is true?!"
############################################################################
# String Interpolation
############################################################################
favor = "blue"
like = "what color do you favor? #{favor}?"
console.log like
############################################################################
# Loop Comprehenison
############################################################################
for state in ["Colorado", "California", "Maine", "New York"]
console.log state
# Notice the index is the second identifier
for state,i in ["Colorado", "California", "Maine", "New York"]
console.log "#{i}: #{state}"
console.log state for state in ["Colorado", "California", "Maine", "New York"]
console.log "Filter example"
console.log state for state in ["Colorado", "California", "Maine", "New York"] when state[0] is "C"
console.log "Filter and object comprehension"
states = [
{ name: "California", tz: "pst" }
{ name: "Colorado", tz: "mnt" }
{ name: "Maine", tz: "est" }
{ name: "New York", tz: "est" }
]
console.log state.name for state in states when state.tz is "est"
# Low level loop that behaves like map()
num = 5
piggies = while num -= 1
console.log "#{num} piggies ran all the way home"
############################################################################
# Looping with deconstruction:
############################################################################
stuff = [
{ AlarmId: 1, x:1}
{ AlarmId: 2, x:2},
]
logAlarmIds = ->
a = ({id:AlarmId, m:x} for {AlarmId, x} in $scope.cards)
### yields =>
[
{ id:1, x:1 },
{ id:2, x:2 }
]
###
############################################################################
# Arrays
############################################################################
# inclusive
range = [1..5]
console.log range
# exclusive
range = [1...5]
console.log range
# ranges converted to slice when after an array
first2 = ["one", "two", "threee"][0..1]
console.log first2
letters = "abcdef"[0..2]
console.log letters
deep = {
a: {
b: {
c: "should now find a.b.c"
}
}
}
console.log deep.a.b.c
console.log deep.a?.b?.c?
# showing off the '::' operator
Array::type = -> console.log "Off prototype"
Array.prototype.type()
############################################################################
# Animals
############################################################################
class Animal
constructor: (@name = "Turle") ->
speak: () -> console.log @name
turtle = new Animal
turtle.speak()
lion = new Animal("Lion")
lion.speak()
############################################################################
# Mixins and Includes
############################################################################
############################################################################
# CoffeeScript Idioms
############################################################################
# For loop in js
# -------------------------------------------------------------------------
# for (var i=0; i < array.length; i++)
# myFunc(array[i])
#
# or
#
# array.forEach(function(item, i) {
# myFunc(item)
# })
# Coffee:
console.log a for a in [1,2,3]
# JS Mapping
# -------------------------------------------------------------------------
# var result = []
# for (var i = 0; i < array.length; i++) {
# result.push(array[i].name)
# }
# Coffee Mapping
# -------------------------------------------------------------------------
array = [{name:"test"}, {name:'fake'}, {name:'nope'}]
result = (item.name for item in array)
# JS Select
# -------------------------------------------------------------------------
# var result = []
# for (var i = 0; i < array.length; i++) {
# if (array[i].name == "test") {
# result.push(array[i])
# }
# }
# ES5 -- only == filter()
# result = array.filter(function(item,i) {
# return item.name == "test"
# })
# Select Select
#
# The parens are required otherwise the 'result' will be the last item in
# the array.
# -------------------------------------------------------------------------
array = [{name:"test"}, {name:'fake'}, {name:'nope'}]
result = (item for item in array when item.name is "test")
# Combining Control Flow and loop comprehesion:
# -------------------------------------------------------------------------
passed = []
failed = []
scores = [29, 58, 76, 83, 88, 90]
(if score > 60 then passed else failed).push score for score in scores
# or
for score in scores
(if score > 60 then passed else failed).push score
############################################################################
# Includes
############################################################################
# JS:
# --------------------------------------------------------------------------
# var included = (array.indexOf("test") != -1)
# Coffee:
# --------------------------------------------------------------------------
included = "test" in array
# Alternative:
# --------------------------------------------------------------------------
included = "a long test string".indexOf("test") isnt -1
# Alternative:
# --------------------------------------------------------------------------
string = "a long test string"
included = !!~ string.indexOf "test"
############################################################################
# Property Iteration
############################################################################
# JS
# --------------------------------------------------------------------------
# var object = {one:1, two:2}
# for (var key in object) console.log(key + " = " + object[key])
# Coffee
object = {one:1, two:2}
console.log("#{key} = #{value}") for key, value of object
############################################################################
# Passing multiple values to func (ex. min/max) via variadic
############################################################################
console.log "max: " + Math.max([14, 35, -7, 46, 98]...)
console.log "min: " + Math.min([14, 35, -7, 46, 98]...)
console.log([14, 35, -7, 46, 98]...)
############################################################################
# Multiple Arguments
############################################################################
############################################################################
# And / Or
############################################################################
string = "migrating coconuts"
console.log string == string
console.log string is string
a = {}
b = "mocking bird"
c = a or b
console.log c
d = null
d or= b
console.log d
############################################################################
# Destructuring Assignments
############################################################################
someObject = { a: 'value for a', b: 'value for b' }
{a, b} = someObject
console.log "a = #{a}, b = #{b}"
{join, resolve} = require 'path'
console.log join('/Users', 'Lucas')
############################################################################
# External Libraries
############################################################################
############################################################################
# Private Variables
############################################################################
type = do ->
types = [
"Boolean"
"Number"
"String"
"Function"
"Array"
"Date"
"RegExp"
"Undefined"
"Null"
]
classToType = {}
for name in types
classToType["[object " + name + "]"] = name.toLowerCase()
# Return a function
(obj) ->
strType = Object::toString.call(obj)
classToType[strType] or "object"
console.log type(false)
############################################################################
# Compiling CoffeeScript
############################################################################
###
%> coffee --compile --output lib src
# Coffee Gotchas:
```
class TreeMap
# Static access of the Tree Map default configuration
@DEFAULT_DRAW_CONFIG :
width: 649
height: 239
classes: ("BlueSeries#{n}" for n in [0..10])
constructor: (results, drawConf) ->
@drawConfig = _.extend({}, TreeMap.DEFAULT_DRAW_CONFIG, drawConf or {})
```
The ':' or the '=' make no difference to the resulting compiled savascript:
```
@DEFAULT_DRAW_CONFIG :
```l
There is a difference between these two lines
```
a = ("BlueSeries#{n}" for n in [0..10])
b = "BlueSeries#{n}" for n in [0..10]
```
`a` is an array
`b` is a string
simply because of the parents '(....)'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment