helpers.js 733 B

12345678910111213141516171819202122232425262728293031323334
  1. 'use strict';
  2. const {Readable, Writable} = require('stream');
  3. const streamFromArray = array =>
  4. new Readable({
  5. objectMode: true,
  6. read() {
  7. if (isNaN(this.index)) this.index = 0;
  8. this.push(this.index < array.length ? array[this.index++] : null);
  9. }
  10. });
  11. const streamToArray = array =>
  12. new Writable({
  13. objectMode: true,
  14. write(chunk, encoding, callback) {
  15. array.push(chunk);
  16. callback(null);
  17. }
  18. });
  19. const delay = (fn, ms = 20) => async (...args) =>
  20. new Promise((resolve, reject) => {
  21. setTimeout(() => {
  22. try {
  23. resolve(fn(...args));
  24. } catch (error) {
  25. reject(error);
  26. }
  27. }, ms);
  28. });
  29. module.exports = {streamFromArray, streamToArray, delay};