@connectv/core
Version:
agent-based reactive programming library for typescript/javascript
63 lines • 2.16 kB
JavaScript
import { Node } from './node';
/**
*
* Represents [expression](https://connective.dev/docs/expr) agents.
*
*/
export class Expr extends Node {
/**
*
* @param inputsOrFunc either a list of names for the inputs of the
* [signature](https://connective.dev/docs/agent#signature) or the expr function
* @param func the expr function (if this is provided, the first parameter must be alist of string)
*
*/
constructor(inputsOrFunc, func) {
super({
inputs: (typeof inputsOrFunc === 'function') ? [] : inputsOrFunc,
required: (typeof inputsOrFunc === 'function') ? [] : inputsOrFunc,
outputs: ['result']
});
this.func = func ? func : inputsOrFunc;
}
run(inputs, output, error, context) {
let _ilist = this.signature.inputs ? this.signature.inputs.map(i => inputs[i]) : [];
try {
let val = this.func.apply(undefined, _ilist.concat(context));
if (typeof val === 'function')
val.apply(undefined, [(out) => output('result', out), error]);
else
output('result', val);
}
catch (err) {
error(err);
}
}
/**
*
* Shortcut for `.out('result')`. The result of the evaluation of the
* expression will be emitted via this output.
*
*/
get result() { return this.out('result'); }
}
/**
*
* Creates an [expr](https://connective.dev/docs/expr) agent.
* Expr agents turn a function into an agent.
* [Checkout the docs](https://connective.dev/docs/expr) for examples and further information.
*
* @param inputsOrFunc either a list of names for the inputs of the signature or the function to convert
* @param func the function to convert (if provided, the first argument must be a list of strings)
*
*/
export function expr(inputsOrFunc, func) {
if (func)
return new Expr(inputsOrFunc, func);
else {
let func = inputsOrFunc;
return new Expr(Array.apply(0, { length: func.length }).map((_, i) => i.toString()), func);
}
}
export default expr;
//# sourceMappingURL=expr.js.map