Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
Code copyright Dustin Diaz and Ross Harmes, Pro JavaScript Design Patterns.
**/
// Constructor.
var Interface = function (name, methods) {
if (arguments.length != 2) {
throw new Error("Interface constructor called with " + arguments.length + "arguments, but expected exactly 2.");
}
this.name = name;
this.methods = [];
for (var i = 0, len = methods.length; i < len; i++) {
if (typeof methods[i] !== 'string') {
throw new Error("Interface constructor expects method names to be " + "passed in as a string.");
}
this.methods.push(methods[i]);
}
};
// Static class method.
Interface.ensureImplements = function (object) {
if (arguments.length < 2) {
throw new Error("Function Interface.ensureImplements called with " + arguments.length + "arguments, but expected at least 2.");
}
for (var i = 1, len = arguments.length; i < len; i++) {
var interface = arguments[i];
if (interface.constructor !== Interface) {
throw new Error("Function Interface.ensureImplements expects arguments" + "two and above to be instances of Interface.");
}
for (var j = 0, methodsLen = interface.methods.length; j < methodsLen; j++) {
var method = interface.methods[j];
if (!object[method] || typeof object[method] !== 'function') {
throw new Error("Function Interface.ensureImplements: object " + "does not implement the " + interface.name + " interface. Method " + method + " was not found.");
}
}
}
};
@ghost

This comment has been minimized.

Copy link

@ghost ghost commented Jan 20, 2017

Thank you!

@liligot

This comment has been minimized.

Copy link

@liligot liligot commented Oct 1, 2018

Thanks again for your help

@Jeffzholy

This comment has been minimized.

Copy link

@Jeffzholy Jeffzholy commented Jan 20, 2020

👍 👍 👍
Thanks so much for the function implementations, but I just have a little suggestion, maybe improve the quality for the solution? 😃

@Jeffzholy

This comment has been minimized.

Copy link

@Jeffzholy Jeffzholy commented Jan 21, 2020

Sorry for my previous comment, I just realise this solution was coded 9 yrs ago...., just ignore my previous one, anyway thanks!! 👍 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment