[Javascript] Broadcaster + Operator + Listener pattern -- 4. Concat

import { compose } from "ramda";
let input = document.getElementById("input");

let inputBroadcaster = (listener) => {
  input.addEventListener("input", listener);

  return () => {
    input.removeEventListener("input", listener);
  };
};

let log = (value) => {
  console.log(value);
};

let getTargetValue = (broadcaster) => (listener) => {
  let stop = broadcaster((event) => {
    listener(event.target.value);
  });
  return stop;
};

let done = Symbol("done'");

let timeout = (listener) => {
  setTimeout(() => {
    listener(done);
  }, 3000);
};
/*
let concat = (firstBroadcaster, secondBroadcaster) => (listener) => {
  firstBroadcaster((value) => {
    if (value === done) {
      secondBroadcaster(listener);
    }
  });
};*/

let concat_forloop = (...broadcastera) => (listener) => {
  broadcastera.forEach((broadcaster, i) => {
    broadcaster((value) => {
      if (value === done && i + 1 <= broadcastera.length - 1) {
        broadcastera[i + 1](listener);
      }
    });
  });
};

let concat_recusive = (...broadcastera) => (listener) => {
  let i = 0;

  let setup = (broadcaster) => {
    broadcaster((value) => {
      if (value === done) {
        ++i <= broadcastera.length - 1
          ? setup(broadcastera[i])
          : listener(done);
      } else {
        listener(value);
      }
    });
  };

  setup(broadcastera[i]);
};

concat_recusive(timeout, inputBroadcaster)(log);

 

posted @ 2020-09-30 18:32  Zhentiw  阅读(164)  评论(0编辑  收藏  举报