There are two types of functions in Imba, methods and blocks. Imba automatically returns the last expression of the function.
def randomize
Math.random
var self = {};
self.randomize = function (){
return Math.random();
};
# A single argument
def square num
num * num
var self = {};
// A single argument
self.square = function (num){
return num * num;
};
# optional arguments
def call url, method = 'GET'
# do something here
var self = {};
// optional arguments
self.call = function (url,method){
// do something here
};
# Variadic arguments
def race winner, *rest
"{winner} beat {rest.join(', ')}"
var self = {};
// Variadic arguments
self.race = function (winner){
var $0 = arguments, i = $0.length;
var rest = new Array(i>1 ? i-1 : 0);
while(i>1) rest[--i - 1] = $0[i];
return ("" + winner + " beat " + rest.join(', '));
};
# Optional arguments, with callback
def save data, options = {}, &callback
# do something here
var self = {};
// Optional arguments, with callback
self.save = function (data,options,callback){
// do something here
};
# Named parameters
def animate values, ease: 'linear', duration: 1
# do something here
var self = {};
// Named parameters
self.animate = function (values,pars){
// do something here
};
var square = do |v| v * v
var square = function(v) { return v * v; };
Blocks are like anonymous function expressions in JavaScript. They can be assigned and passed around. They have their own lexical scope / closure, but no dynamic scope. This means that self (implicit and explicit) inside the block still refers to the self of the outer scope.
Blocks can be passed in directly when calling functions, as the last argument.
[1,2,3,4].map do |num| num * 2
item.save do
# callback trigger when item is saved?
console.log 'item was saved'
var self = {};
[1,2,3,4].map(function(num) { return num * 2; });
self.item().save(function() {
// callback trigger when item is saved?
return console.log('item was saved');
});