Skip to content

Instantly share code, notes, and snippets.

@stuartambient
Created November 18, 2020 02:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stuartambient/d7f4c16fb7af21b2ae8197bfabcb7ac1 to your computer and use it in GitHub Desktop.
Save stuartambient/d7f4c16fb7af21b2ae8197bfabcb7ac1 to your computer and use it in GitHub Desktop.
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