Skip to content

Commit

Permalink
code style 👕, use pump
Browse files Browse the repository at this point in the history
  • Loading branch information
derhuerst committed May 3, 2018
1 parent 7eb161a commit 32022f2
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 31 deletions.
57 changes: 27 additions & 30 deletions index.js
Expand Up @@ -5,8 +5,7 @@ const fs = require('fs')
const ndjson = require('ndjson')
const filterStream = require('stream-filter')
const sink = require('stream-sink')


const pump = require('pump')

const file = path.join(__dirname, 'data.ndjson')

Expand All @@ -21,34 +20,32 @@ const filterByKeys = (pattern) => (data) => {
return true
}

const lines = (...args) => {
const pattern = args.pop()
const promised = !!args.shift()

const chain = [
fs.createReadStream(file),
ndjson.parse()
]
if ('string' === typeof pattern) {
if (pattern !== 'all') {
const filter = filterStream.obj(filterById(pattern))
chain.push(filter)
}
} else if (pattern !== undefined) {
const filter = filterStream.obj(filterByKeys(pattern))
chain.push(filter)
}


const lines = function (/* promised, filter */) {
const args = Array.prototype.slice.call(arguments)
let pattern = args.pop()
let promised = !!args.shift()

const reader = fs.createReadStream(file)
const parser = reader.pipe(ndjson.parse())
let filter

if (pattern === 'all' || pattern === undefined) filter = parser // no filter
else if ('string' === typeof pattern)
filter = parser.pipe(filterStream.obj(filterById(pattern)))
else filter = parser.pipe(filterStream.obj(filterByKeys(pattern)))

if (promised === true) return new Promise((resolve, reject) => {
reader.on('error', reject)
parser.on('error', reject)
filter.on('error', reject)

const results = filter.pipe(sink('object'))
results.catch(reject)
results.then(resolve)
})
else return filter
if (promised === true) {
const out = sink('object')
pump(...chain, out, () => {})
return out
}
return pump(...chain, () => {})
}



module.exports = Object.assign(lines, {filterById, filterByKeys})
lines.filterById = filterById
lines.filterByKeys = filterByKeys
module.exports = lines
2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -30,6 +30,7 @@
},
"dependencies": {
"ndjson": "^1.5.0",
"pump": "^3.0.0",
"stream-filter": "^2.1.0",
"stream-sink": "^2.0.0"
},
Expand All @@ -39,7 +40,6 @@
"is-stream": "^1.0.1",
"moment": "^2.17.1",
"ndjson": "^1.5.0",
"pump": "^3.0.0",
"shallow-equals": "^1.0.0",
"strip-bom-stream": "^3.0.0",
"tap-min": "^1.2.2",
Expand Down

0 comments on commit 32022f2

Please sign in to comment.