Skip to content

Instantly share code, notes, and snippets.

@tatupesonen
Created June 14, 2022 11:49
Show Gist options
  • Save tatupesonen/bcad0892824ad682a537e6132cc60cab to your computer and use it in GitHub Desktop.
Save tatupesonen/bcad0892824ad682a537e6132cc60cab to your computer and use it in GitHub Desktop.
import { differenceInMilliseconds, differenceInSeconds } from "date-fns";
export class Cache {
constructor({ minInterval = 1000 }) {
this.minInterval = minInterval;
this._map = new Map();
}
// Key could be an item here
check = (key) => {
const existing = this._map.get(key);
if(existing !== undefined) {
// Value was found, check if it's longer than a second ago.
// calculate a difference in seconds
const diff = differenceInMilliseconds(new Date(), existing);
if(diff >= this.minInterval) {
// All good, you can modify the value.
this._map.set(key, new Date());
return true;
} else {
// Smaller than one second, return false and don't update the item.
return false;
}
}
else {
// Doesn't exist yet
this._map.set(key, new Date())
return true;
}
}
}
import { EventEmitter } from "events";
import { Cache } from "./cache.js";
const cache = new Cache({ minInterval: 1000 });
const emitter = new EventEmitter();
let transactions = [];
const eventListener = emitter.addListener('addTransaction', (data) => {
// Check if we can add
const permitted = cache.check(data.id);
if (permitted) {
transactions.push(data);
console.log('Received a new transaction ', data);
} else {
console.log('Transaction recently modified, please wait a second.')
}
})
const eventListener2 = emitter.addListener('removeTransaction', (data) => {
const permitted = cache.check(data.id);
if (permitted) {
transactions = transactions.filter((e) => e.id !== data.id);
console.log('Received a new transaction ', data);
} else {
console.log('Transaction recently modified, please wait a second.')
}
})
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
const run = async () => {
for (let i = 0; i < 500; i++) {
emitter.emit('addTransaction', { "data": "New stock added", id: "perkele" })
await sleep(500);
}
}
run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment