Parameterizing mapped behavior

If you could pass arguments to the behavior that gets invoked when you call your behavior functions, it would be nice. This would mean that your behavior function would have to forward the arguments that it receives to the functions that it looks up from the behavior map:

const log = value => console.log('log:', value);
const myBehavior = (action, ...args) => Map.of(
'start', value => log(`starting ${value}...`),
'stop', value => log(`stopping ${value}...`)
).get(
action,
() => {}
)(...args);

myBehavior('start', 'database');
// -> log: starting database...
myBehavior('start', 'server');
// -> log: starting server...
myBehavior('stop', 'database');
// -> log: stopping database...
myBehavior('stop', 'server');
// -> log: stopping server...

Here, we updated the signature of myBehavior() to include an args rest parameter. It's called a rest parameter because the ... syntax allows args to capture an arbitrary number of arguments if they're passed. Then, we use the spread operator (...) to forward these arguments to the behavior functions once they've been looked up.

In this example, the first argument is used to look up the behavior to execute, and the second string parameter is passed to the behavior function which is then logged.

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

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