index.js 1.7 KB

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