Providing default behavior

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 that the second value passed to get() is returned, which in this case is a function that logs 'default'. In practice, this function could be a no-op, or something specific to the application you're building.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.34.87