1. 程式人生 > 實用技巧 >[Javascript] Broadcaster + Operator + Listener pattern -- 23. ifElse operator

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

So far, we've usedfilterto 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 anifand anelse. Let's take a look at what anifElseoperator 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() } }