The preceding example has a couple of limitations. First, there's no way to pass arguments to the behaviors when they're called. Second, if you try to call something that doesn't exist, it blows up. We should be able to address both of these issues.
When the caller attempts to call a behavior that doesn't exist by passing a key that doesn't exist in the behavior map, you should be able to recover from this. Thankfully, the get()
method accepts a second argument that's returned if the requested key doesn't exist:
const myBehavior = action => Map.of( true, () => console.log('thruth'), false, () => console.log('lies') ).get( action, () => console.log('default') )(); myBehavior(true); // -> truth myBehavior(false); // -> lies myBehavior(); // -> default myBehavior(123); // -> default
The last two calls to myBehavior()
result in the default behavior running because neither call is passed a key that exists. This means...