Clojure-inspired multimethods for JavaScript.
Problem statement: JavaScript does not offer native constructs to facilitate the orchestration of functions.
Say we need to generate code that greets someone in a given programming language:
greetings('clojure', 'John');
//=> '(print "Hi John!")'
greetings('shell', 'John');
//=> 'echo "Hi John!"'
Here's one classic implementation:
const greetings = (lang, name) => {
switch (lang) {
case CLOJURE:
return greetings_clojure(name);
case SHELL:
return greetings_shell(name);
default:
throw new Error(`unknown: ${lang}`);
}
};
Let's take a moment to identify the important bits:
- We need some parameters (pink)
- We need a dispatch value to make a decision (yellow)
- We need a "decision tree" (green)
- We need a fallback (orange)
Everything else is just implementation details....
It is these details that multifun
intends to manage so that you can focus on what matters the most:
const multifun = require('@customcommander/multifun');
const xyz =
multifun
( dispatching_fn
, 'xxx', handle_xxx_fn
, 'yyy', handle_yyy_fn
, 'zzz', handle_zzz_fn
// ...
, fallback_fn
);
xyz(...);
Here are the parameters to multifun
:
-
The 1st parameter is the dispatching function.
It takes all the parameters passed toxyz
and returns a value. -
Then you have a serie of value & handler pairs.
If a value is strictly equal to the dispatched value, its handler is applied to the parameters passed toxyz
. (No other pairs will be evaluated.) -
And finally a fallback function if no values matched.
It is applied to the parameters passed toxyz
.