zoukankan      html  css  js  c++  java
  • [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()
  • 相关阅读:
    使用eNSP配置灵活QinQ
    使用eNSP配置端口QinQ
    python-多线程编程
    front-end plugin, generate pdf with html5 and jquery
    dotnetnuke peek. glance.
    a
    租房了,说一个奇妙的事情。
    总是容易忘记zen coding里怎么写标签text, mark一下吧
    springboot+druid连接池及监控配置
    springboot +mybatis分页插件PageHelper
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13869674.html
Copyright © 2011-2022 走看看