[Functional Programming] Match Function Requirements with Lodash Partial and Flip

Functions returning functions returning functions can begin to look a bit unwieldy. The arrow function has helped the syntax a lot, but maybe using a curry utility function to combine all the arguments into a single function will help your syntax look a little cleaner. Currying isn't necessary for our pattern, but you'll definitely see it used in many patterns involving functions returning functions and maybe you'll grow to love it.

 

import { curry, partial, flip } from "lodash"

let createTimeout = curry((time, listener) => {
  let id = setTimeout(listener, time)

  return () => {
    clearTimeout(id)
  }
})

let addListener = curry((selector, eventType, listener) => {
  let element = document.querySelector(selector)
  element.addEventListener(eventType, listener)

  return () => {
    element.removeEventListener(eventType, listener)
  }
})

let createInterval = curry((time, listener) => {
  let id = setInterval(listener, time)
  return () => {
    clearInterval(id)
  }
})

//broadcaster = function that accepts a listener
let merge = curry((broadcaster1, broadcaster2, listener) => {
  let cancel1 = broadcaster1(listener)
  let cancel2 = broadcaster2(listener)

  return () => {
    cancel1()
    cancel2()
  }
})

let clickOrTick = merge(
  // addListener("#button", "click"),
  partial(window.addEventListener, "copy"),
  partial(flip(setInterval), 1000) //setInterval(()=> {}, 1000)
)
let cancelClickOrTick = clickOrTick(() => {
  console.log("click or tick")
})

cancelClickOrTick()

 

posted @ 2020-10-24 15:35  Zhentiw  阅读(130)  评论(0编辑  收藏  举报