[Javascript] Broadcaster + Operator + Listener pattern -- 23. ifElse operator

So far, we've used filter to prevent values when a condition is met. Sometimes you want two different behaviors based on a condition which is where you would naturally reach for an if and an else. Let's take a look at what an ifElse operator would look like in the context of our live search box.

Logic:

let App = () => {
  let onInput = useListener()
  let inputValue = targetValue(onInput)

  let inputToBooks = pipe(
    waitFor(150),
    ifElse(
      // condition
      name => name.length > 3,
      // if
      pipe(
        map(name => `https://openlibrary.org/search.json?q=${name}`),
        mapBroadcaster(getUrl),
        map(json => json.docs)
      ),
      // else
      map(() => [])
  ))(inputValue)
  let books = useBroadcaster(inputToBooks, [])

ifElse:

export let ifElse = (condition, ifOp, elOp) => broadcaster => listener => {
  let cancel = broadcaster(value => {

    if (value === done) {
      return;
    }

    if (condition(value)) {
      ifOp(innerValue => innerValue(value))(listener)
    } else {
      elOp(innerValue => innerValue(value))(listener)
    }
  })

  return () => {
    cancel()
  }
}
原文地址:https://www.cnblogs.com/Answer1215/p/14093562.html