Skip to content

Instantly share code, notes, and snippets.

@genericallyloud
Last active December 26, 2015 09:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save genericallyloud/7128198 to your computer and use it in GitHub Desktop.
Save genericallyloud/7128198 to your computer and use it in GitHub Desktop.
This is a bit of smaller scope functionality which could be used to implement Protocols and probably some other interesting patterns.

The idea for this is based on Brendan Eichs defineOperator function proposed for value objects, as well as trying to come up with a very narrow scope that can be used to build on top of, but also be possible to optimize. The basic concept is to define functions which can be used for single dispatch based on knowing the type of the receiver. It is the heart of what would be needed for protocols, but with an extremely narrow scope.

let foo = Function.createDispatcher();
Function.defineDispatch(foo,Array,function(){ return this.join(".foo ")); });

[1,2,3]::foo(); //1.foo 2.foo 3.foo
{}::foo(); //ERROR - no match, no default
{foo(){ console.log("Object foo");}}::foo(); //ERROR - doesn't support fall through

//here I pass the default function in
let bar = Function.createDispatcher(function(){
  console.log("default");
});
Function.defineDispatch(bar,Array,function(){ return this.join(".bar ")); });

[1,2,3]::bar(); //1.bar 2.bar 3.bar
{}::bar(); //default
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment