Skip to content

Instantly share code, notes, and snippets.

@Bondifrench
Created May 12, 2017 13:48
Show Gist options
  • Save Bondifrench/5b3bc7f47479402cd667c00bfe3b01a7 to your computer and use it in GitHub Desktop.
Save Bondifrench/5b3bc7f47479402cd667c00bfe3b01a7 to your computer and use it in GitHub Desktop.
Ideas to avoid switch statements when choice of components
const notImplemented = { view: () => m("div", "Not implemented") };
const components = {
"WaveForm": sineBody,
"WebsocketSource" wssBody
};
// ...
return m(".card-body", m(components[vnode.attrs.type] || notImplemented, vnode.attrs));
// or
m('.card-body',
m(components[vnode.attrs.type] || 'div', vnode.attrs, 'Not implemented')
)
// or using FP
const get = (k,o) => [o[k]].filter( x => x != null)
// or
const get = (k,o) => o[k] != null ? [ o[k] ] : []
// and
const maybe = (a, f) => Ma => Ma.map( a => f(a)).concat(a).pop()
// or
const maybe = (a,f) => Ma => Ma.length > 0 ? f(Ma[0]) : a
m('.card-body',
[ get(
vnode.attrs.type
, { Waveform: sineBody
, WebsocketSource: wssBody
}
)]
.map( maybe('Not implemented', a => m( a, vnode.attrs) ) )
.pop()
)
// or
[ get(
vnode.attrs.type
, { Waveform: sineBody
, WebsocketSource: wssBody
}
)]
.map( maybe('Not implemented', a => m( a, vnode.attrs) ) )
.map( a => m('.card-body', a )
// this function a => m(a, vnode.attrs) and this function m('.card-body', a) will come up over and over.
// So let's define some combinators for dealing with these patterns.
const children = (tag, attrs) => children => m(tag, attrs, children)
const tag = (attrs,children) => tag => m(tag, attrs,children)
// For completion we could also have attrs but anyway....
[ get(
vnode.attrs.type
, { Waveform: sineBody
, WebsocketSource: wssBody
}
)]
.map( maybe('Not implemented', tag( vnode.attrs, [])) )
.map( children( '.card-body', {}) )
@Bondifrench
Copy link
Author

Credit @JAForbes and @foxdonut

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment