Guest User

Untitled

a guest
Jan 22nd, 2018
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. //json interpolation for string subs. Just used in shape().
  2. const in_json = (strs, ...vals) =>
  3. strs[0] + vals.map((v, i) => JSON.stringify(v) + strs[i + 1]).join("");
  4.  
  5. // validate shape of an object having appropriate methods.
  6. // PLEASE do this, using if() makes this sort of "that fn doesn't handle this particular event"
  7. // unassertable, and that means that you have whole undebuggable pipelines where "somewhere in
  8. // this pipeline that information gets lost, I don't know where!"
  9. const shape = (obj, ...method_names) => {
  10. const missing_methods = method_names.some(m => typeof obj[m] !== "function");
  11. if (missing_methods) {
  12. throw new Error(
  13. in_json`shape mismatch, expected methods ${method_names}, got methods ${Object.keys(
  14. obj
  15. ).filter(k => typeof obj[k] === "function")}`
  16. );
  17. }
  18. };
  19.  
  20. const mapNext = (source, transform) => {
  21. return {
  22. subscribe(sink) {
  23. const sinkM = {};
  24. Object.keys(sink).forEach(k => (sinkM[k] = val => sink[k](val)));
  25. sinkM.next = data => {
  26. sink.next(transform(data));
  27. };
  28. source.subscribe(sinkM);
  29. }
  30. };
  31. };
  32.  
  33. const interval = {
  34. subscribe(other) {
  35. shape(other, "subscribe", "next");
  36. const handle = setInterval(() => other.next(i++), 1000);
  37. let i = 0;
  38. other.subscribe({
  39. next() {
  40. i = 0;
  41. },
  42. dispose() {
  43. clearInterval(handle);
  44. }
  45. });
  46. // you were also returning dispose() above, but that seems nonidiomatic for this
  47. // sort of code where subscribe() is apparently only important for its side-effects.
  48. }
  49. };
  50.  
  51. const logger = {
  52. subscribe(other) {
  53. shape(other, "next");
  54. setTimeout(() => other.next(), 4500);
  55. },
  56. next(value) {
  57. console.log(value);
  58. }
  59. };
  60.  
  61. interval.subscribe(logger);
Add Comment
Please, Sign In to add comment