|
| 1 | +var Splicer = require('stream-splicer'); |
| 2 | +var inherits = require('inherits'); |
| 3 | +var isarray = require('isarray'); |
| 4 | + |
| 5 | +module.exports = Labeled; |
| 6 | +inherits(Labeled, Splicer); |
| 7 | + |
| 8 | +module.exports.obj = function (streams, opts) { |
| 9 | + if (!opts) opts = {}; |
| 10 | + opts.objectMode = true; |
| 11 | + return new Labeled(streams, opts); |
| 12 | +}; |
| 13 | + |
| 14 | +function Labeled (streams, opts) { |
| 15 | + if (!(this instanceof Labeled)) return new Labeled(streams, opts); |
| 16 | + Splicer.call(this, [], opts); |
| 17 | + |
| 18 | + var reps = []; |
| 19 | + for (var i = 0; i < streams.length; i++) { |
| 20 | + var s = streams[i]; |
| 21 | + if (typeof s === 'string') continue; |
| 22 | + if (isarray(s)) { |
| 23 | + s = new Labeled(s, opts); |
| 24 | + } |
| 25 | + if (i >= 0 && typeof streams[i-1] === 'string') { |
| 26 | + s.label = streams[i-1]; |
| 27 | + } |
| 28 | + reps.push(s); |
| 29 | + } |
| 30 | + if (typeof streams[i-1] === 'string') { |
| 31 | + reps.push(new Labeled([], opts)); |
| 32 | + } |
| 33 | + this.splice.apply(this, [0,0].concat(reps)); |
| 34 | +} |
| 35 | + |
| 36 | +Labeled.prototype.indexOf = function (stream) { |
| 37 | + if (typeof stream === 'string') { |
| 38 | + for (var i = 0; i < this._streams.length; i++) { |
| 39 | + if (this._streams[i].label === stream) return i; |
| 40 | + } |
| 41 | + return -1; |
| 42 | + } |
| 43 | + else { |
| 44 | + return Splicer.prototype.indexOf.call(this, stream); |
| 45 | + } |
| 46 | +}; |
| 47 | + |
| 48 | +Labeled.prototype.get = function (key) { |
| 49 | + if (typeof key === 'string') { |
| 50 | + var ix = this.indexOf(key); |
| 51 | + if (ix < 0) return undefined; |
| 52 | + return this._streams[ix]; |
| 53 | + } |
| 54 | + else return Splicer.prototype.get.call(this, key); |
| 55 | +}; |
| 56 | + |
| 57 | +Labeled.prototype.splice = function (key) { |
| 58 | + var ix; |
| 59 | + if (typeof key === 'string') { |
| 60 | + ix = this.indexOf(key); |
| 61 | + } |
| 62 | + else ix = key; |
| 63 | + var args = [ ix ].concat([].slice.call(arguments, 1)); |
| 64 | + return Splicer.prototype.splice.apply(this, args); |
| 65 | +}; |
0 commit comments