[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)

 

上一篇:Trademark


下一篇:oss挂载ecs实现文件自动同步