signalk-server
Version:
An implementation of a [Signal K](http://signalk.org) server for boats.
43 lines (42 loc) • 1.14 kB
JavaScript
"use strict";
/* eslint-disable @typescript-eslint/no-explicit-any */
Object.defineProperty(exports, "__esModule", { value: true });
class DeltaChain {
dispatchMessage;
chain;
next;
constructor(dispatchMessage) {
this.dispatchMessage = dispatchMessage;
this.chain = [];
this.next = [];
}
process(msg) {
return this.doProcess(0, msg);
}
doProcess(index, msg) {
if (index >= this.chain.length) {
this.dispatchMessage(msg);
return;
}
this.chain[index](msg, this.next[index]);
}
register(handler) {
this.chain.push(handler);
this.updateNexts();
return () => {
const handlerIndex = this.chain.indexOf(handler);
if (handlerIndex >= 0) {
this.chain.splice(handlerIndex, 1);
this.updateNexts();
}
};
}
updateNexts() {
this.next = this.chain.map((chainElement, index) => {
return (msg) => {
this.doProcess(index + 1, msg);
};
});
}
}
exports.default = DeltaChain;