test_demo.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. 'use strict';
  2. const unit = require('heya-unit');
  3. const {Transform} = require('stream');
  4. const chain = require('../src/index');
  5. const fromIterable = require('../src/utils/fromIterable');
  6. const getTotalFromDatabaseByKey = async x =>
  7. new Promise(resolve => {
  8. setTimeout(() => {
  9. resolve(Math.min(x % 10, 3));
  10. }, 20);
  11. });
  12. unit.add(module, [
  13. function test_demo(t) {
  14. const async = t.startAsync('test_demo');
  15. const c = chain([
  16. // transforms a value
  17. x => x * x,
  18. // returns several values
  19. x => chain.many([x - 1, x, x + 1]),
  20. // waits for an asynchronous operation
  21. async x => await getTotalFromDatabaseByKey(x),
  22. // returns multiple values with a generator
  23. function* (x) {
  24. for (let i = x; i > 0; --i) {
  25. yield i;
  26. }
  27. return 0;
  28. },
  29. // filters out even values
  30. x => (x % 2 ? x : null),
  31. // uses an arbitrary transform stream
  32. new Transform({
  33. objectMode: true,
  34. transform(x, _, callback) {
  35. callback(null, x + 1);
  36. }
  37. })
  38. ]),
  39. output = [];
  40. c.on('data', data => output.push(data));
  41. c.on('end', () => {
  42. eval(t.TEST('t.unify(output, [2, 2, 4, 2, 4, 2, 4, 2, 4, 2, 4, 2])'));
  43. async.done();
  44. });
  45. fromIterable([1, 2, 3]).pipe(c);
  46. },
  47. function test_demoNoGrouping(t) {
  48. const async = t.startAsync('test_demoNoGrouping');
  49. const c = chain([
  50. // transforms a value
  51. x => x * x,
  52. // returns several values
  53. x => chain.many([x - 1, x, x + 1]),
  54. // waits for an asynchronous operation
  55. async x => await getTotalFromDatabaseByKey(x),
  56. // returns multiple values with a generator
  57. function* (x) {
  58. for (let i = x; i > 0; --i) {
  59. yield i;
  60. }
  61. return 0;
  62. },
  63. // filters out even values
  64. x => (x % 2 ? x : null),
  65. // uses an arbitrary transform stream
  66. new Transform({
  67. objectMode: true,
  68. transform(x, _, callback) {
  69. callback(null, x + 1);
  70. }
  71. })
  72. ], {noGrouping: true}),
  73. output = [];
  74. c.on('data', data => output.push(data));
  75. c.on('end', () => {
  76. eval(t.TEST('t.unify(output, [2, 2, 4, 2, 4, 2, 4, 2, 4, 2, 4, 2])'));
  77. async.done();
  78. });
  79. fromIterable([1, 2, 3]).pipe(c);
  80. }
  81. ]);