test_demo.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. 'use strict';
  2. const unit = require('heya-unit');
  3. const Chain = require('../index');
  4. const {streamFromArray} = require('./helpers');
  5. const {Transform} = require('stream');
  6. unit.add(module, [
  7. function test_demo(t) {
  8. const async = t.startAsync('test_demo');
  9. const getTotalFromDatabaseByKey = async x =>
  10. new Promise(resolve => {
  11. setTimeout(() => {
  12. resolve(Math.min(x % 10, 3));
  13. }, 20);
  14. });
  15. const chain = new Chain([
  16. // transforms a value
  17. x => x * x,
  18. // returns several values
  19. x => [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. chain.on('data', data => output.push(data));
  41. chain.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. streamFromArray([1, 2, 3]).pipe(chain);
  46. }
  47. ]);