index.js 1.7 KB

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