Skip to content

Instantly share code, notes, and snippets.

@thejhh
Last active November 3, 2018 17:56
Show Gist options
  • Select an option

  • Save thejhh/ccb97c2565e74f62318d4b49356237f9 to your computer and use it in GitHub Desktop.

Select an option

Save thejhh/ccb97c2565e74f62318d4b49356237f9 to your computer and use it in GitHub Desktop.
"Interface" / Protocols implementation using ES6 and Symbols
// @norjs/Interface is commercial package from https://www.norjs.com
import Interface from '@norjs/Interface';
import listInterface from './listInterface.js';
class FooList {
// `listInterface.getList` is reference to an unique Symbol value for the name of the method.
//
// Using Symbols may look a bit strange, but this makes it possible to use
// any number of interfaces without any name collisions, nor affect the
// way you design your public or internal implementations.
[listInterface.getList] (arg1, arg2) {
return [];
}
}
// As of now, this will only verify that every symbol specified in the interface
// exists in FooList's prototype.
Interface.assert(listInterface, FooList);
export default FooList;
import Interface from '@norjs/Interface';
// This will create most of the things for the interface here and now, including property symbols.
const listInterface = Interface.create({
name: 'list', // This is just for prettier error messages.
methods:{
// Function arguments are not verified yet. As of now there can be anything here.
// You can also use your own Symbol here.
getList: 'function (arg1, arg2)'
}
});
export default listInterface;
import listInterface from './listInterface.js';
import FooList from './FooList.js';
const foo = new FooList();
// You can verify an object, too.
// Of course, if you already verified the class, this probably is unnecessary.
Interface.assert(listInterface, foo);
// ...or an instance of an interface.
Interface.assert(listInterface(foo));
// listInterface(foo) only creates an object with a single hidden property using a class already
// implemented when the Interface was created. It should be quite fast.
const list = listInterface(foo).getList(1, 2);
// Or using directly the symbol:
list = foo[listInterface.getList](1, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment