Skip to content

Instantly share code, notes, and snippets.

@satheesh-chandran
Created October 7, 2020 04:38
Show Gist options
  • Save satheesh-chandran/4a050eb27161d0622e37117beba27db1 to your computer and use it in GitHub Desktop.
Save satheesh-chandran/4a050eb27161d0622e37117beba27db1 to your computer and use it in GitHub Desktop.
read multiple using event listener
const { EventEmitter } = require('events');
const { readFileSync } = require('fs');
const displayMultiple = (number, factor) =>
console.log(`${number} is a multiple of ${factor}`);
const readMultiple = function () {
const [, , fileName, factor] = process.argv;
const numbers = readFileSync(fileName, 'utf8').split('\n').map(Number);
const factorEmitter = new EventEmitter();
factorEmitter.once('multiple', () => console.log('I found first multiple '));
factorEmitter.on('multiple', displayMultiple);
numbers.forEach(number => {
if (number % factor == 0) factorEmitter.emit('multiple', number, factor);
});
factorEmitter.removeListener('multiple', displayMultiple);
};
readMultiple();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment