Skip to content

Instantly share code, notes, and snippets.

@kalinchernev
Last active February 4, 2017 01:56
Show Gist options
  • Save kalinchernev/985b975fe6591675ce2272b53846b2c8 to your computer and use it in GitHub Desktop.
Save kalinchernev/985b975fe6591675ce2272b53846b2c8 to your computer and use it in GitHub Desktop.
Demonstration of CPS vs EE
'use strict'
// Dependencies
const EventEmitter = require('events').EventEmitter
const path = require('path')
// Definition
function findFiles (files, extension, cb = null) {
const emitter = new EventEmitter()
const errorMessage = 'no files supplied';
if (files.length === 0) {
if (cb) {
cb(errorMessage)
}
emitter.emit('error', errorMessage)
}
if (cb) {
// cps
let result = []
for (let i = 0; i < files.length; ++i) {
if (path.extname(files[i]) === extension) {
result.push(files[i])
}
}
cb(null, result)
} else {
// event emitter style
process.nextTick(() => {
files.forEach(file => {
if (path.extname(file) === extension) {
emitter.emit('match', file)
}
})
})
return emitter
}
}
// Implementation with a callback
findFiles(process.argv.slice(2), '.js', (err, result) => {
if (err) return console.error(err)
console.log(`All in one: ${result}`)
})
// Implementation with an event emitter
findFiles(process.argv.slice(2), '.js')
.on('match', file => console.log(file + ' is a match'))
.on('error', err => console.log('Error emitted: ' + err.message))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment