index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. var expect = require('chai').expect
  2. , unique = require('..')
  3. , Stream = require('stream')
  4. , after = require('after')
  5. , setImmediate = global.setImmediate || process.nextTick;
  6. describe('unique stream', function() {
  7. function makeStream(type) {
  8. var s = new Stream();
  9. s.readable = true;
  10. var n = 10;
  11. var next = after(n, function () {
  12. setImmediate(function () {
  13. s.emit('end');
  14. });
  15. });
  16. for (var i = 0; i < n; i++) {
  17. var o = {
  18. type: type,
  19. name: 'name ' + i,
  20. number: i * 10
  21. };
  22. (function (o) {
  23. setImmediate(function () {
  24. s.emit('data', o);
  25. next();
  26. });
  27. })(o);
  28. }
  29. return s;
  30. }
  31. it('should be able to uniqueify objects based on JSON data', function(done) {
  32. var aggregator = unique();
  33. makeStream('a')
  34. .pipe(aggregator);
  35. makeStream('a')
  36. .pipe(aggregator);
  37. var n = 0;
  38. aggregator
  39. .on('data', function () {
  40. n++;
  41. })
  42. .on('end', function () {
  43. expect(n).to.equal(10);
  44. done();
  45. });
  46. });
  47. it('should be able to uniqueify objects based on a property', function(done) {
  48. var aggregator = unique('number');
  49. makeStream('a')
  50. .pipe(aggregator);
  51. makeStream('b')
  52. .pipe(aggregator);
  53. var n = 0;
  54. aggregator
  55. .on('data', function () {
  56. n++;
  57. })
  58. .on('end', function () {
  59. expect(n).to.equal(10);
  60. done();
  61. });
  62. });
  63. it('should be able to uniqueify objects based on a function', function(done) {
  64. var aggregator = unique(function (data) {
  65. return data.name;
  66. });
  67. makeStream('a')
  68. .pipe(aggregator);
  69. makeStream('b')
  70. .pipe(aggregator);
  71. var n = 0;
  72. aggregator
  73. .on('data', function () {
  74. n++;
  75. })
  76. .on('end', function () {
  77. expect(n).to.equal(10);
  78. done();
  79. });
  80. });
  81. it('should be able to handle uniqueness when not piped', function(done) {
  82. var stream = unique();
  83. var count = 0;
  84. stream.on('data', function (data) {
  85. expect(data).to.equal('hello');
  86. count++;
  87. });
  88. stream.on('end', function() {
  89. expect(count).to.equal(1);
  90. done();
  91. });
  92. stream.write('hello');
  93. stream.write('hello');
  94. stream.end();
  95. });
  96. });