[Javascript] Broadcaster + Operator + Listener pattern -- 23. ifElse operator
阿新 • • 發佈:2020-12-06
So far, we've usedfilter
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 anif
and anelse
. Let's take a look at what anifElse
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() } }