Skip to content

Instantly share code, notes, and snippets.

@timkg
Last active December 17, 2015 06:49
Show Gist options
  • Save timkg/5568259 to your computer and use it in GitHub Desktop.
Save timkg/5568259 to your computer and use it in GitHub Desktop.
A simple implementation of Interfaces in Javascript. Allows you to define Interfaces with a bunch of methods. Defines Function.prototype.implement to be called on constructor functions which want to implement an interface. Throws errors if not all interface methods were declared.
function Interface(methodNames) {
var self = this;
methodNames.forEach(function(name) {
self[name] = function() {
throw new Error('Interface methods should not be called directly. Overwrite with specific implementation details.');
};
});
}
Function.prototype.implement = function(_interface, methodHash) {
var proto = this.prototype = {};
for (var prop in methodHash) {
if (typeof methodHash[prop] === 'function') {
proto[prop] = methodHash[prop];
}
}
for (var prop in _interface) {
if (typeof _interface[prop] === 'function') {
try {
proto[prop]();
} catch (e) {
throw new Error('Did not declare Interface method named ' + prop + '. Go back and declare this method.');
}
}
}
}
var UserRepo = new Interface(['get', 'save', 'edit', 'getAll']);
function UserRepoRedis() {
// implementation-sepcific details
}
UserRepoRedis.implement(UserRepo, {
get: function() {}
, save: function() {}
, edit: function() {}
, getAll: function() {}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment