Abstractions around first class functions like augmenting and inspecting functions as well as to control function calls like dealing with asynchronous control flows.

Methods

(inner) addToObject(f, obj, name) → {function}

Attaches a given function to an object as a method.

Parameters:
NameTypeDescription
ffunction

The function to create a method from.

objobject

The object to attach the method to.

namestring

The name of the method once attached to the object.

Returns:
Type: 
function

(inner) all(obj) → {Array.<String>}

Returns all property names of a given object that reference a function.

Parameters:
NameTypeDescription
objObject

The object to return the property names for.

Returns:
Type: 
Array.<String>
Example
var obj = {foo: 23, bar: function() { return 42; }};
all(obj) // => ["bar"]

(inner) argumentNames(f) → {Array.<String>}

Extract the names of all parameters for a given function object.

Parameters:
NameTypeDescription
ffunction

The function object to extract the parameter names of.

Returns:
Type: 
Array.<String>
Example
argumentNames(function(arg1, arg2) {}) // => ["arg1","arg2"]
argumentNames(function() {}) // => []

(inner) asScript(func, optVarMappingopt) → {function}

Lifts func to become a Closure, that is that free variables referenced in func will be bound to the values of an object that can be passed in as the second parameter. Keys of this object are mapped to the free variables.

Please see Closure for a more detailed explanation and examples.

Parameters:
NameTypeAttributesDescription
funcfunction

The function to create a closure from.

optVarMappingobject<optional>

The var mapping that defines how the free variables inside the closure are to be bound.

Returns:
Type: 
function

(inner) asScriptOf(f, obj, optNameopt, optMappingopt) → {function}

Like asScript but makes f a method of obj as optName or the name of the function.

Parameters:
NameTypeAttributesDescription
ffunction

The function to create a method from.

objobject

The object to attach the method to.

optNamestring<optional>

The name of the method once attached to the object.

optMappingobject<optional>

The var mapping that defines how the free variables inside the method are to be bound.

Returns:
Type: 
function

(inner) compose(…functions) → {function}

Composes a set of synchronous functions: compose(f,g,h)(arg1, arg2) = h(g(f(arg1, arg2)))

Parameters:
NameTypeAttributesDescription
functionsfunction<repeatable>

The collections of functions to compose.

Returns:
Type: 
function
Example
compose(
  function(a,b) { return a+b; },
  function(x) {return x*4}
)(3,2) // => 20

(inner) composeAsync(…functions) → {function}

Composes functions that are asynchronous and expecting continuations to be called in node.js callback style (error is first argument, real arguments follow). A call like composeAsync(f,g,h)(arg1, arg2) has a flow of control like: f(arg1, arg2, thenDo1) -> thenDo1(err, fResult) -> g(fResult, thenDo2) -> thenDo2(err, gResult) -> -> h(fResult, thenDo3) -> thenDo2(err, hResult)

Parameters:
NameTypeAttributesDescription
functionsfunction<repeatable>

The collections of asynchronous functions to compose.

Returns:
Type: 
function
Example
composeAsync(
  function(a,b, thenDo) { thenDo(null, a+b); },
  function(x, thenDo) { thenDo(x*4); }
 )(3,2, function(err, result) { alert(result); });

(inner) createQueue(id, workerFunc) → {WorkerQueue}

Creates and initializes a worker queue.

Parameters:
NameTypeDescription
idstring

The identifier for the worker queue.

workerFuncfunction

Asynchronous function to process queued tasks.

Returns:
Type: 
WorkerQueue
Example
var sum = 0;
var q = createQueue("example-queue", function(arg, thenDo) { sum += arg; thenDo(); });
q.pushAll([1,2,3]);
queues will be remembered by their name
createQueue("example-queue").push(4);
sum // => 6

(inner) curry(func)

Return a version of func with args applied.

Parameters:
NameTypeDescription
funcfunction

The function to curry.

Example
var add1 = (function(a, b) { return a + b; }).curry(1);
add1(3) // => 4

(inner) debounce(wait, func, immediate)

Call func after wait milliseconds elapsed since the last invocation. Unlike throttle an invocation will restart the wait period. This is useful if you have a stream of events that you want to wait for to finish and run a subsequent function afterwards. When you pass arguments to the debounced functions then the arguments from the last call will be use for the invocation.

Parameters:
NameTypeDescription
waitnumber

The duration in milliseconds to wait until the next invocation.

funcfunction

The founction to be wrapped.

immediateBoolean

When set to true, immediately call func but when called again during wait before wait ms are done nothing happens. E.g. to not exec a user invoked action twice accidentally.

Example
var start = Date.now();
var f = debounce(200, function(arg1) {
  alert("running after " + (Date.now()-start) + "ms with arg " + arg1);
});
f("call1");
delay(curry(f, "call2"), 0.1);
delay(curry(f, "call3"), 0.15);
// => Will eventually output: "running after 352ms with arg call3"

(inner) debounceNamed(name)

Like debounce but remembers the debounced function once created and repeated calls to debounceNamed with the identical name will use the same debounced function. This allows to debounce functions in a central place that might be called various times in different contexts without having to manually store the debounced function.

Parameters:
NameTypeDescription
nameString

The identifier for the debounced closure.

See
  • debounce

(inner) delay(func, timeout)

Delays calling func for timeout seconds(!).

Parameters:
NameTypeDescription
funcfunction

Function object to delay execution for.

timeoutnumber

The duration in milliseconds to delay the execution for.

Example
(function() { alert("Run in the future!"); }).delay(1);

(inner) either()

Accepts multiple functions and returns an array of wrapped functions. Those wrapped functions ensure that only one of the original function is run (the first on to be invoked).

This is useful if you have multiple asynchronous choices of how the control flow might continue but want to ensure that a continuation is only triggered once, like in a timeout situation:

function outerFunction(callback) {
  function timeoutAction() { callback(new Error('timeout!')); }
  function otherAction() { callback(null, "All OK"); }
  setTimeout(timeoutAction, 200);
  doSomethingAsync(otherAction);
}

To ensure that callback only runs once you would normally have to write boilerplate like this:

var ran = false;
function timeoutAction() { if (ran) return; ran = true; callback(new Error('timeout!')); }
function otherAction() { if (ran) return; ran = true; callback(null, "All OK"); }

Since this can get tedious an error prone, especially if more than two choices are involved, either can be used like this:

Example
function outerFunction(callback) {
  var actions = either(
    function() { callback(new Error('timeout!')); },
    function() { callback(null, "All OK"); });
  setTimeout(actions[0], 200);
  doSomethingAsync(actions[1]);
}

(inner) eitherNamed(name, func) → {function}

Works like either but usage does not require to wrap all functions at once.

Parameters:
NameTypeDescription
namestring
funcfunction

The function to wrap.

See
  • either
Returns:
Type: 
function
Example
var log = "", name = "either-example-" + Date.now();
function a() { log += "aRun"; };
function b() { log += "bRun"; };
function c() { log += "cRun"; };
setTimeout(eitherNamed(name, a), 100);
setTimeout(eitherNamed(name, b), 40);
setTimeout(eitherNamed(name, c), 80);
setTimeout(function() { alert(log); /\* => "bRun" *\/ }, 150);

(inner) extractBody(func) → {String}

Useful when you have to stringify code but not want to construct strings by hand.

Parameters:
NameTypeDescription
funcfunction

The function to extract the body from.

Returns:
Type: 
String
Example
extractBody(function(arg) {
  var x = 34;
  alert(2 + arg);
}) => "var x = 34;\nalert(2 + arg);"

(inner) flip(f) → {function}

Swaps the first two args

Parameters:
NameTypeDescription
ffunction

Function to flip the arguments for.

Returns:
Type: 
function
Example
flip(function(a, b, c) {
  return a + b + c; })(' World', 'Hello', '!') // => "Hello World!"

(inner) fromString(funcOrString) → {function}

Creates a function from a string.

Parameters:
NameTypeDescription
funcOrStringstring | function

A function or string to create a function from.

Returns:
Type: 
function
Example
fromString("function() { return 3; }")() // => 3

(inner) functionNames(klass) → {Array.<string>}

Treats passed function as class (constructor).

Parameters:
NameTypeDescription
klassfunction

The function to check for as a class.

Returns:
Type: 
Array.<string>
Example
var Klass1 = function() {}
Klass1.prototype.foo = function(a, b) { return a + b; };
Klass1.prototype.bar = function(a) { return this.foo(a, 3); };
Klass1.prototype.baz = 23;
functionNames(Klass1); // => ["bar","foo"]

(inner) getOriginal(wrappedFunc) → {function}

Get the original function that was augmented by wrap. getOriginal will traversed as many wrappers as necessary.

Parameters:
NameTypeDescription
wrappedFuncfunction

The wrapped function to retrieve the original from.

Returns:
Type: 
function

(inner) getVarMapping()

Returns the var mapping for a given lively closure.

(inner) guard(func) → {function}

Similar to debounce but instead of taking a custom time interval we instead wait until the execution of the wrapped function has finished.

Parameters:
NameTypeDescription
funcfunction

The function to guard the execution for.

Returns:

The wrapped function.

Type: 
function

(inner) guardNamed(name, func) → {function}

Like guard but remembers the last invocation via a name. Repeated calls to guardNamed with the same name will therefore be guarded as if we were calling the same guarded closure repeatedly.

Parameters:
NameTypeDescription
namestring

The identifier to guard by.

funcfunction

The function to guard.

Returns:

The guarded function resolved via the identifier.

Type: 
function

(inner) isNativeFunction(fn) → {boolean}

Returns wether or not a given function is a "built in". Built in functions are native to the runtime and their implementation can not be inspected from Javascript.

Parameters:
NameTypeDescription
fnfunction

The function to check for.

Returns:
Type: 
boolean

(inner) localFunctionNames(func) → {Array.<string>}

Return the names of the functions defined on the prototype.

Parameters:
NameTypeDescription
funcfunction

The function whos prototype to check.

Returns:
Type: 
Array.<string>

(inner) logCalls(func, isUrgent) → {function}

Wraps a function to log to the console every time it is applied.

Parameters:
NameTypeDescription
funcfunction

The function to wrap.

isUrgentboolean

Wether or not the applications should logged as warnings or plain logs.

Returns:
Type: 
function

(inner) logCompletion() → {function}

Wrap a function to log to console once it succesfully completes.

Returns:
Type: 
function

(inner) logErrors(func, prefix) → {function}

Wraps a given function to automatically log all the errors encountered to the console.

Parameters:
NameTypeDescription
funcfunction

The function to wrap.

prefixstring

The log prefix to pass to the console.warn() call.

Returns:
Type: 
function

(inner) notYetImplemented(what, strict)

Throws a well behaved error on purpopse, when accessing unimplemented functionality.

Parameters:
NameTypeDefaultDescription
whatstring

The thing, which is not implemented.

strictbooleanfalse

Whether or not to throw an actual error.

Example
notYetImplemented('5D rendering', true)

(inner) once(func) → {function}

Ensure that func is only executed once. Multiple calls will not call func again but will return the original result.

Parameters:
NameTypeDescription
funcfunction

The function to be wrapped to only execute once.

Returns:
Type: 
function

(inner) own(object) → {Array.<String>}

Returns all local (non-prototype) property names of a given object that reference a function.

Parameters:
NameTypeDescription
objectObject

The object to return the property names for.

Returns:
Type: 
Array.<String>
Example
var obj1 = {foo: 23, bar: function() { return 42; }};
var obj2 = {baz: function() { return 43; }};
obj2.__proto__ = obj1
own(obj2) // => ["baz"]
all(obj2) // => ["baz","bar"]

(inner) qualifiedMethodName(f) → {String}

Return a qualified name for a given function object.

Parameters:
NameTypeDescription
ffunction

The function object to determine the name of.

Returns:
Type: 
String

(inner) replaceMethodForOneCall(obj, methodName, replacement) → {object}

Change an objects method for a single invocation.

Parameters:
NameTypeDescription
objobject
methodNamestring
replacementfunction
Returns:
Type: 
object
Example
var obj = {foo: function() { return "foo"}};
lively.lang.replaceMethodForOneCall(obj, "foo", function() { return "bar"; });
obj.foo(); // => "bar"
obj.foo(); // => "foo"

(inner) setLocalVarValue(f, name, value)

Given a lively closure, modifies the var binding.

Parameters:
NameTypeDescription
ffunction

A lively closure whos binding has been instrumented beforehand.

namestring

The name of the local variable to adjust.

value*

The value to adjust the local variable in the closure to.

(inner) setProperty()

See
  • setLocalVarValue

(inner) throttle(func, wait)

Exec func at most once every wait ms even when called more often useful to calm down eagerly running updaters and such. This may very likely drop the last couple of calls so if you need a guarantee for the last call to "complete successfully" throttle is not the right choice.

Parameters:
NameTypeDescription
funcfunction

The function to be wrapped.

waitnumber

The duration of time in milliseconds to wait until the throttle is suspended.

Example
var i = 0;
var throttled = throttle(function() { alert(++i + '-' + Date.now()) }, 500);
Array.range(0,100).forEach(function(n) { throttled() });

(inner) throttleNamed(name)

Like throttle but remembers the throttled function once created and repeated calls to throttleNamed with the identical name will use the same throttled function. This allows to throttle functions in a central place that might be called various times in different contexts without having to manually store the throttled function.

Parameters:
NameTypeDescription
nameString

The identifier for the throttled closure.

See
  • throttle.

(inner) timeToRun(func) → {number}

Returns synchronous runtime of calling func in ms.

Parameters:
NameTypeDescription
funcfunction

The function to time.

Returns:
Type: 
number
Example
timeToRun(function() { new WebResource("http://google.de").beSync().get() });
// => 278 (or something else...)

(inner) timeToRunN(func, n) → {number}

Like timeToRun but calls function n times instead of once. Returns the average runtime of a call in ms.

Parameters:
NameTypeDescription
funcfunction

The function to time.

nnumber

The number of times to run the function.

See
  • timeToRun
Returns:
Type: 
number

(inner) traceCalls(func, stack) → {function}

Wraps a function such that it traces all subsequent function calls to a stack object.

Parameters:
NameTypeDescription
funcfunction

The function to wrap.

stackList

The stack to trace the occuring calls to.

Returns:
Type: 
function

(inner) waitFor(timeoutMs, waitTesterFunc, thenDo)

Wait for waitTesterFunc to return true, then run thenDo, passing failure/timout err as first parameter. A timout occurs after timeoutMs. During the wait period waitTesterFunc might be called multiple times.

Parameters:
NameTypeDescription
timeoutMsnumber

The milliseconds to wait for at max.

waitTesterFuncfunction

The testing function.

thenDofunction

Callback that is invoked once the condition is met.

(inner) waitForAll(optionsopt, funcs, thenDo)

Wait for multiple asynchronous functions. Once all have called the continuation, call thenDo.

Parameters:
NameTypeAttributesDescription
optionsObject<optional>

A set of configuration options.

Properties
NameTypeDescription
timeoutnumber

How long to wait in milliseconds.

funcsArray.<function()>

The set of functions ot wait for.

thenDofunction

The callback to invoke after the wait finishes.

(inner) webkitStack() → {string}

Returns the current stackframes of the execution as a string.

Returns:
Type: 
string

(inner) withNull(func) → {function}

Returns a modified version of func that will have null always curried as first arg. Usful e.g. to make a nodejs-style callback work with a then-able.

Parameters:
NameTypeDescription
funcfunction

The function to modify.

Returns:
Type: 
function
Example
promise.then(withNull(cb)).catch(cb);

(inner) workerWithCallbackQueue(optTimeout)

This functions helps when you have a long running computation that multiple call sites (independent from each other) depend on. This function does the housekeeping to start the long running computation just once and returns an object that allows to schedule callbacks once the workerFunc is done. This is how it works: If id does not exist, workerFunc is called, otherwise ignored. workerFunc is expected to call thenDoFunc with arguments: error, arg1, ..., argN if called subsequently before workerFunc is done, the other thenDoFunc will "pile up" and called with the same arguments as the first thenDoFunc once workerFunc is done.

Parameters:
NameTypeDescription
optTimeoutnumber

The timeout for slow running tasks in milliseconds.

See
  • createQueue
Example
var worker = workerWithCallbackQueue("example",
  function slowFunction(thenDo) {
    var theAnswer = 42;
    setTimeout(function() { thenDo(null, theAnswer); });
  });
// all "call sites" depend on `slowFunction` but don't have to know about
// each other
worker.whenDone(function callsite1(err, theAnswer) { alert("callback1: " + theAnswer); })
worker.whenDone(function callsite2(err, theAnswer) { alert("callback2: " + theAnswer); })
workerWithCallbackQueue("example").whenDone(function callsite3(err, theAnswer) { alert("callback3: " + theAnswer); })
// => Will eventually show: callback1: 42, callback2: 42 and callback3: 42

(inner) wrap(func, wrapper) → {function}

A wrapper is another function that is being called with the arguments of func and a proceed function that, when called, runs the originally wrapped function.

Parameters:
NameTypeDescription
funcfunction

The function to wrap.

wrapperfunction

The function to wrap the other one.

Returns:
Type: 
function
Example
function original(a, b) { return a+b }
var wrapped = wrap(original, function logWrapper(proceed, a, b) {
  alert("original called with " + a + "and " + b);
  return proceed(a, b);
})
wrapped(3,4) // => 7 and a message will pop up

(inner) wrapperChain(method) → {Array.<function()>}

Function wrappers used for wrapping, cop, and other method manipulations attach a property "originalFunction" to the wrapper. By convention this property references the wrapped method like wrapper -> cop wrapper -> real method. tThis method gives access to the linked list starting with the outmost wrapper.

Parameters:
NameTypeDescription
methodfunction

A function that has been wrapped potentially multiple times.

Returns:
Type: 
Array.<function()>

Type Definitions

WorkerQueue

Type:
  • Object
Properties
NameTypeDescription
pushfunction

Handles the addition of a single task to the queue.

pushAllfunction

Handles the addition of multiple tasks to the queue.

handleErrorfunction

Callback to handle errors that appear in a task.

drainfunction

Callback that is run once the queue empties.