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: /npm/highland@2.13.5/lib/index.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","/**\n * Highland: the high-level streams library\n *\n * Highland may be freely distributed under the Apache 2.0 license.\n * http://github.com/caolan/highland\n * Copyright (c) Caolan McMahon\n *\n */\n\n\nvar inherits = require('util').inherits;\nvar deprecate = require('util-deprecate');\nvar EventEmitter = require('events').EventEmitter;\nvar Decoder = require('string_decoder').StringDecoder;\nvar Readable = require('stream').Readable;\n\n/**\n * The Stream constructor, accepts an array of values or a generator function\n * as an optional argument. This is typically the entry point to the Highland\n * APIs, providing a convenient way of chaining calls together.\n *\n * **Arrays -** Streams created from Arrays will emit each value of the Array\n * and then emit a [nil](#nil) value to signal the end of the Stream.\n *\n * **Generators -** These are functions which provide values for the Stream.\n * They are lazy and can be infinite, they can also be asynchronous (for\n * example, making a HTTP request). You emit values on the Stream by calling\n * `push(err, val)`, much like a standard Node.js callback. Once it has been\n * called, the generator function will not be called again unless you call\n * `next()`. This call to `next()` will signal you've finished processing the\n * current data and allow for the generator function to be called again. If the\n * Stream is still being consumed the generator function will then be called\n * again.\n *\n * You can also redirect a generator Stream by passing a new source Stream\n * to read from to next. For example: `next(other_stream)` - then any subsequent\n * calls will be made to the new source.\n *\n * **Node Readable Stream -** Pass in a Node Readable Stream object to wrap\n * it with the Highland API. Reading from the resulting Highland Stream will\n * begin piping the data from the Node Stream to the Highland Stream.\n *\n * A stream constructed in this way relies on `Readable#pipe` to end the\n * Highland Stream once there is no more data. Not all Readable Streams do\n * this. For example, `IncomingMessage` will only emit `close` when the client\n * aborts communications and will *not* properly call `end`. In this case, you\n * can provide an optional `onFinished` function with the signature\n * `onFinished(readable, callback)` as the second argument.\n *\n * This function will be passed the Readable and a callback that should called\n * when the Readable ends. If the Readable ended from an error, the error\n * should be passed as the first argument to the callback. `onFinished` should\n * bind to whatever listener is necessary to detect the Readable's completion.\n * If the callback is called multiple times, only the first invocation counts.\n * If the callback is called *after* the Readable has already ended (e.g., the\n * `pipe` method already called `end`), it will be ignored.\n *\n * The `onFinished` function may optionally return one of the following:\n *\n * - A cleanup function that will be called when the stream ends. It should\n * unbind any listeners that were added.\n * - An object with the following optional properties:\n *    - `onDestroy` - the cleanup function.\n *    - `continueOnError` - Whether or not to continue the stream when an\n *      error is passed to the callback. Set this to `true` if the Readable\n *      may continue to emit values after errors. Default: `false`.\n *\n * See [this issue](https://github.com/caolan/highland/issues/490) for a\n * discussion on why Highland cannot reliably detect stream completion for\n * all implementations and why the `onFinished` function is required.\n *\n * **EventEmitter / jQuery Elements -** Pass in both an event name and an\n * event emitter as the two arguments to the constructor and the first\n * argument emitted to the event handler will be written to the new Stream.\n *\n * You can pass a mapping hint as the third argument, which specifies how\n * event arguments are pushed into the stream. If no mapping hint is provided,\n * only the first value emitted with the event to the will be pushed onto the\n * Stream.\n *\n * If `mappingHint` is a number, an array of that length will be pushed onto\n * the stream, containing exactly that many parameters from the event. If it's\n * an array, it's used as keys to map the arguments into an object which is\n * pushed to the tream. If it is a function, it's called with the event\n * arguments, and the returned value is pushed.\n *\n * **Promise -** Accepts an ES6 / jQuery style promise and returns a\n * Highland Stream which will emit a single value (or an error). In case you use\n * [bluebird cancellation](http://bluebirdjs.com/docs/api/cancellation.html) Highland Stream will be empty for a cancelled promise.\n *\n * **Iterator -** Accepts an ES6 style iterator that implements the [iterator protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_.22iterator.22_protocol):\n * yields all the values from the iterator using its `next()` method and terminates when the\n * iterator's done value returns true. If the iterator's `next()` method throws, the exception will be emitted as an error,\n * and the stream will be ended with no further calls to `next()`.\n *\n * **Iterable -** Accepts an object that implements the [iterable protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_.22iterable.22_protocol),\n * i.e., contains a method that returns an object that conforms to the iterator protocol. The stream will use the\n * iterator defined in the `Symbol.iterator` property of the iterable object to generate emitted values.\n *\n * @id _(source)\n * @section Stream Objects\n * @name _(source)\n * @param {Array | Function | Iterator | Iterable | Promise | Readable Stream | String} source - (optional) source to take values from from\n * @param {Function} onFinished - (optional) a function that detects when the readable completes. Second argument. Only valid if `source` is a Readable.\n * @param {EventEmitter | jQuery Element} eventEmitter - (optional) An event emitter. Second argument. Only valid if `source` is a String.\n * @param {Array | Function | Number} mappingHint - (optional) how to pass the\n * arguments to the callback. Only valid if `source` is a String.\n * @api public\n *\n * // from an Array\n * _([1, 2, 3, 4]);\n *\n * // using a generator function\n * _(function (push, next) {\n *     push(null, 1);\n *     push(err);\n *     next();\n * });\n *\n * // a stream with no source, can pipe node streams through it etc.\n * var through = _();\n *\n * // wrapping a Node Readable Stream so you can easily manipulate it\n * _(readable).filter(hasSomething).pipe(writeable);\n *\n * // wrapping a Readable that may signify completion by emitting `close`\n * // (e.g., IncomingMessage).\n * _(req, function (req, callback) {\n *     req.on('end', callback)\n *         .on('close', callback)\n *         .on('error', callback);\n *\n *     return function () {\n *         req.removeListener('end', callback);\n *         req.removeListener('close', callback);\n *         req.removeListener('error', callback);\n *     };\n * }).pipe(writable);\n *\n * // wrapping a Readable that may emit values after errors.\n * _(req, function (req, callback) {\n *     req.on('error', callback);\n *\n *     return {\n *         onDestroy: function () {\n *             req.removeListener('error', callback);\n *         },\n *         continueOnError: true\n *     };\n * }).pipe(writable);\n *\n * // creating a stream from events\n * _('click', btn).each(handleEvent);\n *\n * // creating a stream from events with a mapping array\n * _('request', httpServer, ['req', 'res']).each(handleEvent);\n * //=> { req: IncomingMessage, res: ServerResponse }\n *\n * // creating a stream from events with a mapping function\n * _('request', httpServer, function(req, res) {\n *     return res;\n * }).each(handleEvent);\n * //=> IncomingMessage\n *\n * // from a Promise object\n * var foo = _($.getJSON('/api/foo'));\n *\n * //from an iterator\n * var map = new Map([['a', 1], ['b', 2]]);\n * var bar = _(map.values()).toArray(_.log);\n * //=> [1, 2]\n *\n * //from an iterable\n * var set = new Set([1, 2, 2, 3, 4]);\n * var bar = _(set).toArray(_.log);\n * //=> [ 1, 2, 3, 4]\n */\n\n/*eslint-disable no-multi-spaces */\nexports = module.exports = function (/*optional*/xs, /*optional*/secondArg, /*optional*/ mappingHint) {\n    /*eslint-enable no-multi-spaces */\n    return new Stream(xs, secondArg, mappingHint);\n};\n\nvar _ = exports;\n\n// Create quick slice reference variable for speed\nvar slice = Array.prototype.slice;\nvar hasOwn = Object.prototype.hasOwnProperty;\n\n// ES5 detected value, used for switch between ES5 and ES3 code\nvar isES5 = (function () {\n    'use strict';\n    return Function.prototype.bind && !this;\n}());\n\nfunction bindContext(fn, context) {\n    if (isES5) {\n        return fn.bind(context);\n    }\n    else {\n        return function () {\n            return fn.apply(context, arguments);\n        };\n    }\n}\n\n_.isUndefined = function (x) {\n    return typeof x === 'undefined';\n};\n\n_.isFunction = function (x) {\n    return typeof x === 'function';\n};\n\n_.isObject = function (x) {\n    return typeof x === 'object' && x !== null;\n};\n\n_.isString = function (x) {\n    return typeof x === 'string';\n};\n\n_.isArray = Array.isArray || function (x) {\n    return Object.prototype.toString.call(x) === '[object Array]';\n};\n\n// setImmediate browser fallback\nif (typeof setImmediate === 'undefined') {\n    _.setImmediate = function (fn) {\n        setTimeout(fn, 0);\n    };\n}\nelse {\n    // modern browser - but not a direct alias for IE10\n    // compatibility and to allow for fake timers in tests.\n    _.setImmediate = function (fn) {\n        setImmediate(fn);\n    };\n}\n\n/**\n * The end of stream marker. This is sent along the data channel of a Stream\n * to tell consumers that the Stream has ended. See the example map code for\n * an example of detecting the end of a Stream.\n *\n * Note: `nil` is setup as a global where possible. This makes it convenient\n * to access, but more importantly lets Streams from different Highland\n * instances work together and detect end-of-stream properly. This is mostly\n * useful for NPM where you may have many different Highland versions installed.\n *\n * @id nil\n * @section Utils\n * @name _.nil\n * @api public\n *\n * var map = function (iter, source) {\n *     return source.consume(function (err, val, push, next) {\n *         if (err) {\n *             push(err);\n *             next();\n *         }\n *         else if (val === _.nil) {\n *             push(null, val);\n *         }\n *         else {\n *             push(null, iter(val));\n *             next();\n *         }\n *     });\n * };\n */\n\n// set up a global nil object in cases where you have multiple Highland\n// instances installed (often via npm)\nvar _global = this;\nif (typeof global !== 'undefined') {\n    _global = global;\n}\nelse if (typeof window !== 'undefined') {\n    _global = window;\n}\nif (!_global.nil) {\n    _global.nil = {};\n}\nvar nil = _.nil = _global.nil;\n\n/**\n * Transforms a function with specific arity (all arguments must be\n * defined) in a way that it can be called as a chain of functions until\n * the arguments list is saturated.\n *\n * This function is not itself curryable.\n *\n * @id curry\n * @name _.curry(fn, [*arguments])\n * @section Functions\n * @param {Function} fn - the function to curry\n * @param args.. - any number of arguments to pre-apply to the function\n * @returns Function\n * @api public\n *\n * fn = curry(function (a, b, c) {\n *     return a + b + c;\n * });\n *\n * fn(1)(2)(3) == fn(1, 2, 3)\n * fn(1, 2)(3) == fn(1, 2, 3)\n * fn(1)(2, 3) == fn(1, 2, 3)\n */\n\n_.curry = function (fn /* args... */) {\n    var args = slice.call(arguments);\n    return _.ncurry.apply(this, [fn.length].concat(args));\n};\n\n/**\n * Same as `curry` but with a specific number of arguments. This can be\n * useful when functions do not explicitly define all its parameters.\n *\n * This function is not itself curryable.\n *\n * @id ncurry\n * @name _.ncurry(n, fn, [args...])\n * @section Functions\n * @param {Number} n - the number of arguments to wait for before apply fn\n * @param {Function} fn - the function to curry\n * @param args... - any number of arguments to pre-apply to the function\n * @returns Function\n * @api public\n *\n * fn = ncurry(3, function () {\n *     return Array.prototype.join.call(arguments, '.');\n * });\n *\n * fn(1, 2, 3) == '1.2.3';\n * fn(1, 2)(3) == '1.2.3';\n * fn(1)(2)(3) == '1.2.3';\n */\n\n_.ncurry = function (n, fn /* args... */) {\n    var largs = slice.call(arguments, 2);\n    if (largs.length >= n) {\n        return fn.apply(this, largs.slice(0, n));\n    }\n\n    return _.partial.apply(this, [_.ncurry, n, fn].concat(largs));\n};\n\n/**\n * Partially applies the function (regardless of whether it has had curry\n * called on it). This will always postpone execution until at least the next\n * call of the partially applied function.\n *\n * @id partial\n * @name _.partial(fn, args...)\n * @section Functions\n * @param {Function} fn - function to partial apply\n * @param args... - the arguments to apply to the function\n * @api public\n *\n * var addAll = function () {\n *     var args = Array.prototype.slice.call(arguments);\n *     return foldl1(add, args);\n * };\n * var f = partial(addAll, 1, 2);\n * f(3, 4) == 10\n */\n\n_.partial = function (f /* args... */) {\n    var args = slice.call(arguments, 1);\n    return function () {\n        return f.apply(this, args.concat(slice.call(arguments)));\n    };\n};\n\n/**\n * Evaluates the function `fn` with the argument positions swapped. Only\n * works with functions that accept two arguments.\n *\n * @id flip\n * @name _.flip(fn, [x, y])\n * @section Functions\n * @param {Function} fn - function to flip argument application for\n * @param x - parameter to apply to the right hand side of f\n * @param y - parameter to apply to the left hand side of f\n * @api public\n *\n * div(2, 4) == 0.5\n * flip(div, 2, 4) == 2\n * flip(div)(2, 4) == 2\n */\n\n_.flip = _.curry(function (fn, x, y) { return fn(y, x); });\n\n/**\n * Creates a composite function, which is the application of function1 to\n * the results of function2. You can pass an arbitrary number of arguments\n * and have them composed. This means you can't partially apply the compose\n * function itself.\n *\n * @id compose\n * @name _.compose(fn1, fn2, ...)\n * @section Functions\n * @api public\n *\n * var add1 = add(1);\n * var mul3 = mul(3);\n *\n * var add1mul3 = compose(mul3, add1);\n * add1mul3(2) == 9\n */\n\n_.compose = function (/*functions...*/) {\n    var fns = slice.call(arguments).reverse();\n    return _.seq.apply(null, fns);\n};\n\n/**\n * The reversed version of [compose](#compose). Where arguments are in the\n * order of application.\n *\n * @id seq\n * @name _.seq(fn1, fn2, ...)\n * @section Functions\n * @api public\n *\n * var add1 = add(1);\n * var mul3 = mul(3);\n *\n * var add1mul3 = seq(add1, mul3);\n * add1mul3(2) == 9\n */\n\n_.seq = function () {\n    var fns = slice.call(arguments);\n    return function () {\n        if (!fns.length) {\n            return null;\n        }\n        var r = fns[0].apply(this, arguments);\n        for (var i = 1; i < fns.length; i++) {\n            r = fns[i].call(this, r);\n        }\n        return r;\n    };\n};\n\nfunction nop() {\n    // Do nothing.\n}\n\nfunction defaultReadableOnFinish(readable, callback) {\n    // It's possible that `close` is emitted *before* `end`, so we simply\n    // cannot handle that case. See\n    // https://github.com/caolan/highland/issues/490 for details.\n\n    // pipe already pushes on end, so no need to bind to `end`.\n\n    // write any errors into the stream\n    readable.once('error', callback);\n\n    return function () {\n        readable.removeListener('error', callback);\n    };\n}\n\nfunction pipeReadable(xs, onFinish, stream) {\n    var response = onFinish(xs, streamEndCb);\n    var unbound = false;\n\n    var cleanup = null;\n    var endOnError = true;\n\n    if (_.isFunction(response)) {\n        cleanup = response;\n    }\n    else if (response != null) {\n        cleanup = response.onDestroy;\n        endOnError = !response.continueOnError;\n    }\n\n    xs.pipe(stream);\n\n    // TODO: Replace with onDestroy in v3.\n    stream._destructors.push(unbind);\n\n    function streamEndCb(error) {\n        if (stream._nil_pushed) {\n            return;\n        }\n\n        if (error) {\n            stream.write(new StreamError(error));\n        }\n\n        if (error == null || endOnError) {\n            unbind();\n            stream.end();\n        }\n    }\n\n    function unbind() {\n        if (unbound) {\n            return;\n        }\n\n        unbound = true;\n\n        if (cleanup) {\n            cleanup();\n        }\n\n        if (xs.unpipe) {\n            xs.unpipe(stream);\n        }\n    }\n}\n\nfunction promiseStream(promise) {\n    var nilScheduled = false;\n    return _(function (push) {\n        // We need to push asynchronously so that errors thrown from handling\n        // these values are not caught by the promise. Also, return null so\n        // that bluebird-based promises don't complain about handlers being\n        // created but not returned. See\n        // https://github.com/caolan/highland/issues/588.\n        promise = promise.then(function (value) {\n            nilScheduled = true;\n            _.setImmediate(function () {\n                push(null, value);\n                push(null, nil);\n            });\n            return null;\n        }, function (err) {\n            nilScheduled = true;\n            _.setImmediate(function () {\n                push(err);\n                push(null, nil);\n            });\n            return null;\n        });\n\n        // Using finally also handles bluebird promise cancellation, so we do\n        // it if we can.\n        if (_.isFunction(promise['finally'])) { // eslint-disable-line dot-notation\n            promise['finally'](function () { // eslint-disable-line dot-notation\n                if (!nilScheduled) {\n                    _.setImmediate(function () {\n                        push(null, nil);\n                    });\n                }\n                return null;\n            });\n        }\n    });\n}\n\nfunction iteratorStream(it) {\n    return _(function (push, next) {\n        var iterElem, iterErr;\n        try {\n            iterElem = it.next();\n        }\n        catch (err) {\n            iterErr = err;\n        }\n\n        if (iterErr) {\n            push(iterErr);\n            push(null, _.nil);\n        }\n        else if (iterElem.done) {\n            if (!_.isUndefined(iterElem.value)) {\n                // generators can return a final\n                // value on completion using return\n                // keyword otherwise value will be\n                // undefined\n                push(null, iterElem.value);\n            }\n            push(null, _.nil);\n        }\n        else {\n            push(null, iterElem.value);\n            next();\n        }\n\n    });\n}\n\nfunction hintMapper(mappingHint) {\n    var mappingHintType = (typeof mappingHint);\n    var mapper;\n\n    if (mappingHintType === 'function') {\n        mapper = mappingHint;\n    }\n    else if (mappingHintType === 'number') {\n        mapper = function () {\n            return slice.call(arguments, 0, mappingHint);\n        };\n    }\n    else if (_.isArray(mappingHint)) {\n        mapper = function () {\n            var args = arguments;\n            return mappingHint.reduce(function (ctx, hint, idx) {\n                ctx[hint] = args[idx];\n                return ctx;\n            }, {});\n        };\n    }\n    else {\n        mapper = function (x) { return x; };\n    }\n\n    return mapper;\n}\n\nfunction pipeStream(src, dest, write, end, passAlongErrors) {\n    var resume = null;\n    if (!passAlongErrors) {\n        src._send_events = true;\n    }\n\n    var s = src.consume(function (err, x, push, next) {\n        var canContinue;\n        if (err) {\n            if (passAlongErrors) {\n                canContinue = write.call(dest, new StreamError(err));\n            }\n            else {\n                canContinue = true;\n            }\n        }\n        else if (x === nil) {\n            end.call(dest);\n            return;\n        }\n        else {\n            canContinue = write.call(dest, x);\n        }\n\n        if (canContinue !== false) {\n            next();\n        }\n        else {\n            resume = next;\n        }\n    });\n\n    dest.on('drain', onConsumerDrain);\n\n    // Since we don't keep a reference to piped-to streams,\n    // save a callback that will unbind the event handler.\n    src._destructors.push(function () {\n        dest.removeListener('drain', onConsumerDrain);\n    });\n\n    dest.emit('pipe', src);\n\n    // Calling resume() may cause data to be synchronously pushed.\n    // That can cause data loss if the destination is a through stream and it\n    // is unpaused. That is, this chain won't work correctly:\n    //   stream.pipe(unpaused).pipe(otherDest);\n    _.setImmediate(function () {\n        s.resume();\n    });\n    return dest;\n\n    function onConsumerDrain() {\n        if (resume) {\n            var oldResume = resume;\n            resume = null;\n            oldResume();\n        }\n    }\n}\n\nfunction generatorPush(stream, write) {\n    if (!write) {\n        write = stream.write;\n    }\n\n    return function (err, x) {\n        // This will set _nil_pushed if necessary.\n        write.call(stream, err ? new StreamError(err) : x);\n    };\n}\n\n\n/**\n * Actual Stream constructor wrapped the the main exported function\n */\n\n/*eslint-disable no-multi-spaces */\nfunction Stream(/*optional*/xs, /*optional*/secondArg, /*optional*/mappingHint) {\n    /*eslint-enable no-multi-spaces */\n    if (xs && _.isStream(xs)) {\n        // already a Stream\n        return xs;\n    }\n\n    EventEmitter.call(this);\n    var self = this;\n\n    // used to detect Highland Streams using isStream(x), this\n    // will work even in cases where npm has installed multiple\n    // versions, unlike an instanceof check\n    self.__HighlandStream__ = true;\n\n    self.id = ('' + Math.random()).substr(2, 6);\n    this.paused = true;\n    this._incoming = [];\n    this._outgoing = [];\n    this._consumers = [];\n    this._observers = [];\n    this._destructors = [];\n    this._send_events = false;\n    this._nil_pushed = false;\n    this._delegate = null;\n    this._is_observer = false;\n    this._in_consume_cb = false;\n    this._repeat_resume = false;\n\n    // Signals whether or not a call to write() returned false, and thus we can\n    // drain. This is only relevant for streams constructed with _().\n    this._can_drain = false;\n\n    // Used by consume() to signal that next() hasn't been called, so resume()\n    // shouldn't ask for more data. Backpressure handling is getting fairly\n    // complicated, and this is very much a hack to get consume() backpressure\n    // to work correctly.\n    this._consume_waiting_for_next = false;\n    this.source = null;\n\n    // Old-style node Stream.pipe() checks for this\n    this.writable = true;\n\n    self.on('newListener', function (ev) {\n        if (ev === 'data') {\n            self._send_events = true;\n            _.setImmediate(bindContext(self.resume, self));\n        }\n        else if (ev === 'end') {\n            // this property avoids us checking the length of the\n            // listners subscribed to each event on each _send() call\n            self._send_events = true;\n        }\n    });\n\n    // TODO: write test to cover this removeListener code\n    self.on('removeListener', function (ev) {\n        if (ev === 'end' || ev === 'data') {\n            var end_listeners = self.listeners('end').length;\n            var data_listeners = self.listeners('data').length;\n            if (end_listeners + data_listeners === 0) {\n                // stop emitting events\n                self._send_events = false;\n            }\n        }\n    });\n\n    if (_.isUndefined(xs)) {\n        // nothing else to do\n        return this;\n    }\n    else if (_.isArray(xs)) {\n        self._incoming = xs.concat([nil]);\n        return this;\n    }\n    else if (_.isFunction(xs)) {\n        this._generator = xs;\n        this._generator_push = generatorPush(this);\n        this._generator_next = function (s) {\n            if (self._nil_pushed) {\n                throw new Error('Cannot call next after nil');\n            }\n\n            if (s) {\n                // we MUST pause to get the redirect object into the _incoming\n                // buffer otherwise it would be passed directly to _send(),\n                // which does not handle StreamRedirect objects!\n                var _paused = self.paused;\n                if (!_paused) {\n                    self.pause();\n                }\n                self.write(new StreamRedirect(s));\n                if (!_paused) {\n                    self._resume(false);\n                }\n            }\n            else {\n                self._generator_running = false;\n            }\n            if (!self.paused) {\n                self._resume(false);\n            }\n        };\n\n        return this;\n    }\n    else if (_.isObject(xs)) {\n        // check to see if we have a readable stream\n        if (_.isFunction(xs.on) && _.isFunction(xs.pipe)) {\n            var onFinish = _.isFunction(secondArg) ? secondArg : defaultReadableOnFinish;\n            pipeReadable(xs, onFinish, self);\n            return this;\n        }\n        else if (_.isFunction(xs.then)) {\n            //probably a promise\n            return promiseStream(xs);\n        }\n        // must check iterators and iterables in this order\n        // because generators are both iterators and iterables:\n        // their Symbol.iterator method returns the `this` object\n        // and an infinite loop would result otherwise\n        else if (_.isFunction(xs.next)) {\n            //probably an iterator\n            return iteratorStream(xs);\n        }\n        else if (!_.isUndefined(_global.Symbol) && xs[_global.Symbol.iterator]) {\n            //probably an iterable\n            return iteratorStream(xs[_global.Symbol.iterator]());\n        }\n        else {\n            throw new Error(\n                'Object was not a stream, promise, iterator or iterable: ' + (typeof xs)\n            );\n        }\n    }\n    else if (_.isString(xs)) {\n        var mapper = hintMapper(mappingHint);\n\n        var callback_func = function () {\n            var ctx = mapper.apply(this, arguments);\n            self.write(ctx);\n        };\n\n        secondArg.on(xs, callback_func);\n        var removeMethod = secondArg.removeListener // EventEmitter\n                           || secondArg.unbind;     // jQuery\n\n        if (removeMethod) {\n            this._destructors.push(function() {\n                removeMethod.call(secondArg, xs, callback_func);\n            });\n        }\n\n        return this;\n    }\n    else {\n        throw new Error(\n            'Unexpected argument type to Stream(): ' + (typeof xs)\n        );\n    }\n}\ninherits(Stream, EventEmitter);\n\n/**\n * Creates a stream that sends a single value then ends.\n *\n * @id of\n * @section Utils\n * @name _.of(x)\n * @param x - the value to send\n * @returns Stream\n * @api public\n *\n * _.of(1).toArray(_.log); // => [1]\n */\n\n_.of = function (x) {\n    return _([x]);\n};\n\n/**\n * Creates a stream that sends a single error then ends.\n *\n * @id fromError\n * @section Utils\n * @name _.fromError(err)\n * @param error - the error to send\n * @returns Stream\n * @api public\n *\n * _.fromError(new Error('Single Error')).toCallback(function (err, result) {\n *     // err contains Error('Single Error') object\n * }\n */\n\n_.fromError = function (error) {\n    return _(function (push) {\n        push(error);\n        push(null, _.nil);\n    });\n};\n\n/**\n * adds a top-level _.foo(mystream) style export for Stream methods\n */\n\nfunction exposeMethod(name) {\n    var f = Stream.prototype[name];\n    var n = f.length;\n    _[name] = _.ncurry(n + 1, function () {\n        var args = slice.call(arguments);\n        var s = _(args.pop());\n        return f.apply(s, args);\n    });\n}\n\n/**\n * Used as an Error marker when writing to a Stream's incoming buffer\n */\n\nfunction StreamError(err) {\n    this.__HighlandStreamError__ = true;\n    this.error = err;\n}\n\n/**\n * Used as a Redirect marker when writing to a Stream's incoming buffer\n */\n\nfunction StreamRedirect(to) {\n    this.__HighlandStreamRedirect__ = true;\n    this.to = to;\n}\n\n/**\n * Returns true if `x` is the end of stream marker.\n *\n * @id isNil\n * @section Utils\n * @name _.isNil(x)\n * @param x - the object to test\n * @api public\n */\n\n_.isNil = function (x) {\n    return x === _.nil;\n};\n\n/**\n * Returns true if `x` is a Highland Stream.\n *\n * @id isStream\n * @section Utils\n * @name _.isStream(x)\n * @param x - the object to test\n * @returns {Boolean}\n * @api public\n *\n * _.isStream('foo')  // => false\n * _.isStream(_([1,2,3]))  // => true\n */\n\n_.isStream = function (x) {\n    return _.isObject(x) && !!x.__HighlandStream__;\n};\n\n_._isStreamError = function (x) {\n    return _.isObject(x) && !!x.__HighlandStreamError__;\n};\n\n_._isStreamRedirect = function (x) {\n    return _.isObject(x) && !!x.__HighlandStreamRedirect__;\n};\n\n/**\n * Sends errors / data to consumers, observers and event handlers\n */\n\nStream.prototype._send = function (err, x) {\n    //console.log(['_send', this.id, err, x]);\n    var token;\n\n    if (this._consumers.length) {\n        token = err ? new StreamError(err) : x;\n        // this._consumers may be changed from under us,\n        // so we keep a copy.\n        var consumers = this._consumers;\n        for (var i = 0, len = consumers.length; i < len; i++) {\n            consumers[i].write(token);\n        }\n    }\n    if (this._observers.length) {\n        token = err ? new StreamError(err) : x;\n        // this._observers may be changed from under us,\n        // so we keep a copy.\n        var observers = this._observers;\n        for (var j = 0, len2 = observers.length; j < len2; j++) {\n            observers[j].write(token);\n        }\n    }\n    if (this._send_events) {\n        if (err) {\n            this.emit('error', err);\n        }\n        else if (x === nil) {\n            this.emit('end');\n        }\n        else {\n            this.emit('data', x);\n        }\n    }\n\n    if (x === nil) {\n        this._onEnd();\n    }\n};\n\n\nStream.prototype._onEnd = function _onEnd() {\n    if (this.ended) {\n        return;\n    }\n\n    this.pause();\n\n    this.ended = true;\n\n    if (this.source) {\n        var source = this.source;\n        source._removeConsumer(this);\n        source._removeObserver(this);\n    }\n\n    var i, len;\n\n    // _removeConsumer may modify this._consumers.\n    var consumers = this._consumers;\n    for (i = 0, len = consumers.length; i < len; i++) {\n        this._removeConsumer(consumers[i]);\n    }\n\n    // Don't use _removeObserver for efficiency reasons.\n    var observer;\n    for (i = 0, len = this._observers.length; i < len; i++) {\n        observer = this._observers[i];\n        if (observer.source === this) {\n            observer.source = null;\n        }\n    }\n\n    for (i = 0, len = this._destructors.length; i < len; i++) {\n        this._destructors[i].call(this);\n    }\n\n    this.source = null;\n    this._consumers = [];\n    this._incoming = [];\n    this._outgoing = [];\n    this._delegate = null;\n    this._generator = null;\n    this._observers = [];\n    this._destructors = [];\n};\n\n/**\n * Pauses the stream. All Highland Streams start in the paused state.\n *\n * It is unlikely that you will need to manually call this method.\n *\n * @id pause\n * @section Stream Objects\n * @name Stream.pause()\n * @api public\n *\n * var xs = _(generator);\n * xs.pause();\n */\n\nStream.prototype.pause = function () {\n    //console.log(['pause', this.id]);\n    this.paused = true;\n    if (!this._is_observer && this.source) {\n        this.source._checkBackPressure();\n    }\n};\n\n/**\n * When there is a change in downstream consumers, it will often ask\n * the parent Stream to re-check its state and pause/resume accordingly.\n */\n\nStream.prototype._checkBackPressure = function () {\n    if (!this._consumers.length) {\n        this._repeat_resume = false;\n        this.pause();\n        return;\n    }\n    for (var i = 0, len = this._consumers.length; i < len; i++) {\n        if (this._consumers[i].paused) {\n            this._repeat_resume = false;\n            this.pause();\n            return;\n        }\n    }\n\n    this._resume(false);\n};\n\n/**\n * Starts pull values out of the incoming buffer and sending them downstream,\n * this will exit early if this causes a downstream consumer to pause.\n */\n\nStream.prototype._readFromBuffer = function () {\n    //console.log(['_readFromBuffer', this.id, this.paused, this._incoming]);\n    var len = this._incoming.length;\n    var i = 0;\n    while (i < len && !this.paused) {\n        var x = this._incoming[i];\n        if (_._isStreamError(x)) {\n            this._send(x.error);\n        }\n        else if (_._isStreamRedirect(x)) {\n            this._redirect(x.to);\n        }\n        else {\n            this._send(null, x);\n        }\n        i++;\n    }\n    // remove processed data from _incoming buffer\n    this._incoming.splice(0, i);\n};\n\n/**\n * Starts pull values out of the incoming buffer and sending them downstream,\n * this will exit early if this causes a downstream consumer to pause.\n */\n\nStream.prototype._sendOutgoing = function () {\n    //console.log(['_sendOutgoing', this.id, this.paused, this._outgoing]);\n    var len = this._outgoing.length;\n    var i = 0;\n    while (i < len && !this.paused) {\n        var x = this._outgoing[i];\n        if (_._isStreamError(x)) {\n            Stream.prototype._send.call(this, x.error);\n        }\n        else if (_._isStreamRedirect(x)) {\n            this._redirect(x.to);\n        }\n        else {\n            Stream.prototype._send.call(this, null, x);\n        }\n        i++;\n    }\n    // remove processed data from _outgoing buffer\n    this._outgoing.splice(0, i);\n};\n\nStream.prototype._resume = function (forceResumeSource) {\n    //console.log(['resume', this.id]);\n    if (this._resume_running || this._in_consume_cb) {\n        //console.log(['resume already processing _incoming buffer, ignore resume call']);\n        // already processing _incoming buffer, ignore resume call\n        this._repeat_resume = true;\n        return;\n    }\n    this._resume_running = true;\n    do {\n        // use a repeat flag to avoid recursing resume() calls\n        this._repeat_resume = false;\n        this.paused = false;\n\n        // send values from outgoing buffer first\n        this._sendOutgoing();\n\n        // send values from incoming buffer before reading from source\n        this._readFromBuffer();\n\n        // we may have paused while reading from buffer\n        if (!this.paused && !this._is_observer) {\n            // ask parent for more data\n            if (this.source) {\n                if (!this._consume_waiting_for_next || forceResumeSource) {\n                    //console.log(['ask parent for more data']);\n                    this.source._checkBackPressure();\n                }\n            }\n            // run _generator to fill up _incoming buffer\n            else if (this._generator) {\n                //console.log(['run generator to fill up _incoming buffer']);\n                this._runGenerator();\n            }\n            else if (this._can_drain) {\n                // perhaps a node stream is being piped in\n                this._can_drain = false;\n                this.emit('drain');\n            }\n        }\n    } while (this._repeat_resume);\n    this._resume_running = false;\n};\n\n/**\n * Resumes a paused Stream. This will either read from the Stream's incoming\n * buffer or request more data from an upstream source. Never call this method\n * on a stream that has been consumed (via a call to [consume](#consume) or any\n * other transform).\n *\n * @id resume\n * @section Stream Objects\n * @name Stream.resume()\n * @api public\n *\n * var xs = _(generator);\n * xs.resume();\n */\n\nStream.prototype.resume = function () {\n    this._resume(true);\n};\n\n/**\n * Ends a Stream. This is the same as sending a [nil](#nil) value as data.\n * You shouldn't need to call this directly, rather it will be called by\n * any [Node Readable Streams](http://nodejs.org/api/stream.html#stream_class_stream_readable)\n * you pipe in.\n *\n * Only call this function on streams that were constructed with no source\n * (i.e., with `_()`).\n *\n * @id end\n * @section Stream Objects\n * @name Stream.end()\n * @api public\n *\n * mystream.end();\n */\n\nStream.prototype.end = function () {\n    if (this._nil_pushed) {\n        // Allow ending multiple times.\n        return;\n    }\n\n    this.write(nil);\n};\n\n/**\n * Pipes a Highland Stream to a [Node Writable\n * Stream](http://nodejs.org/api/stream.html#stream_class_stream_writable).\n * This will pull all the data from the source Highland Stream and write it to\n * the destination, automatically managing flow so that the destination is not\n * overwhelmed by a fast source.\n *\n * Users may optionally pass an object that may contain any of these fields:\n *\n * - `end` - Ends the destination when this stream ends. Default: `true`. This\n *   option has no effect if the destination is either `process.stdout` or\n *   `process.stderr`. Those two streams are never ended.\n *\n * Like [Readable#pipe](https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options),\n * this function will throw errors if there is no `error` handler installed on\n * the stream.\n *\n * This function returns the destination so you can chain together `pipe` calls.\n *\n * **NOTE**: While Highland streams created via `_()` and [pipeline](#pipeline)\n * support being piped to, it is almost never appropriate to `pipe` from a\n * Highland stream to another Highland stream. Those two cases are meant for\n * use when piping from *Node* streams. You might be tempted to use `pipe` to\n * construct reusable transforms. Do not do it. See [through](#through) for a\n * better way.\n *\n * @id pipe\n * @section Consumption\n * @name Stream.pipe(dest, options)\n * @param {Writable Stream} dest - the destination to write all data to\n * @param {Object} options - (optional) pipe options.\n * @api public\n *\n * var source = _(generator);\n * var dest = fs.createWriteStream('myfile.txt')\n * source.pipe(dest);\n *\n * // chained call\n * source.pipe(through).pipe(dest);\n *\n * // DO NOT do this! It will not work. The stream returned by oddDoubler does\n * // not support being piped to.\n * function oddDoubler() {\n *     return _()\n *         return x % 2; // odd numbers only\n *     })\n *     .map(function (x) {\n *         return x * 2;\n *     });\n * }\n *\n * _([1, 2, 3, 4]).pipe(oddDoubler()) // => Garbage\n */\n\nStream.prototype.pipe = function (dest, options) {\n    options = options || {};\n\n    // stdout and stderr are special case writables that cannot be closed\n    var canClose = dest !== process.stdout && dest !== process.stderr && options.end !== false;\n\n    var end;\n    if (canClose) {\n        end = dest.end;\n    }\n    else {\n        end = nop;\n    }\n\n    return pipeStream(this, dest, dest.write, end, false);\n};\n\n/**\n * Destroys a stream by unlinking it from any consumers and sources. This will\n * stop all consumers from receiving events from this stream and removes this\n * stream as a consumer of any source stream.\n *\n * This function calls end() on the stream and unlinks it from any piped-to streams.\n *\n * @id destroy\n * @section Stream Objects\n * @name Stream.destroy()\n * @api public\n */\n\nStream.prototype.destroy = function () {\n    if (this.ended) {\n        return;\n    }\n\n    if (!this._nil_pushed) {\n        this.end();\n    }\n\n    this._onEnd();\n};\n\n/**\n * Runs the generator function for this Stream. If the generator is already\n * running (it has been called and not called next() yet) then this function\n * will do nothing.\n */\n\nStream.prototype._runGenerator = function () {\n    //console.log(['_runGenerator', this.id]);\n    // if _generator already running, exit\n    if (this._generator_running) {\n        return;\n    }\n    this._generator_running = true;\n    this._generator(this._generator_push, this._generator_next);\n};\n\n/**\n * Performs the redirect from one Stream to another. In order for the\n * redirect to happen at the appropriate time, it is put on the incoming\n * buffer as a StreamRedirect object, and this function is called\n * once it is read from the buffer.\n */\n\nStream.prototype._redirect = function (to) {\n    //console.log(['_redirect', this.id, '=>', to.id]);\n    // coerce to Stream\n    to = _(to);\n\n    while (to._delegate) {\n        to = to._delegate;\n    }\n\n    to._consumers = this._consumers.map(function (c) {\n        c.source = to;\n        return c;\n    });\n\n    // TODO: copy _observers\n    this._consumers = [];\n    //[this.consume = function () {\n    //    return to.consume.apply(to, arguments);\n    //};\n    //this._removeConsumer = function () {\n    //    return to._removeConsumer.apply(to, arguments);\n    //};\n\n    // this will cause a memory leak as long as the root object is around\n    to._delegate_source = this._delegate_source || this;\n    to._delegate_source._delegate = to;\n\n    if (this.paused) {\n        to.pause();\n    }\n    else {\n        this.pause();\n        to._checkBackPressure();\n    }\n};\n\n/**\n * Adds a new consumer Stream, which will accept data and provide backpressure\n * to this Stream. Adding more than one consumer will cause an exception to be\n * thrown as the backpressure strategy must be explicitly chosen by the\n * developer (through calling fork or observe).\n */\n\nStream.prototype._addConsumer = function (s) {\n    if (this._consumers.length) {\n        throw new Error(\n            'This stream has already been transformed or consumed. Please ' +\n                'fork() or observe() the stream if you want to perform ' +\n                'parallel transformations.'\n        );\n    }\n    s.source = this;\n    this._consumers.push(s);\n    this._checkBackPressure();\n};\n\n/**\n * Removes a consumer from this Stream.\n */\n\nStream.prototype._removeConsumer = function (s) {\n    var src = this;\n    while (src._delegate) {\n        src = src._delegate;\n    }\n    src._consumers = src._consumers.filter(function (c) {\n        return c !== s;\n    });\n    if (s.source === src) {\n        s.source = null;\n    }\n    src._checkBackPressure();\n};\n\n/**\n * Removes an observer from this Stream.\n */\n\nStream.prototype._removeObserver = function (s) {\n    this._observers = this._observers.filter(function (o) {\n        return o !== s;\n    });\n    if (s.source === this) {\n        s.source = null;\n    }\n};\n\n/**\n * Consumes values from a Stream (once resumed) and returns a new Stream for\n * you to optionally push values onto using the provided push / next functions.\n *\n * This function forms the basis of many higher-level Stream operations.\n * It will not cause a paused stream to immediately resume, but behaves more\n * like a 'through' stream, handling values as they are read.\n *\n * @id consume\n * @section Transforms\n * @name Stream.consume(f)\n * @param {Function} f - the function to handle errors and values\n * @api public\n *\n * var filter = function (f, source) {\n *     return source.consume(function (err, x, push, next) {\n *         if (err) {\n *             // pass errors along the stream and consume next value\n *             push(err);\n *             next();\n *         }\n *         else if (x === _.nil) {\n *             // pass nil (end event) along the stream\n *             push(null, x);\n *         }\n *         else {\n *             // pass on the value only if the value passes the predicate\n *             if (f(x)) {\n *                 push(null, x);\n *             }\n *             next();\n *         }\n *     });\n * };\n */\n\nStream.prototype.consume = function (f) {\n    var self = this;\n    while (self._delegate) {\n        self = self._delegate;\n    }\n    var s = new Stream();\n\n    // Hack. Not needed in v3.0.\n    s._is_consumer = true;\n\n    var async;\n    var next_called;\n    var _send = s._send;\n    var push = function (err, x) {\n        //console.log(['push', err, x, s.paused]);\n        if (s._nil_pushed) {\n            throw new Error('Cannot write to stream after nil');\n        }\n        if (x === nil) {\n            // ended, remove consumer from source\n            s._nil_pushed = true;\n            s._consume_waiting_for_next = false;\n            self._removeConsumer(s);\n\n            // We previously paused the stream, but since a nil was pushed,\n            // next won't be called and we must manually resume.\n            if (async) {\n                s._resume(false);\n            }\n        }\n        if (s.paused) {\n            if (err) {\n                s._outgoing.push(new StreamError(err));\n            }\n            else {\n                s._outgoing.push(x);\n            }\n        }\n        else {\n            _send.call(s, err, x);\n        }\n    };\n    var next = function (s2) {\n        //console.log(['next', async]);\n        s._consume_waiting_for_next = false;\n        if (s._nil_pushed) {\n            throw new Error('Cannot call next after nil');\n        }\n        if (s2) {\n            // we MUST pause to get the redirect object into the _incoming\n            // buffer otherwise it would be passed directly to _send(),\n            // which does not handle StreamRedirect objects!\n            var _paused = s.paused;\n            if (!_paused) {\n                s.pause();\n            }\n            s.write(new StreamRedirect(s2));\n            if (!_paused) {\n                s._resume(false);\n            }\n        }\n        else if (async) {\n            s._resume(false);\n        }\n        else {\n            next_called = true;\n        }\n    };\n    s._send = function (err, x) {\n        async = false;\n        next_called = false;\n        s._in_consume_cb = true;\n\n        f(err, x, push, next);\n\n        s._in_consume_cb = false;\n        async = true;\n\n        // Don't pause if x is nil -- as next will never be called after\n        if (!next_called && x !== nil) {\n            s._consume_waiting_for_next = true;\n            s.pause();\n        }\n\n        if (s._repeat_resume) {\n            s._repeat_resume = false;\n            s._resume(false);\n        }\n    };\n    self._addConsumer(s);\n    self._already_consumed = true;\n    return s;\n};\nexposeMethod('consume');\n\n/**\n * Consumes a single item from the Stream. Unlike consume, this function will\n * not provide a new stream for you to push values onto, and it will unsubscribe\n * as soon as it has a single error, value or nil from the source.\n *\n * You probably won't need to use this directly, but it is used internally by\n * some functions in the Highland library.\n *\n * @id pull\n * @section Consumption\n * @name Stream.pull(f)\n * @param {Function} f - the function to handle data\n * @api public\n *\n * xs.pull(function (err, x) {\n *     // do something\n * });\n */\n\nStream.prototype.pull = function (f) {\n    var s = this.consume(function (err, x) {\n        s.source._removeConsumer(s);\n        f(err, x);\n    });\n    s.id = 'pull:' + s.id;\n    s.resume();\n};\n\n/**\n * Writes a value to the Stream. If the Stream is paused it will go into the\n * Stream's incoming buffer, otherwise it will be immediately processed and\n * sent to the Stream's consumers (if any). Returns false if the Stream is\n * paused, true otherwise. This lets Node's pipe method handle back-pressure.\n *\n * You shouldn't need to call this yourself, but it may be called by Node\n * functions which treat Highland Streams as a [Node Writable Stream](http://nodejs.org/api/stream.html#stream_class_stream_writable).\n *\n * Only call this function on streams that were constructed with no source\n * (i.e., with `_()`).\n\n * @id write\n * @section Stream Objects\n * @name Stream.write(x)\n * @param x - the value to write to the Stream\n * @api public\n *\n * var xs = _();\n * xs.write(1);\n * xs.write(2);\n * xs.end();\n *\n * xs.toArray(function (ys) {\n *     // ys will be [1, 2]\n * });\n *\n * // Do *not* do this.\n * var xs2 = _().toArray(_.log);\n * xs2.write(1); // This call is illegal.\n */\n\nStream.prototype.write = function (x) {\n    if (this._nil_pushed) {\n        throw new Error('Cannot write to stream after nil');\n    }\n\n    // The check for _is_consumer is kind of a hack. Not\n    // needed in v3.0.\n    if (x === _.nil && !this._is_consumer) {\n        this._nil_pushed = true;\n    }\n\n    if (this.paused) {\n        this._incoming.push(x);\n    }\n    else {\n        if (_._isStreamError(x)) {\n            this._send(x.error);\n        }\n        else {\n            this._send(null, x);\n        }\n    }\n\n    if (this.paused) {\n        this._can_drain = true;\n    }\n\n    return !this.paused;\n};\n\n/**\n * Forks a stream, allowing you to add additional consumers with shared\n * back-pressure. A stream forked to multiple consumers will pull values, *one\n * at a time*, from its source as only fast as the slowest consumer can handle\n * them.\n *\n * **NOTE**: Do not depend on a consistent execution order between the forks.\n * This transform only guarantees that all forks will process a value `foo`\n * before any will process a second value `bar`. It does *not* guarantee the\n * order in which the forks process `foo`.\n *\n * **TIP**: Be careful about modifying stream values within the forks (or using\n * a library that does so). Since the same value will be passed to every fork,\n * changes made in one fork will be visible in any fork that executes after it.\n * Add to that the inconsistent execution order, and you can end up with subtle\n * data corruption bugs. If you need to modify any values, you should make a\n * copy and modify the copy instead.\n *\n * *Deprecation warning:* It is currently possible to `fork` a stream after\n * [consuming](#consume) it (e.g., via a [transform](#Transforms)). This will\n * no longer be possible in the next major release. If you are going to `fork`\n * a stream, always call `fork` on it.\n *\n * @id fork\n * @section Higher-order Streams\n * @name Stream.fork()\n * @api public\n *\n * function delay(x, ms) {\n *   return _((push) => {\n *     setTimeout(() => {\n *       push(null, x);\n *       push(null, _.nil);\n *     }, ms);\n *   });\n * }\n *\n * const then = Date.now();\n *\n * const source = _([1, 2, 3, 4])\n *     .tap((x) => console.log(`source: ${x} (${Date.now() - then})`));\n * const fork1 = source.fork().flatMap((x) => delay(x, 1000));\n * const fork2 = source.fork().flatMap((x) => delay(x, 2000));\n *\n * // No values will be pulled from source until fork2 also starts consuming.\n * fork1.each((x) => console.log(`fork1 : ${x} (${Date.now() - then})`));\n *\n * // Now both fork1 and fork2 will get values from source as fast as they both\n * // can process them.\n * fork2.each((x) => console.log(`fork2 : ${x} (${Date.now() - then})`));\n *\n * // =>\n * // source: 1 (3)\n * // fork1 : 1 (1014)\n * // fork2 : 1 (2011)\n * // source: 2 (2011)\n * // fork1 : 2 (3012)\n * // fork2 : 2 (4012)\n * // source: 3 (4013)\n * // fork1 : 3 (5014)\n * // fork2 : 3 (6020)\n * // source: 4 (6020)\n * // fork1 : 4 (7024)\n * // fork2 : 4 (8032)\n */\n\n// Hack our way around the fact that util.deprecate is all-or-nothing for a\n// function.\nvar warnForkAfterConsume = deprecate(function () {\n}, 'Highland: Calling Stream.fork() on a stream that has already been consumed is deprecated. Always call fork() on a stream that is meant to be forked.');\n\nStream.prototype.fork = function () {\n    if (this._already_consumed) {\n        // Trigger deprecation warning.\n        warnForkAfterConsume();\n    }\n\n    var s = new Stream();\n    s.id = 'fork:' + s.id;\n    s.source = this;\n    this._consumers.push(s);\n    this._checkBackPressure();\n    return s;\n};\n\n/**\n * Observes a stream, allowing you to handle values as they are emitted,\n * without adding back-pressure or causing data to be pulled from the source.\n * Unlike [forks](#fork), observers are passive. They don't affect each other\n * or the source stream. They only observe data as the source stream emits\n * them.\n *\n * Observers will buffer data that it sees from the source, so an observer that\n * cannot process the data as fast as the source produces it can end up\n * consuming a lot of memory.\n *\n * @id observe\n * @section Higher-order Streams\n * @name Stream.observe()\n * @api public\n *\n * function delay(x, ms) {\n *   return _((push) => {\n *     setTimeout(() => {\n *       push(null, x);\n *       push(null, _.nil);\n *     }, ms);\n *   });\n * }\n *\n * const then = Date.now();\n *\n * const source = _([1, 2, 3, 4])\n *     .tap((x) => console.log(`source: ${x} (${Date.now() - then})`));\n * const obs = source.observe().flatMap((x) => delay(x, 1000));\n * const main = source.flatMap((x) => delay(x, 10));\n *\n * // obs will not receive any data yet, since it is only a passive\n * // observer.\n * obs.each((x) => console.log(`obs   : ${x} (${Date.now() - then})`));\n *\n * // Now both obs and main will receive data as fast as main can handle it.\n * // Even though since obs is very slow, main will still receive all of the\n * // source's data.\n * main.each((x) => console.log(`main  : ${x} (${Date.now() - then})`));\n *\n * // =>\n * // source: 1 (3)\n * // main  : 1 (21)\n * // source: 2 (22)\n * // main  : 2 (33)\n * // source: 3 (37)\n * // main  : 3 (47)\n * // source: 4 (47)\n * // main  : 4 (57)\n * // obs   : 1 (1010)\n * // obs   : 2 (2012)\n * // obs   : 3 (3018)\n * // obs   : 4 (4052)\n */\n\nStream.prototype.observe = function () {\n    var s = new Stream();\n    s.id = 'observe:' + s.id;\n    s.source = this;\n    s._is_observer = true;\n    this._observers.push(s);\n    return s;\n};\n\n/**\n * Extracts errors from a Stream and applies them to an error handler\n * function. Returns a new Stream with the errors removed (unless the error\n * handler chooses to rethrow them using `push`). Errors can also be\n * transformed and put back onto the Stream as values.\n *\n * @id errors\n * @section Transforms\n * @name Stream.errors(f)\n * @param {Function} f - the function to pass all errors to\n * @api public\n *\n * getDocument.errors(function (err, push) {\n *     if (err.statusCode === 404) {\n *         // not found, return empty doc\n *         push(null, {});\n *     }\n *     else {\n *         // otherwise, re-throw the error\n *         push(err);\n *     }\n * });\n */\n\nStream.prototype.errors = function (f) {\n    return this.consume(function (err, x, push, next) {\n        if (err) {\n            f(err, push);\n            next();\n        }\n        else if (x === nil) {\n            push(null, nil);\n        }\n        else {\n            push(null, x);\n            next();\n        }\n    });\n};\nexposeMethod('errors');\n\n/**\n * Like the [errors](#errors) method, but emits a Stream end marker after\n * an Error is encountered.\n *\n * @id stopOnError\n * @section Transforms\n * @name Stream.stopOnError(f)\n * @param {Function} f - the function to handle an error\n * @api public\n *\n * brokenStream.stopOnError(function (err) {\n *     //console.error('Something broke: ' + err);\n * });\n */\n\nStream.prototype.stopOnError = function (f) {\n    return this.consume(function (err, x, push, next) {\n        if (err) {\n            f(err, push);\n            push(null, nil);\n        }\n        else if (x === nil) {\n            push(null, nil);\n        }\n        else {\n            push(null, x);\n            next();\n        }\n    });\n};\nexposeMethod('stopOnError');\n\n/**\n * Iterates over every value from the Stream, calling the iterator function\n * on each of them. This method consumes the Stream.\n *\n * If an error from the Stream reaches this call, it will emit an `error` event\n * (i.e., it will call `emit('error')` on the stream being consumed).  This\n * event will cause an error to be thrown if unhandled.\n *\n * While `each` consumes the stream, it is possible to chain [done](#done) (and\n * *only* `done`) after it.\n *\n * @id each\n * @section Consumption\n * @name Stream.each(f)\n * @param {Function} f - the iterator function\n * @api public\n *\n * _([1, 2, 3, 4]).each(function (x) {\n *     // will be called 4 times with x being 1, 2, 3 and 4\n * });\n */\n\nStream.prototype.each = function (f) {\n    var self = this;\n    var s = this.consume(function (err, x, push, next) {\n        if (err) {\n            self.emit('error', err);\n        }\n        else if (x === nil) {\n            push(null, nil);\n        }\n        else {\n            f(x);\n            next();\n        }\n    });\n    s.resume();\n    return s;\n};\nexposeMethod('each');\n\n/**\n * Applies all values from a Stream as arguments to a function. This method consumes the stream.\n * `f` will always be called when the `nil` token is encountered, even when the stream is empty.\n *\n * @id apply\n * @section Consumption\n * @name Stream.apply(f)\n * @param {Function} f - the function to apply arguments to\n * @api public\n *\n * _([1, 2, 3]).apply(function (a, b, c) {\n *     // a === 1\n *     // b === 2\n *     // c === 3\n * });\n *\n * _([1, 2, 3]).apply(function (a) {\n *     // arguments.length === 3\n *     // a === 1\n * });\n */\n\nStream.prototype.apply = function (f) {\n    return this.toArray(function (args) {\n        f.apply(null, args);\n    });\n};\nexposeMethod('apply');\n\n/**\n * Collects all values from a Stream into an Array and calls a function with\n * the result. This method consumes the stream.\n *\n * If an error from the Stream reaches this call, it will emit an `error` event\n * (i.e., it will call `emit('error')` on the stream being consumed).  This\n * event will cause an error to be thrown if unhandled.\n *\n * @id toArray\n * @section Consumption\n * @name Stream.toArray(f)\n * @param {Function} f - the callback to provide the completed Array to\n * @api public\n *\n * _([1, 2, 3, 4]).toArray(function (x) {\n *     // parameter x will be [1,2,3,4]\n * });\n */\n\nStream.prototype.toArray = function (f) {\n    var self = this;\n    return this.collect().pull(function (err, x) {\n        if (err) {\n            self.emit('error', err);\n        }\n        else {\n            f(x);\n        }\n    });\n};\n\n/**\n * Calls a function once the Stream has ended. This method consumes the stream.\n * If the Stream has already ended, the function is called immediately.\n *\n * If an error from the Stream reaches this call, it will emit an `error` event\n * (i.e., it will call `emit('error')` on the stream being consumed).  This\n * event will cause an error to be thrown if unhandled.\n *\n * As a special case, it is possible to chain `done` after a call to\n * [each](#each) even though both methods consume the stream.\n *\n * @id done\n * @section Consumption\n * @name Stream.done(f)\n * @param {Function} f - the callback\n * @api public\n *\n * var total = 0;\n * _([1, 2, 3, 4]).each(function (x) {\n *     total += x;\n * }).done(function () {\n *     // total will be 10\n * });\n */\n\nStream.prototype.done = function (f) {\n    if (this.ended) {\n        f();\n        return null;\n    }\n    var self = this;\n    return this.consume(function (err, x, push, next) {\n        if (err) {\n            self.emit('error', err);\n        }\n        else if (x === nil) {\n            f();\n        }\n        else {\n            next();\n        }\n    }).resume();\n};\n\n/**\n *\n * @id toCallbackHandler\n * @param {string} transformName Description to compose user-friendly error messages\n * @param {function} cb Node.js style callback\n * @return {function} Function passed to .consume\n * @private\n */\n\nfunction toCallbackHandler(transformName, cb) {\n    var value;\n    var hasValue = false; // In case an emitted value === null or === undefined.\n    return function (err, x, push, next) {\n        if (err) {\n            push(null, nil);\n            if (hasValue) {\n                cb(new Error(transformName + ' called on stream emitting multiple values'));\n            }\n            else {\n                cb(err);\n            }\n        }\n        else if (x === nil) {\n            if (hasValue) {\n                cb(null, value);\n            }\n            else {\n                cb();\n            }\n        }\n        else {\n            if (hasValue) {\n                push(null, nil);\n                cb(new Error(transformName + ' called on stream emitting multiple values'));\n            }\n            else {\n                value = x;\n                hasValue = true;\n                next();\n            }\n        }\n    };\n}\n\n\n/**\n * Returns the result of a stream to a nodejs-style callback function.\n *\n * If the stream contains a single value, it will call `cb`\n * with the single item emitted by the stream (if present).\n * If the stream is empty, `cb` will be called without any arguments.\n * If an error is encountered in the stream, this function will stop\n * consumption and call `cb` with the error.\n * If the stream contains more than one item, it will stop consumption\n * and call `cb` with an error.\n *\n * @id toCallback\n * @section Consumption\n * @name Stream.toCallback(cb)\n * @param {Function} cb - the callback to provide the error/result to\n * @api public\n *\n * _([1, 2, 3, 4]).collect().toCallback(function (err, result) {\n *     // parameter result will be [1,2,3,4]\n *     // parameter err will be null\n * });\n */\n\nStream.prototype.toCallback = function (cb) {\n    this.consume(toCallbackHandler('toCallback', cb)).resume();\n};\nexposeMethod('toCallback');\n\n\n/**\n * Converts the result of a stream to Promise.\n *\n * If the stream contains a single value, it will return\n * with the single item emitted by the stream (if present).\n * If the stream is empty, `undefined` will be returned.\n * If an error is encountered in the stream, this function will stop\n * consumption and call `cb` with the error.\n * If the stream contains more than one item, it will stop consumption\n * and reject with an error.\n *\n * @id toPromise\n * @section Consumption\n * @name Stream.toPromise(PromiseCtor)\n * @param {Function} PromiseCtor - Promises/A+ compliant constructor\n * @api public\n *\n * _([1, 2, 3, 4]).collect().toPromise(Promise).then(function (result) {\n *     // parameter result will be [1,2,3,4]\n * });\n */\n\nStream.prototype.toPromise = function (PromiseCtor) {\n    var self = this;\n    return new PromiseCtor(function(resolve, reject) {\n        self.consume(toCallbackHandler('toPromise', function(err, res) {\n            if (err) {\n                reject(err);\n            }\n            else {\n                resolve(res);\n            }\n        })).resume();\n    });\n};\nexposeMethod('toPromise');\n\n\n/**\n * Converts the stream to a node Readable Stream for use in methods\n * or pipes that depend on the native stream type.\n *\n * The options parameter can be an object passed into the [`Readable`\n * constructor](http://nodejs.org/api/stream.html#stream_class_stream_readable).\n *\n * @id toNodeStream\n * @section Consumption\n * @name Stream.toNodeStream(options)\n * @param {Object} options - (optional) [`Readable` constructor](http://nodejs.org/api/stream.html#stream_class_stream_readable) options\n * @api public\n *\n * _(fs.createReadStream('./abc')).toNodeStream()\n * _(fs.createReadStream('./abc')).toNodeStream({objectMode: false})\n * _([{a: 1}]).toNodeStream({objectMode: true})\n */\n\nStream.prototype.toNodeStream = function (options) {\n    var self = this;\n    return new Readable(options).wrap(self);\n};\nexposeMethod('toNodeStream');\n\n\n/**\n * Creates a new Stream of transformed values by applying a function to each\n * value from the source. The transformation function can be replaced with\n * a non-function value for convenience, and it will emit that value\n * for every data event on the source Stream.\n *\n * *Deprecation warning:* The use of the convenience non-function argument for\n * `map` is deprecated and will be removed in the next major version.\n *\n * @id map\n * @section Transforms\n * @name Stream.map(f)\n * @param {Function} f - the transformation function or value to map to\n * @api public\n *\n * var doubled = _([1, 2, 3, 4]).map(function (x) {\n *     return x * 2;\n * });\n */\n\n// Hack our way around the fact that util.deprecate is all-or-nothing for a\n// function.\nvar warnMapWithValue = deprecate(function() {\n}, 'Highland: Calling Stream.map() with a non-function argument is deprecated.');\n\nStream.prototype.map = function (f) {\n    if (!_.isFunction(f)) {\n        warnMapWithValue();\n        var val = f;\n        f = function () {\n            return val;\n        };\n    }\n    return this.consume(function (err, x, push, next) {\n        if (err) {\n            push(err);\n            next();\n        }\n        else if (x === nil) {\n            push(err, x);\n        }\n        else {\n            var fnVal, fnErr;\n            try {\n                fnVal = f(x);\n            }\n            catch (e) {\n                fnErr = e;\n            }\n            push(fnErr, fnVal);\n            next();\n        }\n    });\n};\nexposeMethod('map');\n\n/**\n * Creates a new Stream which applies a function to each value from the source\n * and re-emits the source value. Useful when you want to mutate the value or\n * perform side effects\n *\n * @id doto\n * @section Transforms\n * @name Stream.doto(f)\n * @param {Function} f - the function to apply\n * @api public\n *\n * var appended = _([[1], [2], [3], [4]]).doto(function (x) {\n *     x.push(1);\n * });\n *\n * _([1, 2, 3]).doto(console.log)\n * // 1\n * // 2\n * // 3\n * // => 1, 2, 3\n */\n\nStream.prototype.doto = function (f) {\n    return this.map(function (x) {\n        f(x);\n        return x;\n    });\n};\nexposeMethod('doto');\n\n/**\n * An alias for the [doto](#doto) method.\n *\n * @id tap\n * @section Transforms\n * @name Stream.tap(f)\n * @param {Function} f - the function to apply\n * @api public\n *\n * _([1, 2, 3]).tap(console.log)\n */\n\nStream.prototype.tap = Stream.prototype.doto;\n_.tap = _.doto;\n\n/**\n * Limits number of values through the stream to a maximum of number of values\n * per window. Errors are not limited but allowed to pass through as soon as\n * they are read from the source.\n *\n * @id ratelimit\n * @section Transforms\n * @name Stream.ratelimit(num, ms)\n * @param {Number} num - the number of operations to perform per window\n * @param {Number} ms - the window of time to limit the operations in (in ms)\n * @api public\n *\n * _([1, 2, 3, 4, 5]).ratelimit(2, 100);\n *\n * // after 0ms => 1, 2\n * // after 100ms => 1, 2, 3, 4\n * // after 200ms => 1, 2, 3, 4, 5\n */\n\nStream.prototype.ratelimit = function (num, ms) {\n    if (num < 1) {\n        throw new Error('Invalid number of operations per ms: ' + num);\n    }\n    var sent = 0;\n    return this.consume(function (err, x, push, next) {\n        if (err) {\n            push(err);\n            next();\n        }\n        else if (x === nil) {\n            push(null, nil);\n        }\n        else {\n            if (sent < num) {\n                sent++;\n                push(null, x);\n                next();\n            }\n            else {\n                setTimeout(function () {\n                    sent = 1;\n                    push(null, x);\n                    next();\n                }, ms);\n            }\n        }\n    });\n};\nexposeMethod('ratelimit');\n\n/**\n * Creates a new Stream of values by applying each item in a Stream to an\n * iterator function which must return a (possibly empty) Stream. Each item on\n * these result Streams are then emitted on a single output Stream.\n *\n * This transform is functionally equivalent to `.map(f).sequence()`.\n *\n * @id flatMap\n * @section Higher-order Streams\n * @name Stream.flatMap(f)\n * @param {Function} f - the iterator function\n * @api public\n *\n * var readFile = _.wrapCallback(fs.readFile);\n * filenames.flatMap(readFile)\n */\n\nStream.prototype.flatMap = function (f) {\n    return this.map(f).sequence();\n};\nexposeMethod('flatMap');\n\n/**\n * Retrieves values associated with a given property from all elements in\n * the collection.\n *\n * @id pluck\n * @section Transforms\n * @name Stream.pluck(property)\n * @param {String} prop - the property to which values should be associated\n * @api public\n *\n * var docs = [\n *     {type: 'blogpost', title: 'foo'},\n *     {type: 'blogpost', title: 'bar'},\n *     {type: 'comment', title: 'baz'}\n * ];\n *\n * _(docs).pluck('title').toArray(function (xs) {\n *    // xs is now ['foo', 'bar', 'baz']\n * });\n */\n\nStream.prototype.pluck = function (prop) {\n    return this.consume(function (err, x, push, next) {\n        if (err) {\n            push(err);\n            next();\n        }\n        else if (x === nil) {\n            push(err, x);\n        }\n        else if (_.isObject(x)) {\n            push(null, x[prop]);\n            next();\n        }\n        else {\n            push(new Error(\n                'Expected Object, got ' + (typeof x)\n            ));\n            next();\n        }\n    });\n};\nexposeMethod('pluck');\n\n/**\n * Only applies the transformation strategy on Objects.\n * This helper is used in `pick` and `pickBy`\n **/\n\nvar objectOnly = _.curry(function(strategy, x) {\n    if (_.isObject(x)) {\n        return strategy(x);\n    }\n    else {\n        throw new Error(\n            'Expected Object, got ' + (typeof x)\n        );\n    }\n});\n\n\n/**\n *\n * Retrieves copies of all the elements in the collection\n * that satisfy a given predicate. Note: When using ES3,\n * only enumerable elements are selected. Both enumerable\n * and non-enumerable elements are selected when using ES5.\n *\n * @id pickBy\n * @section Transforms\n * @name Stream.pickBy(f)\n * @param {Function} f - the predicate function\n * @api public\n *\n *  var dogs = [\n *      {breed: 'chihuahua', name: 'Princess', age: 5},\n *      {breed: 'labrador', name: 'Rocky', age: 3},\n *      {breed: 'german-shepherd', name: 'Waffles', age: 9}\n *  ];\n\n *  _(dogs).pickBy(function (key, value) {\n *      return value > 4;\n *  }).toArray(function (xs) {\n *    // xs is now:\n *    [\n *      { age: 5 },\n *      {},\n *      { age: 9 }\n *    ]\n *  });\n */\n\nStream.prototype.pickBy = function (f) {\n    return this.map(objectOnly(function (x) {\n        var out = {};\n\n        // prevents testing overridden properties multiple times.\n        var seen = isES5 ? Object.create(null) : {};\n        var obj = x;  // variable used to traverse prototype chain\n        function testAndAdd (prop) {\n            if (seen[prop] !== true && f(prop, x[prop])) {\n                out[prop] = x[prop];\n                seen[prop] = true;\n            }\n        }\n        if (isES5) {\n            do {\n                Object.getOwnPropertyNames(obj).forEach(testAndAdd);\n                obj = Object.getPrototypeOf(obj);\n            } while (obj);\n        }\n        else {\n            for (var k in x) {\n                testAndAdd(k);\n            }\n        }\n        return out;\n    }));\n};\nexposeMethod('pickBy');\n\n/**\n *\n * Retrieves copies of all elements in the collection,\n * with only the whitelisted keys. If one of the whitelisted\n * keys does not exist, it will be ignored.\n *\n * @id pick\n * @section Transforms\n * @name Stream.pick(properties)\n * @param {Array} properties - property names to white filter\n * @api public\n *\n * var dogs = [\n *      {breed: 'chihuahua', name: 'Princess', age: 5},\n *      {breed: 'labrador', name: 'Rocky', age: 3},\n *      {breed: 'german-shepherd', name: 'Waffles', age: 9}\n * ];\n *\n * _(dogs).pick(['breed', 'age']).toArray(function (xs) {\n *       // xs is now:\n *       [\n *           {breed: 'chihuahua', age: 5},\n *           {breed: 'labrador', age: 3},\n *           {breed: 'german-shepherd', age: 9}\n *       ]\n * });\n *\n * _(dogs).pick(['owner']).toArray(function (xs) {\n *      // xs is now:\n *      [\n *          {},\n *          {},\n *          {}\n *      ]\n * });*/\n\nStream.prototype.pick = function (properties) {\n    return this.map(objectOnly(function(x) {\n        var out = {};\n        for (var i = 0, length = properties.length; i < length; i++) {\n            var p = properties[i];\n            if (p in x) {\n                out[p] = x[p];\n            }\n        }\n        return out;\n    }));\n};\nexposeMethod('pick');\n\n/**\n * Creates a new Stream that includes only the values that pass a truth test.\n *\n * @id filter\n * @section Transforms\n * @name Stream.filter(f)\n * @param {Function} f - the truth test function\n * @api public\n *\n * var evens = _([1, 2, 3, 4]).filter(function (x) {\n *     return x % 2 === 0;\n * });\n */\n\nStream.prototype.filter = function (f) {\n    return this.consume(function (err, x, push, next) {\n        if (err) {\n            push(err);\n            next();\n        }\n        else if (x === nil) {\n            push(err, x);\n        }\n        else {\n            var fnVal, fnErr;\n            try {\n                fnVal = f(x);\n            }\n            catch (e) {\n                fnErr = e;\n            }\n\n            if (fnErr) {\n                push(fnErr);\n            }\n            else if (fnVal) {\n                push(null, x);\n            }\n            next();\n        }\n    });\n};\nexposeMethod('filter');\n\n/**\n * Filters using a predicate which returns a Stream. If you need to check\n * against an asynchronous data source when filtering a Stream, this can\n * be convenient. The Stream returned from the filter function should have\n * a Boolean as its first value (all other values on the Stream will be\n * disregarded).\n *\n * @id flatFilter\n * @section Higher-order Streams\n * @name Stream.flatFilter(f)\n * @param {Function} f - the truth test function which returns a Stream\n * @api public\n *\n * var checkExists = _.wrapCallback(fs.access);\n *\n * filenames.flatFilter(checkExists)\n */\n\nStream.prototype.flatFilter = function (f) {\n    return this.flatMap(function (x) {\n        return f(x).take(1).otherwise(errorStream())\n        .flatMap(function (bool) {\n            return _(bool ? [x] : []);\n        });\n    });\n\n    function errorStream() {\n        return _(function (push) {\n            push(new Error('Stream returned by function was empty.'));\n            push(null, _.nil);\n        });\n    }\n};\nexposeMethod('flatFilter');\n\n/**\n * The inverse of [filter](#filter).\n *\n * @id reject\n * @section Transforms\n * @name Stream.reject(f)\n * @param {Function} f - the truth test function\n * @api public\n *\n * var odds = _([1, 2, 3, 4]).reject(function (x) {\n *     return x % 2 === 0;\n * });\n */\n\nStream.prototype.reject = function (f) {\n    return this.filter(_.compose(_.not, f));\n};\nexposeMethod('reject');\n\n/**\n * A convenient form of [filter](#filter), which returns the first object from a\n * Stream that passes the provided truth test.\n *\n * @id find\n * @section Transforms\n * @name Stream.find(f)\n * @param {Function} f - the truth test function which returns a Stream\n * @api public\n *\n * var docs = [\n *     {type: 'blogpost', title: 'foo'},\n *     {type: 'blogpost', title: 'bar'},\n *     {type: 'comment', title: 'foo'}\n * ];\n *\n * var f = function (x) {\n *     return x.type == 'blogpost';\n * };\n *\n * _(docs).find(f);\n * // => {type: 'blogpost', title: 'foo'}\n *\n * // example with partial application\n * var firstBlogpost = _.find(f);\n *\n * firstBlogpost(docs)\n * // => {type: 'blogpost', title: 'foo'}\n */\n\nStream.prototype.find = function (f) {\n    return this.filter(f).take(1);\n};\nexposeMethod('find');\n\n/**\n * A convenient form of [where](#where), which returns the first object from a\n * Stream that matches a set of property values. findWhere is to [where](#where) as [find](#find) is to [filter](#filter).\n *\n * @id findWhere\n * @section Transforms\n * @name Stream.findWhere(props)\n * @param {Object} props - the properties to match against\n * @api public\n *\n * var docs = [\n *     {type: 'blogpost', title: 'foo'},\n *     {type: 'blogpost', title: 'bar'},\n *     {type: 'comment', title: 'foo'}\n * ];\n *\n * _(docs).findWhere({type: 'blogpost'})\n * // => {type: 'blogpost', title: 'foo'}\n *\n * // example with partial application\n * var firstBlogpost = _.findWhere({type: 'blogpost'});\n *\n * firstBlogpost(docs)\n * // => {type: 'blogpost', title: 'foo'}\n */\n\nStream.prototype.findWhere = function (props) {\n    return this.where(props).take(1);\n};\nexposeMethod('findWhere');\n\n\n/**\n * A convenient form of [reduce](#reduce), which groups items based on a function or property name\n *\n * @id group\n * @section Transforms\n * @name Stream.group(f)\n * @param {Function | String} f - the function or property name on which to group,\n *                              toString() is called on the result of a function.\n * @api public\n *\n * var docs = [\n *     {type: 'blogpost', title: 'foo'},\n *     {type: 'blogpost', title: 'bar'},\n *     {type: 'comment', title: 'foo'}\n * ];\n *\n * var f = function (x) {\n *     return x.type;\n * };\n *\n * _(docs).group(f); OR _(docs).group('type');\n * // => {\n * // =>    'blogpost': [{type: 'blogpost', title: 'foo'}, {type: 'blogpost', title: 'bar'}]\n * // =>    'comment': [{type: 'comment', title: 'foo'}]\n * // =>  }\n *\n */\n\nStream.prototype.group = function (f) {\n    var lambda = _.isString(f) ? _.get(f) : f;\n    return this.reduce({}, function (m, o) {\n        var key = lambda(o);\n        if (!hasOwn.call(m, key)) { m[key] = []; }\n        m[key].push(o);\n        return m;\n    });\n};\nexposeMethod('group');\n\n/**\n * Filters a Stream to drop all non-truthy values.\n *\n * @id compact\n * @section Transforms\n * @name Stream.compact()\n * @api public\n *\n * var compacted = _([0, 1, false, 3, null, undefined, 6]).compact();\n * // => 1, 3, 6\n */\n\nStream.prototype.compact = function () {\n    return this.filter(function (x) {\n        return x;\n    });\n};\nexposeMethod('compact');\n\n/**\n * A convenient form of [filter](#filter), which returns all objects from a Stream\n * which match a set of property values.\n *\n * @id where\n * @section Transforms\n * @name Stream.where(props)\n * @param {Object} props - the properties to match against\n * @api public\n *\n * var docs = [\n *     {type: 'blogpost', title: 'foo'},\n *     {type: 'blogpost', title: 'bar'},\n *     {type: 'comment', title: 'foo'}\n * ];\n *\n * _(docs).where({title: 'foo'})\n * // => {type: 'blogpost', title: 'foo'}\n * // => {type: 'comment', title: 'foo'}\n *\n * // example with partial application\n * var getBlogposts = _.where({type: 'blogpost'});\n *\n * getBlogposts(docs)\n * // => {type: 'blogpost', title: 'foo'}\n * // => {type: 'blogpost', title: 'bar'}\n */\n\nStream.prototype.where = function (props) {\n    return this.filter(function (x) {\n        for (var k in props) {\n            if (x[k] !== props[k]) {\n                return false;\n            }\n        }\n        return true;\n    });\n};\nexposeMethod('where');\n\n/**\n * Filters out all duplicate values from the stream and keeps only the first\n * occurence of each value, using the provided function to define equality.\n *\n * Note:\n *\n * - Memory: In order to guarantee that each unique item is chosen only once,\n *   we need to keep an internal buffer of all unique values. This may outgrow\n *   the available memory if you are not cautious about the size of your stream\n *   and the number of unique objects you may receive on it.\n * - Errors: The comparison function should never throw an error. However, if\n *   it does, this transform will emit an error for each all that throws. This\n *   means that one value may turn into multiple errors.\n *\n * @id uniqBy\n * @section Transforms\n * @name Stream.uniqBy(compare)\n * @param {Function} compare - custom equality predicate\n * @api public\n *\n * var colors = [ 'blue', 'red', 'red', 'yellow', 'blue', 'red' ]\n *\n * _(colors).uniqBy(function(a, b) { return a[1] === b[1]; })\n * // => 'blue'\n * // => 'red'\n *\n */\n\nStream.prototype.uniqBy = function (compare) {\n    var uniques = [];\n    return this.consume(function (err, x, push, next) {\n        if (err) {\n            push(err);\n            next();\n        }\n        else if (x === nil) {\n            push(err, x);\n        }\n        else {\n            var seen = false;\n            var hasErr;\n            for (var i = 0, len = uniques.length; i < len; i++) {\n                try {\n                    seen = compare(x, uniques[i]);\n                }\n                catch (e) {\n                    hasErr = e;\n                    seen = true;\n                }\n                if (seen) {\n                    break;\n                }\n            }\n            if (!seen) {\n                uniques.push(x);\n                push(null, x);\n            }\n            if (hasErr) {\n                push(hasErr);\n            }\n            next();\n        }\n    });\n};\nexposeMethod('uniqBy');\n\n/**\n * Filters out all duplicate values from the stream and keeps only the first\n * occurence of each value, using `===` to define equality.\n *\n * Like [uniqBy](#uniqBy), this transform needs to store a buffer containing\n * all unique values that has been encountered. Be careful about using this\n * transform on a stream that has many unique values.\n *\n * @id uniq\n * @section Transforms\n * @name Stream.uniq()\n * @api public\n *\n * var colors = [ 'blue', 'red', 'red', 'yellow', 'blue', 'red' ]\n *\n * _(colors).uniq()\n * // => 'blue'\n * // => 'red'\n * // => 'yellow'\n */\n\nStream.prototype.uniq = function () {\n    if (!_.isUndefined(_global.Set)) {\n        var uniques = new _global.Set(),\n            size = uniques.size;\n\n        return this.consume(function (err, x, push, next) {\n            if (err) {\n                push(err);\n                next();\n            }\n            else if (x === nil) {\n                push(err, x);\n            }\n            // pass NaN through as Set does not respect strict\n            // equality in this case.\n            else if (x !== x) {\n                push(null, x);\n                next();\n            }\n            else {\n                uniques.add(x);\n                if (uniques.size > size) {\n                    size = uniques.size;\n                    push(null, x);\n                }\n                next();\n            }\n        });\n    }\n    return this.uniqBy(function (a, b) {\n        return a === b;\n    });\n};\nexposeMethod('uniq');\n\n/**\n * Takes a *finite* stream of streams and returns a stream where the first\n * element from each separate stream is combined into a single data event,\n * followed by the second elements of each stream and so on until the shortest\n * input stream is exhausted.\n *\n * *Note:* This transform will be renamed `zipAll` in the next major version\n * release.\n *\n * @id zipAll0\n * @section Higher-order Streams\n * @name Stream.zipAll0()\n * @api public\n *\n * _([\n *     _([1, 2, 3]),\n *     _([4, 5, 6]),\n *     _([7, 8, 9]),\n *     _([10, 11, 12])\n * ]).zipAll0()\n * // => [1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]\n *\n * // shortest stream determines length of output stream\n * _([\n *     _([1, 2, 3, 4]),\n *     _([5, 6, 7, 8]),\n *     _([9, 10, 11, 12]),\n *     _([13, 14])\n * ]).zipAll0()\n * // => [1, 5, 9, 13], [2, 6, 10, 14]\n */\n\nStream.prototype.zipAll0 = function () {\n    var returned = 0;\n    var z = [];\n    var finished = false;\n\n    function nextValue(index, max, src, push, next) {\n        src.pull(function (err, x) {\n            if (err) {\n                push(err);\n                nextValue(index, max, src, push, next);\n            }\n            else if (x === _.nil) {\n                if (!finished) {\n                    finished = true;\n                    push(null, nil);\n                }\n            }\n            else {\n                returned++;\n                z[index] = x;\n                if (returned === max) {\n                    push(null, z);\n                    next();\n                }\n            }\n        });\n    }\n\n    return this.collect().flatMap(function (array) {\n        if (!array.length) {\n            return _([]);\n        }\n\n        return _(function (push, next) {\n            returned = 0;\n            z = [];\n            for (var i = 0, length = array.length; i < length; i++) {\n                nextValue(i, length, array[i], push, next);\n            }\n        });\n    });\n\n};\nexposeMethod('zipAll0');\n\n/**\n * Takes a stream and a *finite* stream of `N` streams\n * and returns a stream of the corresponding `(N+1)`-tuples.\n *\n * *Note:* This transform will be renamed `zipEach` in the next major version\n * release.\n *\n * @id zipAll\n * @section Higher-order Streams\n * @name Stream.zipAll(ys)\n * @param {Array | Stream} ys - the array of streams to combine values with\n * @api public\n *\n * _([1,2,3]).zipAll([[4, 5, 6], [7, 8, 9], [10, 11, 12]])\n * // => [1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]\n *\n * // shortest stream determines length of output stream\n * _([1, 2, 3, 4]).zipAll([[5, 6, 7, 8], [9, 10, 11, 12], [13, 14]])\n * // => [1, 5, 9, 13], [2, 6, 10, 14]\n */\n\nStream.prototype.zipAll = function (ys) {\n    return _([this]).concat(_(ys).map(_)).zipAll0();\n};\nexposeMethod('zipAll');\n\n/**\n * Takes two Streams and returns a Stream of corresponding pairs. The size of\n * the resulting stream is the smaller of the two source streams.\n *\n * @id zip\n * @section Higher-order Streams\n * @name Stream.zip(ys)\n * @param {Array | Stream} ys - the other stream to combine values with\n * @api public\n *\n * _(['a', 'b', 'c']).zip([1, 2, 3])  // => ['a', 1], ['b', 2], ['c', 3]\n *\n * _(['a', 'b', 'c']).zip(_([1]))  // => ['a', 1]\n */\n\nStream.prototype.zip = function (ys) {\n    return _([this, _(ys)]).zipAll0();\n};\nexposeMethod('zip');\n\n/**\n * Takes one Stream and batches incoming data into arrays of given length\n *\n * @id batch\n * @section Transforms\n * @name Stream.batch(n)\n * @param {Number} n - length of the array to batch\n * @api public\n *\n * _([1, 2, 3, 4, 5]).batch(2)  // => [1, 2], [3, 4], [5]\n */\n\nStream.prototype.batch = function (n) {\n    return this.batchWithTimeOrCount(-1, n);\n};\nexposeMethod('batch');\n\n/**\n * Takes one Stream and batches incoming data within a maximum time frame\n * into arrays of a maximum length.\n *\n * @id batchWithTimeOrCount\n * @section Transforms\n * @name Stream.batchWithTimeOrCount(ms, n)\n * @param {Number} ms - the maximum milliseconds to buffer a batch\n * @param {Number} n - the maximum length of the array to batch\n * @api public\n *\n * _(function (push) {\n *     push(1);\n *     push(2);\n *     push(3);\n *     setTimeout(push, 20, 4);\n * }).batchWithTimeOrCount(10, 2)\n *\n * // => [1, 2], [3], [4]\n */\n\nStream.prototype.batchWithTimeOrCount = function (ms, n) {\n    var batched = [],\n        timeout;\n\n    return this.consume(function (err, x, push, next) {\n        if (err) {\n            push(err);\n            next();\n        }\n        else if (x === nil) {\n            if (batched.length > 0) {\n                push(null, batched);\n                clearTimeout(timeout);\n            }\n\n            push(null, nil);\n        }\n        else {\n            batched.push(x);\n\n            if (batched.length === n) {\n                push(null, batched);\n                batched = [];\n                clearTimeout(timeout);\n            }\n            else if (batched.length === 1 && ms >= 0) {\n                timeout = setTimeout(function () {\n                    push(null, batched);\n                    batched = [];\n                }, ms);\n            }\n\n            next();\n        }\n    });\n};\nexposeMethod('batchWithTimeOrCount');\n\n/**\n * Creates a new Stream with the separator interspersed between the elements of the source.\n *\n * `intersperse` is effectively the inverse of [splitBy](#splitBy).\n *\n * @id intersperse\n * @section Transforms\n * @name Stream.intersperse(sep)\n * @param {String} sep - the value to intersperse between the source elements\n * @api public\n *\n * _(['ba', 'a', 'a']).intersperse('n')  // => 'ba', 'n', 'a', 'n', 'a'\n * _(['mississippi']).splitBy('ss').intersperse('ss')  // => 'mi', 'ss', 'i', 'ss', 'ippi'\n * _(['foo']).intersperse('bar')  // => 'foo'\n */\n\nStream.prototype.intersperse = function (separator) {\n    var started = false;\n    return this.consume(function (err, x, push, next) {\n        if (err) {\n            push(err);\n            next();\n        }\n        else if (x === nil) {\n            push(null, nil);\n        }\n        else {\n            if (started) {\n                push(null, separator);\n            }\n            else {\n                started = true;\n            }\n            push(null, x);\n            next();\n        }\n    });\n};\nexposeMethod('intersperse');\n\n/**\n * Splits the source Stream by a separator and emits the pieces in between, much like splitting a string.\n *\n * `splitBy` is effectively the inverse of [intersperse](#intersperse).\n *\n * @id splitBy\n * @section Transforms\n * @name Stream.splitBy(sep)\n * @param {String | RegExp} sep - the separator to split on\n * @api public\n *\n * _(['mis', 'si', 's', 'sippi']).splitBy('ss')  // => 'mi', 'i', 'ippi'\n * _(['ba', 'a', 'a']).intersperse('n').splitBy('n')  // => 'ba', 'a', 'a'\n * _(['foo']).splitBy('bar')  // => 'foo'\n */\n\nStream.prototype.splitBy = function (sep) {\n    var decoder = new Decoder();\n    var buffer = false;\n\n    function drain(x, push) {\n        buffer = (buffer || '') + decoder.write(x);\n        var pieces = buffer.split(sep);\n        buffer = pieces.pop();\n\n        pieces.forEach(function (piece) {\n            push(null, piece);\n        });\n    }\n\n    return this.consume(function (err, x, push, next) {\n        if (err) {\n            push(err);\n            next();\n        }\n        else if (x === nil) {\n            if (_.isString(buffer)) {\n                drain(decoder.end(), push);\n                push(null, buffer);\n            }\n            push(null, nil);\n        }\n        else {\n            drain(x, push);\n            next();\n        }\n    });\n};\nexposeMethod('splitBy');\n\n/**\n * [splitBy](#splitBy) over newlines.\n *\n * @id split\n * @section Transforms\n * @name Stream.split()\n * @api public\n *\n * _(['a\\n', 'b\\nc\\n', 'd', '\\ne']).split()  // => 'a', 'b', 'c', 'd', 'e'\n * _(['a\\r\\nb\\nc']]).split()  // => 'a', 'b', 'c'\n */\n\nStream.prototype.split = function () {\n    return this.splitBy(/\\r?\\n/);\n};\nexposeMethod('split');\n\n/**\n * Creates a new Stream with the values from the source in the range of `start` (inclusive) to `end` (exclusive).\n * `start` and `end` must be of type `Number`, if `start` is not a `Number` it will default to `0`\n * and, likewise, `end` will default to `Infinity`: this could result in the whole stream being be\n * returned.\n *\n * @id slice\n * @section Transforms\n * @name Stream.slice(start, end)\n * @param {Number} start - integer representing index to start reading from source (inclusive)\n * @param {Number} stop - integer representing index to stop reading from source (exclusive)\n * @api public\n *\n * _([1, 2, 3, 4]).slice(1, 3) // => 2, 3\n */\n\nStream.prototype.slice = function(start, end) {\n    var index = 0;\n    start = typeof start != 'number' || start < 0 ? 0 : start;\n    end = typeof end != 'number' ? Infinity : end;\n\n    if (start === 0 && end === Infinity) {\n        return this;\n    }\n    else if (start >= end) {\n        return _([]);\n    }\n    var s = this.consume(function (err, x, push, next) {\n        var done = x === nil;\n        if (err) {\n            push(err);\n        }\n        else if (!done && index++ >= start) {\n            push(null, x);\n        }\n\n        if (!done && index < end) {\n            next();\n        }\n        else {\n            push(null, nil);\n        }\n    });\n    s.id = 'slice:' + s.id;\n    return s;\n};\nexposeMethod('slice');\n\n/**\n * Creates a new Stream with the first `n` values from the source. `n` must be of type `Number`,\n * if not the whole stream will be returned.\n *\n * @id take\n * @section Transforms\n * @name Stream.take(n)\n * @param {Number} n - integer representing number of values to read from source\n * @api public\n *\n * _([1, 2, 3, 4]).take(2) // => 1, 2\n */\n\nStream.prototype.take = function (n) {\n    var s = this.slice(0, n);\n    s.id = 'take:' + s.id;\n    return s;\n};\nexposeMethod('take');\n\n/**\n * Acts as the inverse of [`take(n)`](#take) - instead of returning the first `n` values, it ignores the\n * first `n` values and then emits the rest. `n` must be of type `Number`, if not the whole stream will\n * be returned. All errors (even ones emitted before the nth value) will be emitted.\n *\n * @id drop\n * @section Transforms\n * @name Stream.drop(n)\n * @param {Number} n - integer representing number of values to read from source\n * @api public\n *\n * _([1, 2, 3, 4]).drop(2) // => 3, 4\n */\n\nStream.prototype.drop = function (n) {\n    return this.slice(n, Infinity);\n};\nexposeMethod('drop');\n\n/**\n * Creates a new Stream with only the first value from the source.\n *\n * @id head\n * @section Transforms\n * @name Stream.head()\n * @api public\n *\n * _([1, 2, 3, 4]).head() // => 1\n */\n\nStream.prototype.head = function () {\n    return this.take(1);\n};\nexposeMethod('head');\n\n/**\n * Drops all values from the Stream apart from the last one (if any).\n *\n * @id last\n * @section Transforms\n * @name Stream.last()\n * @api public\n *\n * _([1, 2, 3, 4]).last()  // => 4\n */\n\nStream.prototype.last = function () {\n    var nothing = {};\n    var prev = nothing;\n    return this.consume(function (err, x, push, next) {\n        if (err) {\n            push(err);\n            next();\n        }\n        else if (x === nil) {\n            if (prev !== nothing) {\n                push(null, prev);\n            }\n            push(null, nil);\n        }\n        else {\n            prev = x;\n            next();\n        }\n    });\n};\nexposeMethod('last');\n\n/**\n * Collects all values together then emits each value individually in sorted\n * order. The method for sorting the elements is defined by the comparator\n * function supplied as a parameter.\n *\n * The comparison function takes two arguments `a` and `b` and should return\n *\n * - a negative number if `a` should sort before `b`.\n * - a positive number if `a` should sort after `b`.\n * - zero if `a` and `b` may sort in any order (i.e., they are equal).\n *\n * This function must also define a [partial\n * order](https://en.wikipedia.org/wiki/Partially_ordered_set). If it does not,\n * the resulting ordering is undefined.\n *\n * @id sortBy\n * @section Transforms\n * @name Stream.sortBy(f)\n * @param {Function} f - the comparison function\n * @api public\n *\n * var sorts = _([3, 1, 4, 2]).sortBy(function (a, b) {\n *     return b - a;\n * }).toArray(_.log);\n *\n * //=> [4, 3, 2, 1]\n */\n\nStream.prototype.sortBy = function (f) {\n    return this.collect().invoke('sort', [f]).sequence();\n};\nexposeMethod('sortBy');\n\n/**\n * Collects all values together then emits each value individually but in sorted order.\n * The method for sorting the elements is ascending lexical.\n *\n * @id sort\n * @section Transforms\n * @name Stream.sort()\n * @api public\n *\n * var sorted = _(['b', 'z', 'g', 'r']).sort().toArray(_.log);\n * // => ['b', 'g', 'r', 'z']\n */\n\nStream.prototype.sort = function () {\n    return this.sortBy();\n};\nexposeMethod('sort');\n\n\n/**\n * Transforms a stream using an arbitrary target transform.\n *\n * If `target` is a function, this transform passes the current Stream to it,\n * returning the result.\n *\n * If `target` is a [Duplex\n * Stream](https://nodejs.org/api/stream.html#stream_class_stream_duplex_1),\n * this transform pipes the current Stream through it. It will always return a\n * Highland Stream (instead of the piped to target directly as in\n * [pipe](#pipe)). Any errors emitted will be propagated as Highland errors.\n *\n * **TIP**: Passing a function to `through` is a good way to implement complex\n * reusable stream transforms. You can even construct the function dynamically\n * based on certain inputs. See examples below.\n *\n * @id through\n * @section Higher-order Streams\n * @name Stream.through(target)\n * @param {Function | Duplex Stream} target - the stream to pipe through or a\n * function to call.\n * @api public\n *\n * // This is a static complex transform.\n * function oddDoubler(s) {\n *     return s.filter(function (x) {\n *         return x % 2; // odd numbers only\n *     })\n *     .map(function (x) {\n *         return x * 2;\n *     });\n * }\n *\n * // This is a dynamically-created complex transform.\n * function multiplyEvens(factor) {\n *     return function (s) {\n *         return s.filter(function (x) {\n *             return x % 2 === 0;\n *         })\n *         .map(function (x) {\n *             return x * factor;\n *         });\n *     };\n * }\n *\n * _([1, 2, 3, 4]).through(oddDoubler); // => 2, 6\n *\n * _([1, 2, 3, 4]).through(multiplyEvens(5)); // => 10, 20\n *\n * // Can also be used with Node Through Streams\n * _(filenames).through(jsonParser).map(function (obj) {\n *     // ...\n * });\n *\n * // All errors will be propagated as Highland errors\n * _(['zz{\"a\": 1}']).through(jsonParser).errors(function (err) {\n *   console.log(err); // => SyntaxError: Unexpected token z\n * });\n */\n\nStream.prototype.through = function (target) {\n    var output;\n\n    if (_.isFunction(target)) {\n        return target(this);\n    }\n    else {\n        output = _();\n        this.on('error', writeErr);\n        target.on('error', writeErr);\n\n        // Intentionally bypass this.pipe so that through() and pipe() can\n        // evolve independently of each other.\n        return pipeStream(this, target, target.write, target.end, false)\n            .pipe(output);\n    }\n\n    function writeErr(err) {\n        output.write(new StreamError(err));\n    }\n};\nexposeMethod('through');\n\n/**\n * Creates a 'Through Stream', which passes data through a pipeline\n * of functions or other through Streams. This is particularly useful\n * when combined with partial application of Highland functions to expose a\n * Node-compatible Through Stream.\n *\n * This is not a method on a Stream, and it only exposed at the top-level\n * as `_.pipeline`. It takes an arbitrary number of arguments.\n *\n * @id pipeline\n * @section Higher-order Streams\n * @name _.pipeline(...)\n * @api public\n *\n * var through = _.pipeline(\n *     _.map(parseJSON),\n *     _.filter(isBlogpost),\n *     _.reduce(collectCategories)\n *     _.through(otherPipeline)\n * );\n *\n * readStream.pipe(through).pipe(outStream);\n *\n * // Alternatively, you can use pipeline to manipulate a stream in\n * // the chained method call style:\n *\n * var through2 = _.pipeline(function (s) {\n *     return s.map(parseJSON).filter(isBlogpost); // etc.\n * });\n */\n\n_.pipeline = function (/*through...*/) {\n    if (!arguments.length) {\n        return _();\n    }\n    var start = arguments[0], rest, startHighland;\n    if (!_.isStream(start) && !_.isFunction(start.resume)) {\n        // not a Highland stream or Node stream, start with empty stream\n        start = _();\n        startHighland = start;\n        rest = slice.call(arguments);\n    }\n    else {\n        // got a stream as first argument, co-erce to Highland stream\n        startHighland = _(start);\n        rest = slice.call(arguments, 1);\n    }\n\n    var end = rest.reduce(function (src, dest) {\n        return src.through(dest);\n    }, startHighland);\n\n    var wrapper = _(function (push, next) {\n        end.pull(function (err, x) {\n            push(err, x);\n            if (x !== nil) {\n                next();\n            }\n        });\n    });\n\n    wrapper.write = function (x) {\n        return start.write(x);\n    };\n\n    wrapper.end = function () {\n        return start.end();\n    };\n\n    start.on('drain', function () {\n        wrapper.emit('drain');\n    });\n\n    return wrapper;\n};\n\n/**\n * Reads values from a Stream of Streams or Arrays, emitting them on a single\n * output Stream. This can be thought of as a [flatten](#flatten), just one\n * level deep, often used for resolving asynchronous actions such as a HTTP\n * request or reading a file.\n *\n * @id sequence\n * @section Higher-order Streams\n * @name Stream.sequence()\n * @api public\n *\n * var nums = _([\n *     _([1, 2, 3]),\n *     _([4, 5, 6])\n * ]);\n *\n * nums.sequence()  // => 1, 2, 3, 4, 5, 6\n *\n * // using sequence to read from files in series\n * var readFile = _.wrapCallback(fs.readFile);\n * filenames.map(readFile).sequence()\n */\n\nStream.prototype.sequence = function () {\n    var original = this;\n    var curr = this;\n    return _(function (push, next) {\n        curr.pull(function (err, x) {\n            if (err) {\n                push(err);\n                next();\n            }\n            else if (_.isArray(x)) {\n                if (onOriginalStream()) {\n                    // just send all values from array directly\n                    x.forEach(function (y) {\n                        push(null, y);\n                    });\n                }\n                else {\n                    push(null, x);\n                }\n                next();\n            }\n            else if (_.isStream(x)) {\n                if (onOriginalStream()) {\n                    // switch to reading new stream\n                    curr = x;\n                    next();\n                }\n                else {\n                    // sequence only goes 1 level deep\n                    push(null, x);\n                    next();\n                }\n            }\n            else if (x === nil) {\n                if (onOriginalStream()) {\n                    push(null, nil);\n                }\n                else {\n                    // resume reading from original\n                    curr = original;\n                    next();\n                }\n            }\n            else {\n                if (onOriginalStream()) {\n                    // we shouldn't be getting non-stream (or array)\n                    // values from the top-level stream\n                    push(new Error(\n                        'Expected Stream, got ' + (typeof x)\n                    ));\n                    next();\n                }\n                else {\n                    push(null, x);\n                    next();\n                }\n            }\n        });\n    });\n\n    function onOriginalStream() {\n        return curr === original;\n    }\n};\nexposeMethod('sequence');\n\n/**\n * An alias for the [sequence](#sequence) method.\n *\n * @id series\n * @section Higher-order Streams\n * @name Stream.series()\n * @api public\n *\n * var readFile = _.wrapCallback(fs.readFile);\n * filenames.map(readFile).series()\n */\n\nStream.prototype.series = Stream.prototype.sequence;\n_.series = _.sequence;\n\n/**\n * Recursively reads values from a Stream which may contain nested Streams\n * or Arrays. As values or errors are encountered, they are emitted on a\n * single output Stream.\n *\n * @id flatten\n * @section Higher-order Streams\n * @name Stream.flatten()\n * @api public\n *\n * _([1, [2, 3], [[4]]]).flatten();  // => 1, 2, 3, 4\n *\n * var nums = _(\n *     _([1, 2, 3]),\n *     _([4, _([5, 6]) ])\n * );\n *\n * nums.flatten();  // => 1, 2, 3, 4, 5, 6\n */\n\nStream.prototype.flatten = function () {\n    var curr = this;\n    var stack = [];\n    return _(function (push, next) {\n        curr.pull(function (err, x) {\n            if (err) {\n                push(err);\n                next();\n                return;\n            }\n            if (_.isArray(x)) {\n                x = _(x);\n            }\n            if (_.isStream(x)) {\n                stack.push(curr);\n                curr = x;\n                next();\n            }\n            else if (x === nil) {\n                if (stack.length) {\n                    curr = stack.pop();\n                    next();\n                }\n                else {\n                    push(null, nil);\n                }\n            }\n            else {\n                push(null, x);\n                next();\n            }\n        });\n    });\n};\nexposeMethod('flatten');\n\n/**\n * Takes a Stream of Streams and reads from them in parallel, buffering\n * the results until they can be returned to the consumer in their original\n * order.\n *\n * @id parallel\n * @section Higher-order Streams\n * @name Stream.parallel(n)\n * @param {Number} n - the maximum number of concurrent reads/buffers\n * @api public\n *\n * var readFile = _.wrapCallback(fs.readFile);\n * var filenames = _(['foo.txt', 'bar.txt', 'baz.txt']);\n *\n * // read from up to 10 files at once\n * filenames.map(readFile).parallel(10);\n */\n\nStream.prototype.parallel = function (n) {\n    var source = this;\n    var running = [];\n    var ended = false;\n    var reading_source = false;\n\n    if (typeof n !== 'number') {\n        throw new Error('Must specify a number to parallel().');\n    }\n\n    if (n <= 0) {\n        throw new Error('The parallelism factor must be positive');\n    }\n\n    return _(function (push, next) {\n        if (running.length < n && !ended && !reading_source) {\n            // get another stream if not already waiting for one\n            reading_source = true;\n            source.pull(function (err, x) {\n                reading_source = false;\n                if (err) {\n                    push(err);\n                }\n                else if (x === nil) {\n                    ended = true;\n                }\n                else if (!_.isStream(x)) {\n                    push(new Error('Expected Stream, got ' + (typeof x)));\n                }\n                else {\n                    // got a new source, add it to the running array\n                    var run = {stream: x, buffer: []};\n                    running.push(run);\n                    x.consume(function (_err, y, _push, _next) {\n                        if (running[0] === run) {\n                            // current output stream\n                            if (y === nil) {\n                                // remove self from running and check\n                                // to see if we need to read from source again\n                                running.shift();\n                                flushBuffer();\n                                next();\n\n                            }\n                            else {\n                                // push directly onto parallel output stream\n                                push(_err, y);\n                            }\n                        }\n                        else {\n                            // we're reading ahead, buffer the output\n                            run.buffer.push([_err, y]);\n                        }\n                        if (y !== nil) {\n                            // keep reading until we hit nil\n                            _next();\n                        }\n                    }).resume();\n                }\n                // check if we need to get any more streams\n                return next();\n            });\n        }\n        else if (!running.length && ended) {\n            // nothing more to do\n            push(null, nil);\n        }\n\n        function flushBuffer() {\n            while (running.length && running[0].buffer.length) {\n                var buf = running[0].buffer;\n                for (var i = 0; i < buf.length; i++) {\n                    if (buf[i][1] === nil) {\n                        // this stream has ended\n                        running.shift();\n                        break;\n                    }\n                    else {\n                        // send the buffered output\n                        push.apply(null, buf[i]);\n                    }\n                }\n                buf.length = 0;\n            }\n        }\n        // else wait for more data to arrive from running streams\n    });\n};\nexposeMethod('parallel');\n\n/**\n * Switches source to an alternate Stream if the current Stream is empty.\n *\n * @id otherwise\n * @section Higher-order Streams\n * @name Stream.otherwise(ys)\n * @param {Stream | Function} ys - alternate stream (or stream-returning function) to use if this stream is empty\n * @api public\n *\n * _([1,2,3]).otherwise(['foo'])  // => 1, 2, 3\n * _([]).otherwise(['foo'])       // => 'foo'\n *\n * _.otherwise(_(['foo']), _([1,2,3]))    // => 1, 2, 3\n * _.otherwise(_(['foo']), _([]))         // => 'foo'\n */\n\nStream.prototype.otherwise = function (ys) {\n    var xs = this;\n    return xs.consume(function (err, x, push, next) {\n        if (err) {\n            // got an error, just keep going\n            push(err);\n            next();\n        }\n        else if (x === nil) {\n            // hit the end without redirecting to xs, use alternative\n            if (_.isFunction(ys)) {\n                next(ys());\n            }\n            else {\n                next(ys);\n            }\n        }\n        else {\n            // got a value, push it, then redirect to xs\n            push(null, x);\n            next(xs);\n        }\n    });\n};\nexposeMethod('otherwise');\n\n/**\n * Adds a value to the end of a Stream.\n *\n * @id append\n * @section Transforms\n * @name Stream.append(y)\n * @param y - the value to append to the Stream\n * @api public\n *\n * _([1, 2, 3]).append(4)  // => 1, 2, 3, 4\n */\n\nStream.prototype.append = function (y) {\n    return this.consume(function (err, x, push, next) {\n        if (x === nil) {\n            push(null, y);\n            push(null, _.nil);\n        }\n        else {\n            push(err, x);\n            next();\n        }\n    });\n};\nexposeMethod('append');\n\n/**\n * Boils down a Stream to a single value. The memo is the initial state\n * of the reduction, and each successive step of it should be returned by\n * the iterator function. The iterator is passed two arguments:\n * the memo and the next value.\n *\n * If the iterator throws an error, the reduction stops and the resulting\n * stream will emit that error instead of a value.\n *\n * *Note:* The order of the `memo` and `iterator` arguments will be flipped in\n * the next major version release.\n *\n * @id reduce\n * @section Transforms\n * @name Stream.reduce(memo, iterator)\n * @param memo - the initial state of the reduction\n * @param {Function} iterator - the function which reduces the values\n * @api public\n *\n * var add = function (a, b) {\n *     return a + b;\n * };\n *\n * _([1, 2, 3, 4]).reduce(0, add)  // => 10\n */\n\nStream.prototype.reduce = function (z, f) {\n    // This can't be implemented with scan(), because we don't know if the\n    // errors that we see from the scan were thrown by the iterator or just\n    // passed through from the source stream.\n    return this.consume(function (err, x, push, next) {\n        if (x === nil) {\n            push(null, z);\n            push(null, _.nil);\n        }\n        else if (err) {\n            push(err);\n            next();\n        }\n        else {\n            try {\n                z = f(z, x);\n            }\n            catch (e) {\n                push(e);\n                push(null, _.nil);\n                return;\n            }\n\n            next();\n        }\n    });\n};\nexposeMethod('reduce');\n\n/**\n * Same as [reduce](#reduce), but uses the first element as the initial\n * state instead of passing in a `memo` value.\n *\n * @id reduce1\n * @section Transforms\n * @name Stream.reduce1(iterator)\n * @param {Function} iterator - the function which reduces the values\n * @api public\n *\n * _([1, 2, 3, 4]).reduce1(add)  // => 10\n */\n\nStream.prototype.reduce1 = function (f) {\n    var self = this;\n    return _(function (push, next) {\n        self.pull(function (err, x) {\n            if (err) {\n                push(err);\n                next();\n            }\n            else if (x === nil) {\n                push(null, nil);\n            }\n            else {\n                next(self.reduce(x, f));\n            }\n        });\n    });\n};\nexposeMethod('reduce1');\n\n/**\n * Groups all values into an Array and passes down the stream as a single\n * data event. This is a bit like doing [toArray](#toArray), but instead\n * of accepting a callback and consuming the stream, it passes the value on.\n *\n * @id collect\n * @section Transforms\n * @name Stream.collect()\n * @api public\n *\n * _(['foo', 'bar']).collect().toArray(function (xs) {\n *     // xs will be [['foo', 'bar']]\n * });\n */\n\nStream.prototype.collect = function () {\n    var xs = [];\n    return this.consume(function (err, x, push, next) {\n        if (err) {\n            push(err);\n            next();\n        }\n        else if (x === nil) {\n            push(null, xs);\n            push(null, nil);\n        }\n        else {\n            xs.push(x);\n            next();\n        }\n    });\n};\nexposeMethod('collect');\n\n/**\n * Like [reduce](#reduce), but emits each intermediate value of the\n * reduction as it is calculated.\n *\n * If the iterator throws an error, the scan will stop and the stream will\n * emit that error. Any intermediate values that were produced before the\n * error will still be emitted.\n *\n * *Note:* The order of the `memo` and `iterator` arguments will be flipped in\n * the next major version release.\n *\n * @id scan\n * @section Transforms\n * @name Stream.scan(memo, iterator)\n * @param memo - the initial state of the reduction\n * @param {Function} iterator - the function which reduces the values\n * @api public\n *\n * _([1, 2, 3, 4]).scan(0, add)  // => 0, 1, 3, 6, 10\n */\n\nStream.prototype.scan = function (z, f) {\n    var self = this;\n    return _([z]).concat(\n        self.consume(function (err, x, push, next) {\n            if (x === nil) {\n                push(null, _.nil);\n            }\n            else if (err) {\n                push(err);\n                next();\n            }\n            else {\n                try {\n                    z = f(z, x);\n                }\n                catch (e) {\n                    push(e);\n                    push(null, _.nil);\n                    return;\n                }\n\n                push(null, z);\n                next();\n            }\n        })\n    );\n};\nexposeMethod('scan');\n\n/**\n * Same as [scan](#scan), but uses the first element as the initial\n * state instead of passing in a `memo` value.\n *\n * @id scan1\n * @section Transforms\n * @name Stream.scan1(iterator)\n * @param {Function} iterator - the function which reduces the values\n * @api public\n *\n * _([1, 2, 3, 4]).scan1(add)  // => 1, 3, 6, 10\n */\n\nStream.prototype.scan1 = function (f) {\n    var self = this;\n    return _(function (push, next) {\n        self.pull(function (err, x) {\n            if (err) {\n                push(err);\n                next();\n            }\n            else if (x === nil) {\n                push(null, nil);\n            }\n            else {\n                next(self.scan(x, f));\n            }\n        });\n    });\n};\nexposeMethod('scan1');\n\nfunction HighlandTransform(push) {\n    this.push = push;\n}\n\nHighlandTransform.prototype['@@transducer/init'] = function () {\n    return this.push;\n};\n\nHighlandTransform.prototype['@@transducer/result'] = function (push) {\n    // Don't push nil here. Otherwise, we can't catch errors from `result`\n    // and propagate them. The `transduce` implementation will do it.\n    return push;\n};\n\nHighlandTransform.prototype['@@transducer/step'] = function (push, input) {\n    push(null, input);\n    return push;\n};\n\n/**\n * Applies the transformation defined by the the given *transducer* to the\n * stream. A transducer is any function that follows the\n * [Transducer Protocol](https://github.com/cognitect-labs/transducers-js#transformer-protocol).\n * See\n * [transduce-js](https://github.com/cognitect-labs/transducers-js#transducers-js)\n * for more details on what transducers actually are.\n *\n * The `result` object that is passed in through the\n * [Transformer Protocol](https://github.com/cognitect-labs/transducers-js#transformer-protocol)\n * will be the `push` function provided by the [consume](#consume) transform.\n *\n * Like [scan](#scan), if the transducer throws an exception, the transform\n * will stop and emit that error. Any intermediate values that were produced\n * before the error will still be emitted.\n *\n * @id transduce\n * @section Transforms\n * @name Stream.transduce(xf)\n * @param {Function} xf - The transducer.\n * @api public\n *\n * var xf = require('transducer-js').map(_.add(1));\n * _([1, 2, 3, 4]).transduce(xf);\n * // => 2, 3, 4, 5\n */\n\nStream.prototype.transduce = function transduce(xf) {\n    var transform = null,\n        memo = null;\n\n    return this.consume(function (err, x, push, next) {\n        if (transform == null) {\n            transform = xf(new HighlandTransform(push));\n            memo = transform['@@transducer/init']();\n        }\n\n        if (err) {\n            // Pass through errors, like we always do.\n            push(err);\n            next();\n        }\n        else if (x === _.nil) {\n            // Push may be different from memo depending on the transducer that\n            // we get.\n            runResult(push, memo);\n        }\n        else {\n            var res = runStep(push, memo, x);\n\n            if (!res) {\n                return;\n            }\n\n            memo = res;\n            if (memo['@@transducer/reduced']) {\n                runResult(memo['@@transducer/value']);\n            }\n            else {\n                next();\n            }\n        }\n    });\n\n    function runResult(push, _memo) {\n        try {\n            transform['@@transducer/result'](_memo);\n        }\n        catch (e) {\n            push(e);\n        }\n        push(null, _.nil);\n    }\n\n    function runStep(push, _memo, x) {\n        try {\n            return transform['@@transducer/step'](_memo, x);\n        }\n        catch (e) {\n            push(e);\n            push(null, _.nil);\n            return null;\n        }\n    }\n};\nexposeMethod('transduce');\n\n/**\n * Concatenates a Stream to the end of this Stream.\n *\n * Be aware that in the top-level export, the args may be in the reverse\n * order to what you'd expect `_([a], [b]) => b, a`, as this follows the\n * convention of other top-level exported functions which do `x` to `y`.\n *\n * @id concat\n * @section Higher-order Streams\n * @name Stream.concat(ys)\n * @param {Stream | Array} ys - the values to concatenate onto this Stream\n * @api public\n *\n * _([1, 2]).concat([3, 4])  // => 1, 2, 3, 4\n * _.concat([3, 4], [1, 2])  // => 1, 2, 3, 4\n */\n\nStream.prototype.concat = function (ys) {\n    ys = _(ys);\n    return this.consume(function (err, x, push, next) {\n        if (x === nil) {\n            next(ys);\n        }\n        else {\n            push(err, x);\n            next();\n        }\n    });\n};\nexposeMethod('concat');\n\n/**\n * Takes a Stream of Streams and merges their values and errors into a\n * single new Stream. The merged stream ends when all source streams have\n * ended.\n *\n * Note that no guarantee is made with respect to the order in which\n * values for each stream end up in the merged stream. Values in the\n * merged stream will, however, respect the order they were emitted from\n * their respective streams.\n *\n * @id merge\n * @section Higher-order Streams\n * @name Stream.merge()\n * @api public\n *\n * var readFile = _.wrapCallback(fs.readFile);\n *\n * var txt = _(['foo.txt', 'bar.txt']).map(readFile)\n * var md = _(['baz.md']).map(readFile)\n *\n * _([txt, md]).merge();\n * // => contents of foo.txt, bar.txt and baz.txt in the order they were read\n */\n\nStream.prototype.merge = function () {\n    var self = this;\n    var srcs = [];\n\n    var srcsNeedPull = [],\n        first = true,\n        async = false;\n\n    return _(function (push, next) {\n        if (first) {\n            first = false;\n            getSourcesSync(push, next);\n        }\n\n        if (srcs.length === 0) {\n            push(null, nil);\n        }\n        else if (srcsNeedPull.length) {\n            pullFromAllSources(push, next);\n            next();\n        }\n        else {\n            async = true;\n        }\n    });\n\n    // Make a handler for the main merge loop.\n    function srcPullHandler(push, next, src) {\n        return function (err, x) {\n            if (err) {\n                push(err);\n                srcsNeedPull.push(src);\n            }\n            else if (x === nil) {\n                srcs = srcs.filter(function (s) {\n                    return s !== src;\n                });\n            }\n            else {\n                if (src === self) {\n                    srcs.push(x);\n                    srcsNeedPull.push(x);\n                    srcsNeedPull.unshift(self);\n                }\n                else {\n                    push(null, x);\n                    srcsNeedPull.push(src);\n                }\n            }\n\n            if (async) {\n                async = false;\n                next();\n            }\n        };\n    }\n\n\n    function pullFromAllSources(push, next) {\n        var _srcs = srcsNeedPull;\n        srcsNeedPull = [];\n        _srcs.forEach(function (src) {\n            src.pull(srcPullHandler(push, next, src));\n        });\n    }\n\n    // Pulls as many sources as possible from self synchronously.\n    function getSourcesSync(push, next) {\n        // Shadows the outer async variable.\n        var asynchronous;\n        var done = false;\n\n        var pull_cb = function(err, x) {\n            asynchronous = false;\n            if (done) {\n                // This means the pull was async. Handle like\n                // regular async.\n                srcPullHandler(push, next, self)(err, x);\n            }\n            else {\n                if (err) {\n                    push(err);\n                }\n                else if (x === nil) {\n                    done = true;\n                }\n                else {\n                    srcs.push(x);\n                    srcsNeedPull.push(x);\n                }\n            }\n        };\n\n        while (!done) {\n            asynchronous = true;\n            self.pull(pull_cb);\n\n            // Async behavior, record self as a src and return.\n            if (asynchronous) {\n                done = true;\n                srcs.unshift(self);\n            }\n        }\n    }\n\n};\nexposeMethod('merge');\n\n/**\n * Takes a Stream of Streams and merges their values and errors into a\n * single new Stream, limitting the number of unpaused streams that can\n * running at any one time.\n *\n * Note that no guarantee is made with respect to the order in which\n * values for each stream end up in the merged stream. Values in the\n * merged stream will, however, respect the order they were emitted from\n * their respective streams.\n *\n * @id mergeWithLimit\n * @section Higher-order Streams\n * @name Stream.mergeWithLimit(n)\n * @param {Number} n - the maximum number of streams to run in parallel\n * @api public\n *\n * var readFile = _.wrapCallback(fs.readFile);\n *\n * var txt = _(['foo.txt', 'bar.txt']).flatMap(readFile)\n * var md = _(['baz.md']).flatMap(readFile)\n * var js = _(['bosh.js']).flatMap(readFile)\n *\n * _([txt, md, js]).mergeWithLimit(2);\n * // => contents of foo.txt, bar.txt, baz.txt and bosh.js in the order\n * // they were read, but bosh.js is not read until either foo.txt and bar.txt\n * // has completely been read or baz.md has been read\n */\n\n\nStream.prototype.mergeWithLimit = function (n){\n    var self = this;\n    var processCount = 0;\n    var waiting = false;\n    if (typeof n !== 'number' || n < 1) {\n        throw new Error('mergeWithLimit expects a positive number, but got: ' + n);\n    }\n\n    if (n === Infinity) {\n        return this.merge();\n    }\n    return _(function(push, next){\n        self.pull(function(err, x){\n            var done = x === nil;\n            if (err){\n                push(err);\n                next();\n            }\n            else if (x === nil) {\n                push(null, nil);\n            }\n            else {\n                processCount++;\n                push(err, x);\n                // console.log('start', x.id);\n                x._destructors.push(function(){\n                    processCount--;\n                    // console.log('end', x.id);\n                    if (waiting) {\n                        // console.log('get more');\n                        waiting = false;\n                        next();\n                    }\n                });\n                if (!done && processCount < n) {\n                    next();\n                }\n                else {\n                    // console.log('wait till something ends');\n                    waiting = true;\n                }\n            }\n\n        });\n    }).merge();\n};\nexposeMethod('mergeWithLimit');\n\n/**\n * Calls a named method on each object from the Stream - returning\n * a new stream with the result of those calls.\n *\n * @id invoke\n * @section Transforms\n * @name Stream.invoke(method, args)\n * @param {String} method - the method name to call\n * @param {Array} args - the arguments to call the method with\n * @api public\n *\n * _(['foo', 'bar']).invoke('toUpperCase', [])  // => 'FOO', 'BAR'\n *\n * var readFile = _.wrapCallback(fs.readFile);\n * filenames.flatMap(readFile).invoke('toString', ['utf8']);\n */\n\nStream.prototype.invoke = function (method, args) {\n    return this.map(function (x) {\n        return x[method].apply(x, args);\n    });\n};\nexposeMethod('invoke');\n\n/**\n * Takes a Stream of callback-accepting node-style functions,\n * [wraps](#wrapCallback) each one into a stream-returning function,\n * calls them with the arguments provided, and returns the results\n * as a Stream.\n *\n * This can be used as a control flow shortcut and draws parallels\n * with some control flow functions from [async](https://github.com/caolan/async).\n * A few rough correspondences include:\n *\n * - `.nfcall([]).series()` to `async.series()`\n * - `.nfcall([]).parallel(n)` to `async.parallelLimit(n)`\n * - `.nfcall(args)` to `async.applyEach(..., args)`\n * - `.nfcall(args).series()` to `async.applyEachSeries(..., args)`\n *\n * @id nfcall\n * @section Transforms\n * @name Stream.nfcall(args)\n * @param {Array} args - the arguments to call each function with\n * @api public\n *\n * _([\n *   function (callback) {\n *     setTimeout(function () {\n *       callback(null, 'one');\n *     }, 200);\n *   },\n *   function (callback) {\n *     setTimeout(function () {\n *       callback(null, 'two');\n *     }, 100);\n *   }\n * ]).nfcall([]).parallel(2).toArray(function (xs) {\n *   // xs is ['one', 'two'] even though second function had a shorter timeout\n * });\n *\n * _([enableSearch, updateSchema]).nfcall(['bucket']).toArray(callback);\n * // does roughly the same as\n * async.applyEach([enableSearch, updateSchema], 'bucket', callback);\n *\n * _([\n *   fs.appendFile,\n *   fs.appendFile\n * ]).nfcall(['example.txt', 'hello']).series().toArray(function() {\n *   // example.txt now contains 'hellohello'\n * });\n *\n */\n\nStream.prototype.nfcall = function (args) {\n    return this.map(function (x) {\n        return _.wrapCallback(x).apply(x, args);\n    });\n};\nexposeMethod('nfcall');\n\n/**\n * Ensures that only one data event is push downstream (or into the buffer)\n * every `ms` milliseconds, any other values are dropped.\n *\n * @id throttle\n * @section Transforms\n * @name Stream.throttle(ms)\n * @param {Number} ms - the minimum milliseconds between each value\n * @api public\n *\n * _('mousemove', document).throttle(1000);\n */\n\nStream.prototype.throttle = function (ms) {\n    var last = 0 - ms;\n    return this.consume(function (err, x, push, next) {\n        var now = new Date().getTime();\n        if (err) {\n            push(err);\n            next();\n        }\n        else if (x === nil) {\n            push(null, nil);\n        }\n        else if (now - ms >= last) {\n            last = now;\n            push(null, x);\n            next();\n        }\n        else {\n            next();\n        }\n    });\n};\nexposeMethod('throttle');\n\n/**\n * Holds off pushing data events downstream until there has been no more\n * data for `ms` milliseconds. Sends the last value that occurred before\n * the delay, discarding all other values.\n *\n * **Implementation Note**: This transform will will not wait the full `ms`\n * delay to emit a pending value (if any) once it see a `nil`, as that\n * guarantees that there will be no more values.\n *\n * @id debounce\n * @section Transforms\n * @name Stream.debounce(ms)\n * @param {Number} ms - the milliseconds to wait before sending data\n * @api public\n *\n * function delay(x, ms, push) {\n *     setTimeout(function () {\n *         push(null, x);\n *     }, ms);\n * }\n *\n * // sends last keyup event after user has stopped typing for 1 second\n * $('keyup', textbox).debounce(1000);\n *\n * // A nil triggers the emit immediately\n * _(function (push, next) {\n *     delay(0, 100, push);\n *     delay(1, 200, push);\n *     delay(_.nil, 250, push);\n * }).debounce(75);\n * // => after 175ms => 1\n * // => after 250ms (not 275ms!) => 1 2\n */\n\nStream.prototype.debounce = function (ms) {\n    var t = null;\n    var nothing = {};\n    var last = nothing;\n\n    return this.consume(function (err, x, push, next) {\n        if (err) {\n            // let errors through regardless\n            push(err);\n            next();\n        }\n        else if (x === nil) {\n            if (t) {\n                clearTimeout(t);\n            }\n            if (last !== nothing) {\n                push(null, last);\n            }\n            push(null, nil);\n        }\n        else {\n            last = x;\n            if (t) {\n                clearTimeout(t);\n            }\n            t = setTimeout(function () {\n                push(null, x);\n            }, ms);\n            next();\n        }\n    });\n};\nexposeMethod('debounce');\n\n/**\n * Creates a new Stream, which when read from, only returns the last\n * seen value from the source. The source stream does not experience\n * back-pressure. Useful if you're using a Stream to model a changing\n * property which you need to query periodically.\n *\n * @id latest\n * @section Transforms\n * @name Stream.latest()\n * @api public\n *\n * // slowThing will always get the last known mouse position\n * // when it asks for more data from the mousePosition stream\n * mousePosition.latest().map(slowThing)\n */\n\nStream.prototype.latest = function () {\n    var nothing = {},\n        latest = nothing,\n        errors = [],\n        ended = false,\n        onValue = null;\n\n    this.consume(function (err, x, push, next) {\n        if (onValue != null) {\n            var cb = onValue;\n            onValue = null;\n            cb(err, x);\n        }\n\n        if (err) {\n            errors.push(err);\n            next();\n        }\n        else if (x === nil) {\n            ended = true;\n        }\n        else {\n            latest = x;\n            next();\n        }\n    }).resume();\n\n    return _(function (push, next) {\n        var oldErrors = errors;\n        errors = [];\n\n        if (!oldErrors.length && latest === nothing && !ended) {\n            // We haven't gotten any data yet. We can't call next\n            // because that might cause the stream to call the generator\n            // again, resulting in an infinite loop. Thus, we stick a\n            // a callback to be called whenever we get a value.\n            onValue = function (err, x) {\n                push(err, x);\n                if (x !== nil) {\n                    next();\n                }\n            };\n        }\n        else {\n            oldErrors.forEach(push);\n            if (latest !== nothing) {\n                push(null, latest);\n            }\n            if (ended) {\n                push(null, nil);\n            }\n            else {\n                next();\n            }\n        }\n    });\n};\nexposeMethod('latest');\n\n/**\n * Returns values from an Object as a Stream. Reads properties\n * lazily, so if you don't read from all keys on an object, not\n * all properties will be read from (may have an effect where getters\n * are used).\n *\n * @id values\n * @section Objects\n * @name _.values(obj)\n * @param {Object} obj - the object to return values from\n * @api public\n *\n * _.values({foo: 1, bar: 2, baz: 3})  // => 1, 2, 3\n */\n\n_.values = function (obj) {\n    return _.keys(obj).map(function (k) {\n        return obj[k];\n    });\n};\n\n/**\n * Returns keys from an Object as a Stream.\n *\n * @id keys\n * @section Objects\n * @name _.keys(obj)\n * @param {Object} obj - the object to return keys from\n * @api public\n *\n * _.keys({foo: 1, bar: 2, baz: 3})  // => 'foo', 'bar', 'baz'\n */\n\nfunction keys (obj) {\n    var keysArray = [];\n    for (var k in obj) {\n        if (hasOwn.call(obj, k)) {\n            keysArray.push(k);\n        }\n    }\n    return keysArray;\n}\n\n_.keys = function (obj) {\n    return _(keys(obj));\n};\n\n/**\n * Returns key/value pairs for an Object as a Stream. Reads properties\n * lazily, so if you don't read from all keys on an object, not\n * all properties will be read from (may have an effect where getters\n * are used).\n *\n * @id pairs\n * @section Objects\n * @name _.pairs(obj)\n * @param {Object} obj - the object to return key/value pairs from\n * @api public\n *\n * _.pairs({foo: 1, bar: 2})  // => ['foo', 1], ['bar', 2]\n */\n\n_.pairs = function (obj) {\n    return _.keys(obj).map(function (k) {\n        return [k, obj[k]];\n    });\n};\n\n/**\n * Extends one object with the properties of another. **Note:** The\n * arguments are in the reverse order of other libraries such as\n * underscore. This is so it follows the convention of other functions in\n * this library and so you can more meaningfully partially apply it.\n *\n * @id extend\n * @section Objects\n * @name _.extend(a, b)\n * @param {Object} a - the properties to extend b with\n * @param {Object} b - the original object to extend\n * @api public\n *\n * _.extend({name: 'bar'}, {name: 'foo', price: 20})\n * // => {name: 'bar', price: 20}\n *\n * // example of partial application\n * var publish = _.extend({published: true});\n *\n * publish({title: 'test post'})\n * // => {title: 'test post', published: true}\n */\n\n_.extend = _.curry(function (extensions, target) {\n    for (var k in extensions) {\n        if (hasOwn.call(extensions, k)) {\n            target[k] = extensions[k];\n        }\n    }\n    return target;\n});\n\n/**\n * Returns a property from an object.\n *\n * @id get\n * @section Objects\n * @name _.get(prop, obj)\n * @param {String} prop - the property to return\n * @param {Object} obj - the object to read properties from\n * @api public\n *\n * var obj = {foo: 'bar', baz: 123};\n * _.get('foo', obj) // => 'bar'\n *\n * // making use of partial application\n * var posts = [\n *   {title: 'one'},\n *   {title: 'two'},\n *   {title: 'three'}\n * ];\n *\n * _(posts).map(_.get('title'))  // => 'one', 'two', 'three'\n */\n\n_.get = _.curry(function (prop, obj) {\n    return obj[prop];\n});\n\n/**\n * Updates a property on an object, returning the updated object.\n *\n * @id set\n * @section Objects\n * @name _.set(prop, value, obj)\n * @param {String} prop - the property to return\n * @param value - the value to set the property to\n * @param {Object} obj - the object to set properties on\n * @api public\n *\n * var obj = {foo: 'bar', baz: 123};\n * _.set('foo', 'wheeee', obj) // => {foo: 'wheeee', baz: 123}\n *\n * // making use of partial application\n * var publish = _.set('published', true);\n *\n * publish({title: 'example'})  // => {title: 'example', published: true}\n */\n\n_.set = _.curry(function (prop, val, obj) {\n    obj[prop] = val;\n    return obj;\n});\n\n/**\n * Logs values to the console, a simple wrapper around `console.log` that\n * it suitable for passing to other functions by reference without having to\n * call `bind`.\n *\n * @id log\n * @section Utils\n * @name _.log(args..)\n * @api public\n *\n * _.log('Hello, world!');\n *\n * _([1, 2, 3, 4]).each(_.log);\n */\n\n_.log = function () {\n    console.log.apply(console, arguments);\n};\n\n/**\n * Wraps a node-style async function which accepts a callback, transforming\n * it to a function which accepts the same arguments minus the callback and\n * returns a Highland Stream instead. The wrapped function keeps its context,\n * so you can safely use it as a method without binding (see the second\n * example below).\n *\n * `wrapCallback` also accepts an optional `mappingHint`, which specifies how\n * callback arguments are pushed to the stream. This can be used to handle\n * non-standard callback protocols that pass back more than one value.\n *\n * `mappingHint` can be a function, number, or array. See the documentation on\n * [EventEmitter Stream Objects](#Stream Objects) for details on the mapping\n * hint. If `mappingHint` is a function, it will be called with all but the\n * first argument that is passed to the callback. The first is still assumed to\n * be the error argument.\n *\n * @id wrapCallback\n * @section Utils\n * @name _.wrapCallback(f)\n * @param {Function} f - the node-style function to wrap\n * @param {Array | Function | Number} mappingHint - (optional) how to pass the\n * arguments to the callback\n * @api public\n *\n * var fs = require('fs');\n *\n * var readFile = _.wrapCallback(fs.readFile);\n *\n * readFile('example.txt').apply(function (data) {\n *     // data is now the contents of example.txt\n * });\n *\n * function Reader(file) {\n *     this.file = file;\n * }\n *\n * Reader.prototype.read = function(cb) {\n *     fs.readFile(this.file, cb);\n * };\n *\n * Reader.prototype.readStream = _.wrapCallback(Reader.prototype.read);\n */\n\n/*eslint-disable no-multi-spaces */\n_.wrapCallback = function (f, /*optional*/mappingHint) {\n    /*eslint-enable no-multi-spaces */\n    var mapper = hintMapper(mappingHint);\n\n    return function () {\n        var self = this;\n        var args = slice.call(arguments);\n        return _(function (push) {\n            var cb = function (err) {\n                if (err) {\n                    push(err);\n                }\n                else {\n                    var cbArgs = slice.call(arguments, 1);\n                    var v = mapper.apply(this, cbArgs);\n                    push(null, v);\n                }\n                push(null, nil);\n            };\n            f.apply(self, args.concat([cb]));\n        });\n    };\n};\n\n/**\n * Takes an object or a constructor function and returns that object or\n * constructor with streamified versions of its function properties.\n * Passed constructors will also have their prototype functions\n * streamified.  This is useful for wrapping many node style async\n * functions at once, and for preserving those functions' context.\n *\n * @id streamifyAll\n * @section Utils\n * @name _.streamifyAll(source)\n * @param {Object | Function} source - the function or object with\n * node-style function properties.\n * @api public\n *\n * var fs = _.streamifyAll(require('fs'));\n *\n * fs.readFileStream('example.txt').apply(function (data) {\n *     // data is now the contents of example.txt\n * });\n */\n\nfunction isClass (fn) {\n    if (!(typeof fn === 'function' && fn.prototype)) { return false; }\n    var getKeys = isES5 ? Object.getOwnPropertyNames : keys;\n    var allKeys = getKeys(fn.prototype);\n    return allKeys.length > 0 && !(allKeys.length === 1 &&\n            allKeys[0] === 'constructor');\n}\n\nfunction inheritedKeys (obj) {\n    var allProps = {};\n    var curr = obj;\n    var handleProp = function (prop) {\n        allProps[prop] = true;\n    };\n    while (Object.getPrototypeOf(curr)) {\n        var props = Object.getOwnPropertyNames(curr);\n        props.forEach(handleProp);\n        curr = Object.getPrototypeOf(curr);\n    }\n    return keys(allProps);\n}\n\nfunction streamifyAll (inp, suffix) {\n    // will not streamify inherited functions in ES3\n    var getKeys = isES5 ? inheritedKeys : keys;\n    var allKeys = getKeys(inp);\n\n    for (var i = 0, len = allKeys.length; i < len; i++) {\n        var key = allKeys[i];\n        var val;\n\n        // will skip context aware getters\n        try {\n            val = inp[key];\n        }\n        catch (e) {\n            // Ignore\n        }\n\n        if (val && typeof val === 'function' && !isClass(val) &&\n                !val.__HighlandStreamifiedFunction__) {\n\n            var streamified = _.wrapCallback(val);\n            streamified.__HighlandStreamifiedFunction__ = true;\n            inp[key + suffix] = streamified;\n        }\n    }\n    return inp;\n}\n\n_.streamifyAll = function (arg) {\n    if (typeof arg !== 'function' && typeof arg !== 'object') {\n        throw new TypeError('takes an object or a constructor function');\n    }\n    var suffix = 'Stream';\n\n    var ret = streamifyAll(arg, suffix);\n    if (isClass(arg)) {\n        ret.prototype = streamifyAll(arg.prototype, suffix);\n    }\n    return ret;\n};\n\n/**\n * Add two values. Can be partially applied.\n *\n * @id add\n * @section Operators\n * @name _.add(a, b)\n * @api public\n *\n * _.add(1, 2) === 3\n * _.add(1)(5) === 6\n */\n\n_.add = _.curry(function (a, b) {\n    return a + b;\n});\n\n/**\n * Perform logical negation on a value. If `x` is truthy then returns false,\n * otherwise returns true.\n *\n * @id not\n * @section Operators\n * @name _.not(x)\n * @param x - the value to negate\n * @api public\n *\n * _.not(true)   // => false\n * _.not(false)  // => true\n */\n\n_.not = function (x) {\n    return !x;\n};\n"]}