var crypto = require('crypto')

module.exports = function (type, encoding, onEnd) {
  if (onEnd == null) onEnd = encoding, encoding = null
  var hash = (typeof type == 'string') ? crypto.createHash(type) : type
  var ended
  function hasher(read) {
    return function (abort, cb) {
      read(abort, function (end, data) {
        if (end === true && !hasher.digest) hasher.digest = hash.digest(encoding)
        else if (!end) hash.update(data)
        if (end && onEnd && !ended) {
          onEnd(end === true ? null : end, hasher.digest)
          ended = true
        }
        cb(end, data)
      })
    }
  }
  hasher.hash = hash
  return hasher
}
