[Functional Programming] Counter example

document.getElementById("app").innerHTML = `
<h1>Hello Parcel!</h1>
<div>
  <button id="plus">+</button>  
  <button id="mius">-</button>  
</div>
`;

const addListener = (selector, eventType) => (listener) => {
  const element = document.querySelector(selector);
  element.addEventListener(eventType, listener);
};

const plusClick = addListener("#plus", "click");
const miusClick = addListener("#mius", "click");

const hardCode = (newValue) => (broadcaster) => (listener) => {
  return broadcaster((value) => {
    listener(newValue);
  });
};

const plusOne = hardCode(1)(plusClick)
const miusOne = hardCode(-1)(miusClick)

const add = (initial) => broadcaster => listener => {
  return broadcaster((value) => {
    listener(initial += value)
  })
}

const merge = (b1, b2) => listener => {
  b1(listener)
  b2(listener)
}

const counter = add(0)(merge(plusOne, miusOne))
counter(console.log)

 

posted @ 2020-10-29 01:34  Zhentiw  阅读(123)  评论(0编辑  收藏  举报