JSFiddle - React, Tailwind, and code Playground
JavaScript
//PROCESSED POINT HOLDERS
var points = {}; // { '3;-4' : true, '3;4': false }
var pointsArray = []; // [ {x: 3, y: 4}, {x: -3, y: 4}]
//SOCKET INIT
var socket = new WebSocket('wss://echo.websocket.org/');
//SERVER SIDE INFRASTRUCTURE, WE NEED TO EMULATE REMOTE HOST
var socketServerEmulator = function(message) {
var messageJson = null;
try { messageJson = JSON.parse(message.data); } catch(e) {}
if (messageJson && messageJson.mtype) {
switch (messageJson.mtype) {
case 'request':
var result = (messageJson.x + messageJson.y) % 2 === 0;
console.log('SERVER EMULATOR: Got request', messageJson);
console.log('SERVER EMULATOR: SENDING GENERATED RESPONSE...');
socket.send(JSON.stringify({
'mtype': 'response',
'x': messageJson.x,
'y': messageJson.y,
'status': result
}));
break;
case 'response':
console.log('SERVER EMULATOR: Passing through response: ', messageJson);
break;
default:
break;
}
}
}
//// CLIENT SIDE CODE ////
function processResponse(response, resolvePromise) {
var responseJson = null;
try { responseJson = JSON.parse(response.data); } catch(e) {}
if (!responseJson || !responseJson.mtype || responseJson.mtype != 'response') {
return false;
}
console.log('CLIENT: Processing response...');
if (responseJson.status) {
var x = responseJson.x;
var y = responseJson.y;
//Saving data to points array
points[x + ';' + y] = true;
pointsArray.push({
'x': x,
'y': y
});
resolvePromise(true);
} else {
resolvePromise(false);
}
console.log('CLIENT: Response processed.');
}
function getCell(x, y) {
return new Promise(function(resolveFunc) {
setTimeout(function() {
socket.addEventListener('message', function(message) {
processResponse(message, resolveFunc);
socket.removeEventListener('message', this);
});
...