Created
November 18, 2020 02:12
-
-
Save stuartambient/d7f4c16fb7af21b2ae8197bfabcb7ac1 to your computer and use it in GitHub Desktop.
NodeJS Design Patterns (third edition) challenges
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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