JSFiddle - React, Tailwind, and code Playground
by Glutamat
JavaScript
var util = {
Buffer: function () {
var buffer = [];
return {
add: function (request) {
return buffer.push(request);
},
get: function () {
return buffer.shift();
},
has: function () {
return !!buffer.length;
}
};
}
}
var WebSocketManager = (function () {
var free, used, instance;
free = [];
used = [];
function flushTo (buffer,socket) {
while (buffer.has ()) {
socket.send (buffer.get());
}
}
function WebSocketManager () {
if (instance) {
return instance
} else if (! (this instanceof WebSocketManager)) {
return (instance = new WebSocketManager);
}
}
WebSocketManager.prototype.open = function (url) {
var socket = new WebSocket (url);
var buffer = util.Buffer();
var interface = new SocketInterface (socket,buffer);
return interface;
}
function SocketInterface (socket,buffer) {
var interface = this;
socket.onmessage = function (message) {
interface.onmessage.call (interface, message.data)
}
socket.onopen = function () {
interface.onopen ();
flushTo (buffer,socket);
}
this.send = function (message) {
buffer.add (message) ;
if (socket.readyState === 1) {
flushTo (buffer,socket);
}
return this;
}
};
["open","message"].forEach ( function (a) {
SocketInterface.prototype ["on" + a] = Function.prototype;
SocketInterface.prototype [a] = function (callback) {
if (typeof callback === "function") {
this["on" + a] = callback;
}
return this;
}
});
...