JSFiddle - React, Tailwind, and code Playground
by Nidhi Patel
JavaScript
class Decryption {
constructor(initialKey) {
this.key = initialKey;
this.isBusy = false;
this.requestQueue = [];
}
decrypt(payload, callback) {
// Check if the manager is busy, if yes, add the request to the queue
if (this.isBusy) {
this.requestQueue.push({ payload, callback });
} else {
// Manager is not busy, process the request
this.isBusy = true ;
// Reusing decryptEncrypt function
decryptEncrypt(this.key, payload, (result) => {
// Update the key before invoking the callback
this.key = result.key;
// Invoke the callback with the decrypted message and new key
callback({ key: result.key, message: result.message });
// Check if there are pending requests in the queue
if (this.requestQueue.length > 0) {
const nextRequest = this.requestQueue.shift();
this.decrypt(nextRequest.payload, nextRequest.callback);
} else {
// No pending requests, manager is now idle
this.isBusy = false;
}
});
}
}
}
// Example usage:
const mgr = new Decryption('initialKey');
function decryptAndLog(encryptedPayload) {
mgr.decrypt(encryptedPayload, (decryptedMessage) => {
console.log('Decrypted message:', decryptedMessage);
});
}
function decryptEncrypt(key, payload, callback) {
const newKey = someProcessToGenerateNewKey(key);
const message = someProcessToDecrypt(payload, key);
callback({ key: newKey, message });
}
function someProcessToGenerateNewKey(oldKey) {
return oldKey + 'new';
}
function someProcessToDecrypt(payload, key) {
return 'decrypted' + payload;
}
// Example usage:
decryptAndLog('payload1');
decryptAndLog('payload2');
decryptAndLog('payload3');