Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
NodeJS Design Patterns (third edition) challenges
const { EventEmitter } = require('events');
const ticker = (num, cb) => {
const emitter = new EventEmitter();
const counters = { timePassed: 0, count: 0 };
const timestamp = () => {
const time = Date.now();
return time % 5 === 0;
};
const repeat = () => {
if (counters.timePassed >= num)
return process.nextTick(() => cb(counters.count));
if (timestamp()) {
emitter.emit('error', new Error('ticker stopped'));
return cb(counters.count);
}
emitter.emit('tick', '....');
setTimeout(repeat, 50);
process.nextTick(() => (counters.timePassed += 50));
process.nextTick(() => (counters.count += 1));
};
process.nextTick(() => {
if (timestamp()) {
emitter.emit('error', new Error('ticker stopped'));
return cb(counters.count);
} else {
emitter.emit('first-tick', 'ticker started');
setTimeout(repeat, 50);
}
});
return emitter;
};
const cb = completed => {
console.log(`Completed ${completed} ticks`);
};
ticker(2000, cb)
/* .on('newListener', newListener => console.log(newListener)) */
.on('error', err => console.log(err.message))
.on('tick', msg => console.log(msg))
.on('first-tick', msg => console.log(msg));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment