Abstractions around first class functions like augmenting and inspecting functions as well as to control function calls like dealing with asynchronous control flows.
- Source
Methods
(inner) addToObject(f, obj, name) → {function}
Attaches a given function to an object as a method.
| Name | Type | Description |
|---|---|---|
f | function | The function to create a method from. |
obj | object | The object to attach the method to. |
name | string | The name of the method once attached to the object. |
- Source
- Type:
- function
(inner) all(obj) → {Array.<String>}
Returns all property names of a given object that reference a function.
| Name | Type | Description |
|---|---|---|
obj | Object | The object to return the property names for. |
- Source
- Type:
- Array.<String>
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.
| Name | Type | Description |
|---|---|---|
f | function | The function object to extract the parameter names of. |
- Source
- Type:
- Array.<String>
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.
| Name | Type | Attributes | Description |
|---|---|---|---|
func | function | The function to create a closure from. | |
optVarMapping | object | <optional> | The var mapping that defines how the free variables inside the closure are to be bound. |
- Source
- 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.
| Name | Type | Attributes | Description |
|---|---|---|---|
f | function | The function to create a method from. | |
obj | object | The object to attach the method to. | |
optName | string | <optional> | The name of the method once attached to the object. |
optMapping | object | <optional> | The var mapping that defines how the free variables inside the method are to be bound. |
- Source
- Type:
- function
(inner) compose(…functions) → {function}
Composes a set of synchronous functions: compose(f,g,h)(arg1, arg2) = h(g(f(arg1, arg2)))
| Name | Type | Attributes | Description |
|---|---|---|---|
functions | function | <repeatable> | The collections of functions to compose. |
- Source
- Type:
- function
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)
| Name | Type | Attributes | Description |
|---|---|---|---|
functions | function | <repeatable> | The collections of asynchronous functions to compose. |
- Source
- Type:
- function
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.
| Name | Type | Description |
|---|---|---|
id | string | The identifier for the worker queue. |
workerFunc | function | Asynchronous function to process queued tasks. |
- Source
- Type:
- WorkerQueue
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.
| Name | Type | Description |
|---|---|---|
func | function | The function to curry. |
- Source
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.
| Name | Type | Description |
|---|---|---|
wait | number | The duration in milliseconds to wait until the next invocation. |
func | function | The founction to be wrapped. |
immediate | Boolean | When set to true, immediately call |
- Source
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.
| Name | Type | Description |
|---|---|---|
name | String | The identifier for the debounced closure. |
- Source
- See
- debounce
(inner) delay(func, timeout)
Delays calling func for timeout seconds(!).
| Name | Type | Description |
|---|---|---|
func | function | Function object to delay execution for. |
timeout | number | The duration in milliseconds to delay the execution for. |
- Source
(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:
- Source
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.
| Name | Type | Description |
|---|---|---|
name | string | |
func | function | The function to wrap. |
- Source
- See
- either
- Type:
- function
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.
| Name | Type | Description |
|---|---|---|
func | function | The function to extract the body from. |
- Source
- Type:
- String
extractBody(function(arg) {
var x = 34;
alert(2 + arg);
}) => "var x = 34;\nalert(2 + arg);"(inner) flip(f) → {function}
Swaps the first two args
| Name | Type | Description |
|---|---|---|
f | function | Function to flip the arguments for. |
- Source
- Type:
- function
flip(function(a, b, c) {
return a + b + c; })(' World', 'Hello', '!') // => "Hello World!"(inner) fromString(funcOrString) → {function}
Creates a function from a string.
| Name | Type | Description |
|---|---|---|
funcOrString | string | | A function or string to create a function from. |
- Source
- Type:
- function
fromString("function() { return 3; }")() // => 3(inner) functionNames(klass) → {Array.<string>}
Treats passed function as class (constructor).
| Name | Type | Description |
|---|---|---|
klass | function | The function to check for as a class. |
- Source
- Type:
- Array.<string>
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.
| Name | Type | Description |
|---|---|---|
wrappedFunc | function | The wrapped function to retrieve the original from. |
- Source
- Type:
- function
(inner) getVarMapping()
Returns the var mapping for a given lively closure.
- Source
(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.
| Name | Type | Description |
|---|---|---|
func | function | The function to guard the execution for. |
- Source
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.
| Name | Type | Description |
|---|---|---|
name | string | The identifier to guard by. |
func | function | The function to guard. |
- Source
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.
| Name | Type | Description |
|---|---|---|
fn | function | The function to check for. |
- Source
- Type:
- boolean
(inner) localFunctionNames(func) → {Array.<string>}
Return the names of the functions defined on the prototype.
| Name | Type | Description |
|---|---|---|
func | function | The function whos prototype to check. |
- Source
- Type:
- Array.<string>
(inner) logCalls(func, isUrgent) → {function}
Wraps a function to log to the console every time it is applied.
| Name | Type | Description |
|---|---|---|
func | function | The function to wrap. |
isUrgent | boolean | Wether or not the applications should logged as warnings or plain logs. |
- Source
- Type:
- function
(inner) logCompletion() → {function}
Wrap a function to log to console once it succesfully completes.
- Source
- Type:
- function
(inner) logErrors(func, prefix) → {function}
Wraps a given function to automatically log all the errors encountered to the console.
| Name | Type | Description |
|---|---|---|
func | function | The function to wrap. |
prefix | string | The log prefix to pass to the console.warn() call. |
- Source
- Type:
- function
(inner) notYetImplemented(what, strict)
Throws a well behaved error on purpopse, when accessing unimplemented functionality.
| Name | Type | Default | Description |
|---|---|---|---|
what | string | The thing, which is not implemented. | |
strict | boolean | false | Whether or not to throw an actual error. |
- Source
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.
| Name | Type | Description |
|---|---|---|
func | function | The function to be wrapped to only execute once. |
- Source
- Type:
- function
(inner) own(object) → {Array.<String>}
Returns all local (non-prototype) property names of a given object that reference a function.
| Name | Type | Description |
|---|---|---|
object | Object | The object to return the property names for. |
- Source
- Type:
- Array.<String>
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.
| Name | Type | Description |
|---|---|---|
f | function | The function object to determine the name of. |
- Source
- Type:
- String
(inner) replaceMethodForOneCall(obj, methodName, replacement) → {object}
Change an objects method for a single invocation.
| Name | Type | Description |
|---|---|---|
obj | object | |
methodName | string | |
replacement | function |
- Source
- Type:
- object
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.
| Name | Type | Description |
|---|---|---|
f | function | A lively closure whos binding has been instrumented beforehand. |
name | string | The name of the local variable to adjust. |
value | * | The value to adjust the local variable in the closure to. |
- Source
(inner) setProperty()
- Source
- 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.
| Name | Type | Description |
|---|---|---|
func | function | The function to be wrapped. |
wait | number | The duration of time in milliseconds to wait until the throttle is suspended. |
- Source
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.
| Name | Type | Description |
|---|---|---|
name | String | The identifier for the throttled closure. |
- Source
- See
- throttle.
(inner) timeToRun(func) → {number}
Returns synchronous runtime of calling func in ms.
| Name | Type | Description |
|---|---|---|
func | function | The function to time. |
- Source
- Type:
- number
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.
| Name | Type | Description |
|---|---|---|
func | function | The function to time. |
n | number | The number of times to run the function. |
- Source
- See
- timeToRun
- Type:
- number
(inner) traceCalls(func, stack) → {function}
Wraps a function such that it traces all subsequent function calls to a stack object.
| Name | Type | Description |
|---|---|---|
func | function | The function to wrap. |
stack | List | The stack to trace the occuring calls to. |
- Source
- 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.
| Name | Type | Description |
|---|---|---|
timeoutMs | number | The milliseconds to wait for at max. |
waitTesterFunc | function | The testing function. |
thenDo | function | Callback that is invoked once the condition is met. |
- Source
(inner) waitForAll(optionsopt, funcs, thenDo)
Wait for multiple asynchronous functions. Once all have called the continuation, call thenDo.
| Name | Type | Attributes | Description | ||||||
|---|---|---|---|---|---|---|---|---|---|
options | Object | <optional> | A set of configuration options. Properties
| ||||||
funcs | Array.<function()> | The set of functions ot wait for. | |||||||
thenDo | function | The callback to invoke after the wait finishes. |
- Source
(inner) webkitStack() → {string}
Returns the current stackframes of the execution as a string.
- Source
- 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.
| Name | Type | Description |
|---|---|---|
func | function | The function to modify. |
- Source
- Type:
- function
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.
| Name | Type | Description |
|---|---|---|
optTimeout | number | The timeout for slow running tasks in milliseconds. |
- Source
- See
- createQueue
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.
| Name | Type | Description |
|---|---|---|
func | function | The function to wrap. |
wrapper | function | The function to wrap the other one. |
- Source
- Type:
- function
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.
| Name | Type | Description |
|---|---|---|
method | function | A function that has been wrapped potentially multiple times. |
- Source
- Type:
- Array.<function()>
Type Definitions
WorkerQueue
- Object
| Name | Type | Description |
|---|---|---|
push | function | Handles the addition of a single task to the queue. |
pushAll | function | Handles the addition of multiple tasks to the queue. |
handleError | function | Callback to handle errors that appear in a task. |
drain | function | Callback that is run once the queue empties. |
- Source