rafa
Version:
Rafa.js is a Javascript framework for building concurrent applications.
106 lines (90 loc) • 3.04 kB
JavaScript
// # constructor(value: Any): Message
// A message is the container that contains the values and errors sent through
// a stream.
function Message(value) {
this.value = value;
}
inherit(Message, Rafa, {
isMessage: true,
isValue: true,
isError: false,
isDone: false,
// # collect(collector: A => B): Message
// Return a new message whose value is the result of applying the `collector`
// function to this Message's value. Return `undefined` if the `collector`
// returns `null` or `undefined`.
collect(collector) {
var value = collector(this.value);
/*eslint-disable*/
if (value != null) return this.copy(value);
/*eslint-enable*/
},
// # copy(value: A): Message
// Copy this message and set the new Message"s value to value.
copy(value) {
return new this.constructor(value);
},
// # filter(predicate: A => Bool): Message
// Return this message if the predicate function `a => b` returns true when
// this message's `value` is applied as `a`, otherwise return undefined.
filter(predicate) {
if (predicate(this.value)) return this;
},
// # fold(initial: A, folder: (A, A) => A): Message
// Return a new message whose value is the result of applying a folder
// function to the value of this message and an initial value.
fold(initial, folder) {
return this.copy(folder(initial, this.value));
},
// # map(mapper: A => B): Message
// Return a new message whose value is the result of applying the funciton
// `mapper` to this stream's value.
map(mapper) {
return this.copy(mapper(this.value));
},
// # push(Stream, done: A => _)
// Push this message through a stream
push(stream, done) {
stream.push(this.context(done), this);
},
// # toError(): ErrorMessage
// Convert this object to an ErrorMessage if it is a Message or DoneMessage.
toError() {
if (!this.isError) return this.errorMessage(this.value);
return this;
},
// # toDone(): DoneMessage
// Convert this object to an DoneMessage if it is an ErrorMessage or Message.
toDone() {
if (!this.isDone) {
if (this.isError) return this.errordoneMessage(this.error);
return this.doneMessage(this.value);
}
return this;
},
// # toKind(): String
// Return a string representing the kind of message (Message, ErrorMessage,
// or DoneMessage).
toKind() {
let kind;
if (this.isError) kind = "Error";
else if (this.isDone) kind = "Done";
return `${kind}Message`;
},
// # toString(): String
// Return a Javascript normalized String with this message's kind.
toString() {
return `[object ${this.toKind()}]`;
},
// # toRepr(): String
// Return a string that displays the kind and value of this message.
toRepr() {
return `${this.toKind()}(${this.value})`;
},
// # toValue(): Message
// Convert this object to a Message if it is an ErrorMessage or DoneMessage.
toValue() {
if (!this.isValue || this.isDone) return this.message(this.value);
return this;
}
});