Kaffeine

Extended Javascript for Pros

Fork me on GitHub

Function Extensions

implicit_functions

The function keyword can be optionally omitted, along with empty argument lists:

ok = (timeout) {
  sendNote()
  setTimeout { run() }, timeout
  return true
}

Gotcha

according to this definition {} or { } could be a function or an object, so to avoid ambiguity: it is defined to be an object.

To express an empty function, make sure it has some code within. For example:

{;}
{null}
function() {}

implicit return

The last statement of a function will be automagically returned (Ruby style). For example

getName = { @name } 

This will only work for returnable statements, i.e. variables, objects and functions. So an final if statement will result no return value

getName = { 
  if truthy 
    @name 
} 

gotcha

A constructor must not return an array or an object to work properly. So make sure you do not accidently do this

Animal = (name) { @name = name @friends = [] // wrong => new Animal() won’t work properly }

Animal = (name) { @friends = []
@name = name // better => providing you’re sure that name will be a string or null }

Animal = (name) { @friends = []
@name = name
return // best => cannot break }

hash alias

Kaffeine provides # shortcut for referring to the first argument in a function. Additionally, #n refers to the nth argument (n >= 0). Useful for terse function definitions:

//
square = { 
  #*# 
}
//
times = { 
  #*#1 
}

default arguments

This module allows support for ruby-syle defaults for null or undefined arguments. Note, this uses non strict comparison with null, meaning falsy values such as 0 or “” can be used as default.

fn = 
(x=1, a=0) {
  log x, a
}
fn 5  // => 5, 0